Merge "Extend job list when inheriting jobs" into feature/zuulv3
diff --git a/.zuul.yaml b/.zuul.yaml
index 0ae5beb..c21b30f 100644
--- a/.zuul.yaml
+++ b/.zuul.yaml
@@ -6,4 +6,5 @@
         - tox-cover
         - tox-linters
         - tox-py27
+        - tox-py35
         - tox-tarball
diff --git a/bindep.txt b/bindep.txt
index 6895444..5db144b 100644
--- a/bindep.txt
+++ b/bindep.txt
@@ -14,3 +14,4 @@
 libffi-devel [platform:rpm]
 python-dev [platform:dpkg]
 python-devel [platform:rpm]
+bubblewrap [platform:rpm]
diff --git a/doc/source/connections.rst b/doc/source/connections.rst
index 7b302e9..120d529 100644
--- a/doc/source/connections.rst
+++ b/doc/source/connections.rst
@@ -87,6 +87,11 @@
   Path to SSH key to use when cloning github repositories.
   ``sshkey=/home/zuul/.ssh/id_rsa``
 
+**git_host**
+  Optional: Hostname of the github install (such as a GitHub Enterprise)
+  If not specified, defaults to ``github.com``
+  ``git_host=github.myenterprise.com``
+
 SMTP
 ----
 
diff --git a/doc/source/developer/datamodel.rst b/doc/source/developer/datamodel.rst
index 2996ff4..acb8612 100644
--- a/doc/source/developer/datamodel.rst
+++ b/doc/source/developer/datamodel.rst
@@ -54,7 +54,7 @@
 Filters
 ~~~~~~~
 
-.. autoclass:: zuul.model.ChangeishFilter
+.. autoclass:: zuul.model.RefFilter
 .. autoclass:: zuul.model.EventFilter
 
 
diff --git a/doc/source/triggers.rst b/doc/source/triggers.rst
index 07b18ab..41a56a0 100644
--- a/doc/source/triggers.rst
+++ b/doc/source/triggers.rst
@@ -109,7 +109,10 @@
 following options.
 
   **event**
-  The pull request event from github. A ``pull_request`` event will
+  The event from github. Supported events are ``pull_request``,
+  ``pull_request_review``,  and ``push``.
+
+  A ``pull_request`` event will
   have associated action(s) to trigger from. The supported actions are:
 
     *opened* - pull request opened
@@ -126,32 +129,54 @@
 
     *unlabeled* - label removed from pull request
 
+    *review* - review added on pull request
+
     *push* - head reference updated (pushed to branch)
 
+    *status* - status set on commit
+
+  A ``pull_request_review`` event will
+  have associated action(s) to trigger from. The supported actions are:
+
+    *submitted* - pull request review added
+
+    *dismissed* - pull request review removed
+
   **branch**
   The branch associated with the event. Example: ``master``.  This
   field is treated as a regular expression, and multiple branches may
-  be listed. Used for ``pull-request`` events.
+  be listed. Used for ``pull_request`` and ``pull_request_review`` events.
 
   **comment**
-  This is only used for ``pull_request`` ``comment`` events.  It accepts a list
-  of regexes that are searched for in the comment string. If any of these
+  This is only used for ``pull_request`` ``comment`` actions.  It accepts a
+  list of regexes that are searched for in the comment string. If any of these
   regexes matches a portion of the comment string the trigger is matched.
   ``comment: retrigger`` will match when comments containing 'retrigger'
   somewhere in the comment text are added to a pull request.
 
   **label**
-  This is only used for ``labeled`` and ``unlabeled`` actions. It accepts a list
-  of strings each of which matches the label name in the event literally.
-  ``label: recheck`` will match a ``labeled`` action when pull request is
-  labeled with a ``recheck`` label. ``label: 'do not test'`` will match a
-  ``unlabeled`` action when a label with name ``do not test`` is removed from
-  the pull request.
+  This is only used for ``labeled`` and ``unlabeled`` ``pull_request`` actions.
+  It accepts a list of strings each of which matches the label name in the
+  event literally.  ``label: recheck`` will match a ``labeled`` action when
+  pull request is labeled with a ``recheck`` label. ``label: 'do not test'``
+  will match a ``unlabeled`` action when a label with name ``do not test`` is
+  removed from the pull request.
 
-  Additionally a ``push`` event can be configured, with an ``ref`` field. This
-  field is treated as a regular expression and multiple refs may be listed.
-  Github always sends full ref name, eg. ``refs/tags/bar`` and this string is
-  matched against the regexp.
+  **state**
+  This is only used for ``pull_request_review`` events.  It accepts a list of
+  strings each of which is matched to the review state, which can be one of
+  ``approved``, ``comment``, or ``request_changes``.
+
+  **status**
+  This is only used for ``status`` actions. It accepts a list of strings each of
+  which matches the user setting the status, the status context, and the status
+  itself in the format of ``user:context:status``.  For example,
+  ``zuul_github_ci_bot:check_pipeline:success``.
+
+  **ref**
+  This is only used for ``push`` events. This field is treated as a regular
+  expression and multiple refs may be listed. Github always sends full ref
+  name, eg. ``refs/tags/bar`` and this string is matched against the regexp.
 
 GitHub Configuration
 ~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/zuul.rst b/doc/source/zuul.rst
index 56cc6a8..a78a0fa 100644
--- a/doc/source/zuul.rst
+++ b/doc/source/zuul.rst
@@ -108,6 +108,10 @@
   commands.
   ``state_dir=/var/lib/zuul``
 
+**jobroot_dir**
+  Path to directory that Zuul should store temporary job files.
+  ``jobroot_dir=/tmp``
+
 **report_times**
   Boolean value (``true`` or ``false``) that determines if Zuul should
   include elapsed times for each job in the textual report.  Used by
@@ -165,6 +169,29 @@
   Path to PID lock file for the merger process.
   ``pidfile=/var/run/zuul-merger/merger.pid``
 
+executor
+""""""""
+
+The zuul-executor process configuration.
+
+**git_dir**
+  Directory that Zuul should clone local git repositories to.
+  ``git_dir=/var/lib/zuul/git``
+
+**log_config**
+  Path to log config file for the executor process.
+  ``log_config=/etc/zuul/logging.yaml``
+
+**private_key_file**
+  SSH private key file to be used when logging into worker nodes.
+  ``private_key_file=~/.ssh/id_rsa``
+
+**user**
+  User ID for the zuul-executor process. In normal operation as a daemon,
+  the executor should be started as the ``root`` user, but it will drop
+  privileges to this user during startup.
+  ``user=zuul``
+
 .. _connection:
 
 connection ArbitraryName
diff --git a/etc/status/public_html/index.html b/etc/status/public_html/index.html
index 97025a6..cc3d40a 100644
--- a/etc/status/public_html/index.html
+++ b/etc/status/public_html/index.html
@@ -30,8 +30,10 @@
     <script src="jquery.zuul.js"></script>
     <script src="zuul.app.js"></script>
     <script>
+        // @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt Apache 2.0
         zuul_build_dom(jQuery, '#zuul_container');
         zuul_start(jQuery);
+	// @license-end
     </script>
 </body>
 </html>
diff --git a/etc/status/public_html/jquery.zuul.js b/etc/status/public_html/jquery.zuul.js
index d973948..aec7a46 100644
--- a/etc/status/public_html/jquery.zuul.js
+++ b/etc/status/public_html/jquery.zuul.js
@@ -1,5 +1,8 @@
 // jquery plugin for Zuul status page
 //
+// @licstart  The following is the entire license notice for the
+// JavaScript code in this page.
+//
 // Copyright 2012 OpenStack Foundation
 // Copyright 2013 Timo Tijhof
 // Copyright 2013 Wikimedia Foundation
@@ -16,6 +19,9 @@
 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 // License for the specific language governing permissions and limitations
 // under the License.
+//
+// @licend  The above is the entire license notice
+// for the JavaScript code in this page.
 
 (function ($) {
     'use strict';
@@ -52,6 +58,10 @@
 
         var collapsed_exceptions = [];
         var current_filter = read_cookie('zuul_filter_string', '');
+        var change_set_in_url = window.location.href.split('#')[1];
+        if (change_set_in_url) {
+           current_filter = change_set_in_url;
+        }
         var $jq;
 
         var xhr,
@@ -269,7 +279,16 @@
 
                 var $change_link = $('<small />');
                 if (change.url !== null) {
-                    if (/^[0-9a-f]{40}$/.test(change.id)) {
+                    var github_id = change.id.match(/^([0-9]+),([0-9a-f]{40})$/);
+                    if (github_id) {
+                        $change_link.append(
+                            $('<a />').attr('href', change.url).append(
+                                $('<abbr />')
+                                    .attr('title', change.id)
+                                    .text('#' + github_id[1])
+                            )
+                        );
+                    } else if (/^[0-9a-f]{40}$/.test(change.id)) {
                         var change_id_short = change.id.slice(0, 7);
                         $change_link.append(
                             $('<a />').attr('href', change.url).append(
diff --git a/etc/status/public_html/zuul.app.js b/etc/status/public_html/zuul.app.js
index 6321af8..ae950e8 100644
--- a/etc/status/public_html/zuul.app.js
+++ b/etc/status/public_html/zuul.app.js
@@ -1,5 +1,8 @@
 // Client script for Zuul status page
 //
+// @licstart  The following is the entire license notice for the
+// JavaScript code in this page.
+//
 // Copyright 2013 OpenStack Foundation
 // Copyright 2013 Timo Tijhof
 // Copyright 2013 Wikimedia Foundation
@@ -16,6 +19,9 @@
 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 // License for the specific language governing permissions and limitations
 // under the License.
+//
+// @licend  The above is the entire license notice
+// for the JavaScript code in this page.
 
 /*exported zuul_build_dom, zuul_start */
 
diff --git a/requirements.txt b/requirements.txt
index 2fe6963..746bbcb 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,8 @@
 pbr>=1.1.0
 
-Github3.py==1.0.0a2
+# pull from master until https://github.com/sigmavirus24/github3.py/pull/671
+# is in a release
+-e git+https://github.com/sigmavirus24/github3.py.git@develop#egg=Github3.py
 PyYAML>=3.1.0
 Paste
 WebOb>=1.2.3
@@ -11,7 +13,7 @@
 extras
 statsd>=1.0.0,<3.0
 voluptuous>=0.10.2
-gear>=0.5.7,<1.0.0
+gear>=0.9.0,<1.0.0
 apscheduler>=3.0
 PrettyTable>=0.6,<0.8
 babel>=1.0
@@ -21,3 +23,6 @@
 sqlalchemy
 alembic
 cryptography>=1.6
+cachecontrol
+pyjwt
+iso8601
diff --git a/test-requirements.txt b/test-requirements.txt
index 735b4dd..baf6cad 100644
--- a/test-requirements.txt
+++ b/test-requirements.txt
@@ -1,4 +1,6 @@
-hacking>=0.12.0,!=0.13.0,<0.14  # Apache-2.0
+pep8
+pyflakes
+flake8
 
 coverage>=3.6
 sphinx>=1.5.1,<1.6
diff --git a/tests/base.py b/tests/base.py
index 77c0644..faf9ef3 100755
--- a/tests/base.py
+++ b/tests/base.py
@@ -16,6 +16,7 @@
 # under the License.
 
 from six.moves import configparser as ConfigParser
+import datetime
 import gc
 import hashlib
 import json
@@ -90,7 +91,7 @@
 
 
 def random_sha1():
-    return hashlib.sha1(str(random.random())).hexdigest()
+    return hashlib.sha1(str(random.random()).encode('ascii')).hexdigest()
 
 
 def iterate_timeout(max_seconds, purpose):
@@ -496,11 +497,6 @@
             if cat != 'submit':
                 change.addApproval(cat, action[cat], username=self.user)
 
-        # TODOv3(jeblair): can this be removed?
-        if 'label' in action:
-            parts = action['label'].split('=')
-            change.addApproval(parts[0], parts[2], username=self.user)
-
         change.messages.append(message)
 
         if 'submit' in action:
@@ -547,7 +543,8 @@
 class FakeGithubPullRequest(object):
 
     def __init__(self, github, number, project, branch,
-                 subject, upstream_root, number_of_commits=1):
+                 subject, upstream_root, files=[], number_of_commits=1,
+                 writers=[]):
         """Creates a new PR with several commits.
         Sends an event about opened PR."""
         self.github = github
@@ -558,27 +555,30 @@
         self.subject = subject
         self.number_of_commits = 0
         self.upstream_root = upstream_root
+        self.files = []
         self.comments = []
         self.labels = []
         self.statuses = {}
+        self.reviews = []
+        self.writers = []
         self.updated_at = None
         self.head_sha = None
         self.is_merged = False
+        self.merge_message = None
+        self.state = 'open'
         self._createPRRef()
-        self._addCommitToRepo()
+        self._addCommitToRepo(files=files)
         self._updateTimeStamp()
 
-    def addCommit(self):
+    def addCommit(self, files=[]):
         """Adds a commit on top of the actual PR head."""
-        self._addCommitToRepo()
+        self._addCommitToRepo(files=files)
         self._updateTimeStamp()
-        self._clearStatuses()
 
-    def forcePush(self):
+    def forcePush(self, files=[]):
         """Clears actual commits and add a commit on top of the base."""
-        self._addCommitToRepo(reset=True)
+        self._addCommitToRepo(files=files, reset=True)
         self._updateTimeStamp()
-        self._clearStatuses()
 
     def getPullRequestOpenedEvent(self):
         return self._getPullRequestEvent('opened')
@@ -608,6 +608,39 @@
             },
             'repository': {
                 'full_name': self.project
+            },
+            'sender': {
+                'login': 'ghuser'
+            }
+        }
+        return (name, data)
+
+    def getReviewAddedEvent(self, review):
+        name = 'pull_request_review'
+        data = {
+            'action': 'submitted',
+            'pull_request': {
+                'number': self.number,
+                'title': self.subject,
+                'updated_at': self.updated_at,
+                'base': {
+                    'ref': self.branch,
+                    'repo': {
+                        'full_name': self.project
+                    }
+                },
+                'head': {
+                    'sha': self.head_sha
+                }
+            },
+            'review': {
+                'state': review
+            },
+            'repository': {
+                'full_name': self.project
+            },
+            'sender': {
+                'login': 'ghuser'
             }
         }
         return (name, data)
@@ -643,6 +676,9 @@
             },
             'label': {
                 'name': label
+            },
+            'sender': {
+                'login': 'ghuser'
             }
         }
         return (name, data)
@@ -653,6 +689,7 @@
             'action': 'unlabeled',
             'pull_request': {
                 'number': self.number,
+                'title': self.subject,
                 'updated_at': self.updated_at,
                 'base': {
                     'ref': self.branch,
@@ -661,11 +698,17 @@
                     }
                 },
                 'head': {
-                    'sha': self.head_sha
+                    'sha': self.head_sha,
+                    'repo': {
+                        'full_name': self.project
+                    }
                 }
             },
             'label': {
                 'name': label
+            },
+            'sender': {
+                'login': 'ghuser'
             }
         }
         return (name, data)
@@ -679,7 +722,7 @@
         GithubChangeReference.create(
             repo, self._getPRReference(), 'refs/tags/init')
 
-    def _addCommitToRepo(self, reset=False):
+    def _addCommitToRepo(self, files=[], reset=False):
         repo = self._getRepo()
         ref = repo.references[self._getPRReference()]
         if reset:
@@ -690,7 +733,12 @@
         zuul.merger.merger.reset_repo_to_head(repo)
         repo.git.clean('-x', '-f', '-d')
 
-        fn = '%s-%s' % (self.branch.replace('/', '_'), self.number)
+        if files:
+            fn = files[0]
+            self.files = files
+        else:
+            fn = '%s-%s' % (self.branch.replace('/', '_'), self.number)
+            self.files = [fn]
         msg = self.subject + '-' + str(self.number_of_commits)
         fn = os.path.join(repo.working_dir, fn)
         f = open(fn, 'w')
@@ -700,6 +748,9 @@
         repo.index.add([fn])
 
         self.head_sha = repo.index.commit(msg).hexsha
+        # Create an empty set of statuses for the given sha,
+        # each sha on a PR may have a status set on it
+        self.statuses[self.head_sha] = []
         repo.head.reference = 'master'
         zuul.merger.merger.reset_repo_to_head(repo)
         repo.git.clean('-x', '-f', '-d')
@@ -712,15 +763,54 @@
         repo = self._getRepo()
         return repo.references[self._getPRReference()].commit.hexsha
 
-    def setStatus(self, state, url, description, context):
-        self.statuses[context] = {
+    def setStatus(self, sha, state, url, description, context, user='zuul'):
+        # Since we're bypassing github API, which would require a user, we
+        # hard set the user as 'zuul' here.
+        # insert the status at the top of the list, to simulate that it
+        # is the most recent set status
+        self.statuses[sha].insert(0, ({
             'state': state,
             'url': url,
-            'description': description
-        }
+            'description': description,
+            'context': context,
+            'creator': {
+                'login': user
+            }
+        }))
 
-    def _clearStatuses(self):
-        self.statuses = {}
+    def addReview(self, user, state, granted_on=None):
+        gh_time_format = '%Y-%m-%dT%H:%M:%SZ'
+        # convert the timestamp to a str format that would be returned
+        # from github as 'submitted_at' in the API response
+
+        if granted_on:
+            granted_on = datetime.datetime.utcfromtimestamp(granted_on)
+            submitted_at = time.strftime(
+                gh_time_format, granted_on.timetuple())
+        else:
+            # github timestamps only down to the second, so we need to make
+            # sure reviews that tests add appear to be added over a period of
+            # time in the past and not all at once.
+            if not self.reviews:
+                # the first review happens 10 mins ago
+                offset = 600
+            else:
+                # subsequent reviews happen 1 minute closer to now
+                offset = 600 - (len(self.reviews) * 60)
+
+            granted_on = datetime.datetime.utcfromtimestamp(
+                time.time() - offset)
+            submitted_at = time.strftime(
+                gh_time_format, granted_on.timetuple())
+
+        self.reviews.append({
+            'state': state,
+            'user': {
+                'login': user,
+                'email': user + "@derp.com",
+            },
+            'submitted_at': submitted_at,
+        })
 
     def _getPRReference(self):
         return '%s/head' % self.number
@@ -732,6 +822,7 @@
             'number': self.number,
             'pull_request': {
                 'number': self.number,
+                'title': self.subject,
                 'updated_at': self.updated_at,
                 'base': {
                     'ref': self.branch,
@@ -740,8 +831,29 @@
                     }
                 },
                 'head': {
-                    'sha': self.head_sha
+                    'sha': self.head_sha,
+                    'repo': {
+                        'full_name': self.project
+                    }
                 }
+            },
+            'sender': {
+                'login': 'ghuser'
+            }
+        }
+        return (name, data)
+
+    def getCommitStatusEvent(self, context, state='success', user='zuul'):
+        name = 'status'
+        data = {
+            'state': state,
+            'sha': self.head_sha,
+            'description': 'Test results for %s: %s' % (self.head_sha, state),
+            'target_url': 'http://zuul/%s' % self.head_sha,
+            'branches': [],
+            'context': context,
+            'sender': {
+                'login': user
             }
         }
         return (name, data)
@@ -761,10 +873,11 @@
         self.merge_failure = False
         self.merge_not_allowed_count = 0
 
-    def openFakePullRequest(self, project, branch, subject):
+    def openFakePullRequest(self, project, branch, subject, files=[]):
         self.pr_number += 1
         pull_request = FakeGithubPullRequest(
-            self, self.pr_number, project, branch, subject, self.upstream_root)
+            self, self.pr_number, project, branch, subject, self.upstream_root,
+            files=files)
         self.pull_requests.append(pull_request)
         return pull_request
 
@@ -788,7 +901,7 @@
         """Emulates sending the GitHub webhook event to the connection."""
         port = self.webapp.server.socket.getsockname()[1]
         name, data = event
-        payload = json.dumps(data)
+        payload = json.dumps(data).encode('utf8')
         headers = {'X-Github-Event': name}
         req = urllib.request.Request(
             'http://localhost:%s/connection/%s/payload'
@@ -800,6 +913,7 @@
         pr = self.pull_requests[number - 1]
         data = {
             'number': number,
+            'title': pr.subject,
             'updated_at': pr.updated_at,
             'base': {
                 'repo': {
@@ -808,12 +922,49 @@
                 'ref': pr.branch,
             },
             'mergeable': True,
+            'state': pr.state,
             'head': {
-                'sha': pr.head_sha
+                'sha': pr.head_sha,
+                'repo': {
+                    'full_name': pr.project
+                }
             }
         }
         return data
 
+    def getPullBySha(self, sha):
+        prs = list(set([p for p in self.pull_requests if sha == p.head_sha]))
+        if len(prs) > 1:
+            raise Exception('Multiple pulls found with head sha: %s' % sha)
+        pr = prs[0]
+        return self.getPull(pr.project, pr.number)
+
+    def getPullFileNames(self, project, number):
+        pr = self.pull_requests[number - 1]
+        return pr.files
+
+    def _getPullReviews(self, owner, project, number):
+        pr = self.pull_requests[number - 1]
+        return pr.reviews
+
+    def getUser(self, login):
+        data = {
+            'username': login,
+            'name': 'Github User',
+            'email': 'github.user@example.com'
+        }
+        return data
+
+    def getRepoPermission(self, project, login):
+        owner, proj = project.split('/')
+        for pr in self.pull_requests:
+            pr_owner, pr_project = pr.project.split('/')
+            if (pr_owner == owner and proj == pr_project):
+                if login in pr.writers:
+                    return 'write'
+                else:
+                    return 'read'
+
     def getGitUrl(self, project):
         return os.path.join(self.upstream_root, str(project))
 
@@ -830,7 +981,7 @@
         pull_request = self.pull_requests[pr_number - 1]
         pull_request.addComment(message)
 
-    def mergePull(self, project, pr_number, sha=None):
+    def mergePull(self, project, pr_number, commit_message='', sha=None):
         pull_request = self.pull_requests[pr_number - 1]
         if self.merge_failure:
             raise Exception('Pull request was not merged')
@@ -839,6 +990,19 @@
             raise MergeFailure('Merge was not successful due to mergeability'
                                ' conflict')
         pull_request.is_merged = True
+        pull_request.merge_message = commit_message
+
+    def getCommitStatuses(self, project, sha):
+        owner, proj = project.split('/')
+        for pr in self.pull_requests:
+            pr_owner, pr_project = pr.project.split('/')
+            # This is somewhat risky, if the same commit exists in multiple
+            # PRs, we might grab the wrong one that doesn't have a status
+            # that is expected to be there. Maybe re-work this so that there
+            # is a global registry of commit statuses like with github.
+            if (pr_owner == owner and pr_project == proj and
+                sha in pr.statuses):
+                return pr.statuses[sha]
 
     def setCommitStatus(self, project, sha, state,
                         url='', description='', context=''):
@@ -847,7 +1011,7 @@
             pr_owner, pr_project = pr.project.split('/')
             if (pr_owner == owner and pr_project == proj and
                 pr.head_sha == sha):
-                pr.setStatus(state, url, description, context)
+                pr.setStatus(sha, state, url, description, context)
 
     def labelPull(self, project, pr_number, label):
         pull_request = self.pull_requests[pr_number - 1]
@@ -915,7 +1079,7 @@
                     return
 
     def stop(self):
-        os.write(self.wake_write, '1\n')
+        os.write(self.wake_write, b'1\n')
 
 
 class FakeBuild(object):
@@ -1128,9 +1292,10 @@
 
 
 class RecordingAnsibleJob(zuul.executor.server.AnsibleJob):
-    def doMergeChanges(self, items):
+    def doMergeChanges(self, items, repo_state):
         # Get a merger in order to update the repos involved in this job.
-        commit = super(RecordingAnsibleJob, self).doMergeChanges(items)
+        commit = super(RecordingAnsibleJob, self).doMergeChanges(
+            items, repo_state)
         if not commit:  # merge conflict
             self.recordResult('MERGER_FAILURE')
         return commit
@@ -1199,7 +1364,7 @@
         for queue in [self.high_queue, self.normal_queue, self.low_queue]:
             for job in queue:
                 if not hasattr(job, 'waiting'):
-                    if job.name.startswith('executor:execute'):
+                    if job.name.startswith(b'executor:execute'):
                         job.waiting = self.hold_jobs_in_queue
                     else:
                         job.waiting = False
@@ -1226,9 +1391,9 @@
                 len(self.low_queue))
         self.log.debug("releasing queued job %s (%s)" % (regex, qlen))
         for job in self.getQueue():
-            if job.name != 'executor:execute':
+            if job.name != b'executor:execute':
                 continue
-            parameters = json.loads(job.arguments)
+            parameters = json.loads(job.arguments.decode('utf8'))
             if not regex or re.match(regex, parameters.get('job')):
                 self.log.debug("releasing queued job %s" %
                                job.unique)
@@ -1298,7 +1463,10 @@
 
     def run(self):
         while self._running:
-            self._run()
+            try:
+                self._run()
+            except Exception:
+                self.log.exception("Error in fake nodepool:")
             time.sleep(0.1)
 
     def _run(self):
@@ -1317,7 +1485,7 @@
             path = self.REQUEST_ROOT + '/' + oid
             try:
                 data, stat = self.client.get(path)
-                data = json.loads(data)
+                data = json.loads(data.decode('utf8'))
                 data['_oid'] = oid
                 reqs.append(data)
             except kazoo.exceptions.NoNodeError:
@@ -1333,7 +1501,7 @@
         for oid in sorted(nodeids):
             path = self.NODE_ROOT + '/' + oid
             data, stat = self.client.get(path)
-            data = json.loads(data)
+            data = json.loads(data.decode('utf8'))
             data['_oid'] = oid
             try:
                 lockfiles = self.client.get_children(path + '/lock')
@@ -1365,7 +1533,7 @@
                     image_id=None,
                     host_keys=["fake-key1", "fake-key2"],
                     executor='fake-nodepool')
-        data = json.dumps(data)
+        data = json.dumps(data).encode('utf8')
         path = self.client.create(path, data,
                                   makepath=True,
                                   sequence=True)
@@ -1394,9 +1562,12 @@
 
         request['state_time'] = time.time()
         path = self.REQUEST_ROOT + '/' + oid
-        data = json.dumps(request)
+        data = json.dumps(request).encode('utf8')
         self.log.debug("Fulfilling node request: %s %s" % (oid, data))
-        self.client.set(path, data)
+        try:
+            self.client.set(path, data)
+        except kazoo.exceptions.NoNodeError:
+            self.log.debug("Node request %s %s disappeared" % (oid, data))
 
 
 class ChrootedKazooFixture(fixtures.Fixture):
@@ -1534,6 +1705,18 @@
         else:
             self._log_stream = sys.stdout
 
+        # NOTE(jeblair): this is temporary extra debugging to try to
+        # track down a possible leak.
+        orig_git_repo_init = git.Repo.__init__
+
+        def git_repo_init(myself, *args, **kw):
+            orig_git_repo_init(myself, *args, **kw)
+            self.log.debug("Created git repo 0x%x %s" %
+                           (id(myself), repr(myself)))
+
+        self.useFixture(fixtures.MonkeyPatch('git.Repo.__init__',
+                                             git_repo_init))
+
         handler = logging.StreamHandler(self._log_stream)
         formatter = logging.Formatter('%(asctime)s %(name)-32s '
                                       '%(levelname)-8s %(message)s')
@@ -1555,7 +1738,7 @@
         # from libraries that zuul depends on such as gear.
         log_defaults_from_env = os.environ.get(
             'OS_LOG_DEFAULTS',
-            'git.cmd=INFO,kazoo.client=WARNING,gear=INFO')
+            'git.cmd=INFO,kazoo.client=WARNING,gear=INFO,paste=INFO')
 
         if log_defaults_from_env:
             for default in log_defaults_from_env.split(','):
@@ -1710,8 +1893,6 @@
         old_urlopen = urllib.request.urlopen
         urllib.request.urlopen = URLOpenerFactory
 
-        self._startMerger()
-
         self.executor_server = RecordingExecutorServer(
             self.config, self.connections,
             jobdir_root=self.test_root,
@@ -1754,7 +1935,7 @@
         self.sched.reconfigure(self.config)
         self.sched.resume()
 
-    def configure_connections(self):
+    def configure_connections(self, source_only=False):
         # Set up gerrit related fakes
         # Set a changes database so multiple FakeGerrit's can report back to
         # a virtual canonical database given by the configured hostname
@@ -1797,7 +1978,7 @@
 
         # Register connections from the config using fakes
         self.connections = zuul.lib.connections.ConnectionRegistry()
-        self.connections.configure(self.config)
+        self.connections.configure(self.config, source_only=source_only)
 
     def setup_config(self):
         # This creates the per-test configuration object.  It can be
@@ -1862,7 +2043,7 @@
                     'source': {driver:
                                {'config-projects': ['common-config'],
                                 'untrusted-projects': untrusted_projects}}}}]
-        f.write(yaml.dump(config))
+        f.write(yaml.dump(config).encode('utf8'))
         f.close()
         self.config.set('zuul', 'tenant_config',
                         os.path.join(FIXTURE_DIR, f.name))
@@ -1962,12 +2143,19 @@
         self.assertEqual({}, self.executor_server.job_workers)
         # Make sure that git.Repo objects have been garbage collected.
         repos = []
+        gc.disable()
         gc.collect()
         for obj in gc.get_objects():
             if isinstance(obj, git.Repo):
-                self.log.debug("Leaked git repo object: %s" % repr(obj))
+                self.log.debug("Leaked git repo object: 0x%x %s" %
+                               (id(obj), repr(obj)))
+                for ref in gc.get_referrers(obj):
+                    self.log.debug("  Referrer %s" % (repr(ref)))
                 repos.append(obj)
-        self.assertEqual(len(repos), 0)
+        if repos:
+            for obj in gc.garbage:
+                self.log.debug("  Garbage %s" % (repr(obj)))
+        gc.enable()
         self.assertEmptyQueues()
         self.assertNodepoolState()
         self.assertNoGeneratedKeys()
@@ -1980,8 +2168,6 @@
     def shutdown(self):
         self.log.debug("Shutting down after tests")
         self.executor_client.stop()
-        self.merge_server.stop()
-        self.merge_server.join()
         self.merge_client.stop()
         self.executor_server.stop()
         self.sched.stop()
@@ -1996,10 +2182,17 @@
         self.fake_nodepool.stop()
         self.zk.disconnect()
         self.printHistory()
-        # we whitelist watchdog threads as they have relatively long delays
+        # We whitelist watchdog threads as they have relatively long delays
         # before noticing they should exit, but they should exit on their own.
+        # Further the pydevd threads also need to be whitelisted so debugging
+        # e.g. in PyCharm is possible without breaking shutdown.
+        whitelist = ['executor-watchdog',
+                     'pydevd.CommandThread',
+                     'pydevd.Reader',
+                     'pydevd.Writer',
+                     ]
         threads = [t for t in threading.enumerate()
-                   if t.name != 'executor-watchdog']
+                   if t.name not in whitelist]
         if len(threads) > 1:
             log_str = ""
             for thread_id, stack_frame in sys._current_frames().items():
@@ -2136,8 +2329,9 @@
             if build.url is None:
                 self.log.debug("%s has not reported start" % build)
                 return False
+            # using internal ServerJob which offers no Text interface
             worker_build = self.executor_server.job_builds.get(
-                server_job.unique)
+                server_job.unique.decode('utf8'))
             if worker_build:
                 if worker_build.isWaiting():
                     continue
@@ -2216,7 +2410,7 @@
 
     def countJobResults(self, jobs, result):
         jobs = filter(lambda x: x.result == result, jobs)
-        return len(jobs)
+        return len(list(jobs))
 
     def getJobFromHistory(self, name, project=None):
         for job in self.history:
@@ -2241,7 +2435,7 @@
         start = time.time()
         while time.time() < (start + 5):
             for stat in self.statsd.stats:
-                k, v = stat.split(':')
+                k, v = stat.decode('utf-8').split(':')
                 if key == k:
                     if value is None and kind is None:
                         return
diff --git a/tests/encrypt_secret.py b/tests/encrypt_secret.py
index b8524a0..0b0cf19 100644
--- a/tests/encrypt_secret.py
+++ b/tests/encrypt_secret.py
@@ -30,5 +30,6 @@
     ciphertext = encryption.encrypt_pkcs1_oaep(sys.argv[1], public_key)
     print(ciphertext.encode('base64'))
 
+
 if __name__ == '__main__':
     main()
diff --git a/tests/fixtures/config/multi-driver/git/common-config/playbooks/project-gerrit.yaml b/tests/fixtures/config/multi-driver/git/common-config/playbooks/project-gerrit.yaml
new file mode 100644
index 0000000..f679dce
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/git/common-config/playbooks/project-gerrit.yaml
@@ -0,0 +1,2 @@
+- hosts: all
+  tasks: []
diff --git a/tests/fixtures/config/multi-driver/git/common-config/playbooks/project1-github.yaml b/tests/fixtures/config/multi-driver/git/common-config/playbooks/project1-github.yaml
new file mode 100644
index 0000000..f679dce
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/git/common-config/playbooks/project1-github.yaml
@@ -0,0 +1,2 @@
+- hosts: all
+  tasks: []
diff --git a/tests/fixtures/config/multi-driver/git/common-config/zuul.yaml b/tests/fixtures/config/multi-driver/git/common-config/zuul.yaml
new file mode 100644
index 0000000..2dab845
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/git/common-config/zuul.yaml
@@ -0,0 +1,46 @@
+- pipeline:
+    name: check_github
+    manager: independent
+    trigger:
+      github:
+        - event: pull_request
+          action:
+            - opened
+            - changed
+            - reopened
+    success:
+      github:
+        status: 'success'
+    failure:
+      github:
+        status: 'failure'
+
+- pipeline:
+    name: check_gerrit
+    manager: independent
+    trigger:
+      gerrit:
+        - event: patchset-created
+    success:
+      gerrit:
+        verify: 1
+    failure:
+      gerrit:
+        verify: 1
+
+- job:
+    name: project-gerrit
+- job:
+    name: project1-github
+
+- project:
+    name: org/project
+    check_gerrit:
+      jobs:
+        - project-gerrit
+
+- project:
+    name: org/project1
+    check_github:
+      jobs:
+        - project1-github
diff --git a/tests/fixtures/config/multi-driver/git/org_project/README b/tests/fixtures/config/multi-driver/git/org_project/README
new file mode 100644
index 0000000..9daeafb
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/git/org_project/README
@@ -0,0 +1 @@
+test
diff --git a/tests/fixtures/config/multi-driver/git/org_project1/README b/tests/fixtures/config/multi-driver/git/org_project1/README
new file mode 100644
index 0000000..9daeafb
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/git/org_project1/README
@@ -0,0 +1 @@
+test
diff --git a/tests/fixtures/config/multi-driver/main.yaml b/tests/fixtures/config/multi-driver/main.yaml
new file mode 100644
index 0000000..301df38
--- /dev/null
+++ b/tests/fixtures/config/multi-driver/main.yaml
@@ -0,0 +1,11 @@
+- tenant:
+    name: tenant-one
+    source:
+      github:
+        config-projects:
+          - common-config
+        untrusted-projects:
+          - org/project1
+      gerrit:
+        untrusted-projects:
+          - org/project
diff --git a/tests/fixtures/config/requirements/email/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/email/git/common-config/zuul.yaml
index 1a5baed..efc3b32 100644
--- a/tests/fixtures/config/requirements/email/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/email/git/common-config/zuul.yaml
@@ -11,8 +11,9 @@
       gerrit:
         verified: -1
     require:
-      approval:
-        - email: jenkins@example.com
+      gerrit:
+        approval:
+          - email: jenkins@example.com
 
 - pipeline:
     name: trigger
diff --git a/tests/fixtures/config/requirements/newer-than/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/newer-than/git/common-config/zuul.yaml
index fa230de..6f0601d 100644
--- a/tests/fixtures/config/requirements/newer-than/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/newer-than/git/common-config/zuul.yaml
@@ -11,9 +11,10 @@
       gerrit:
         verified: -1
     require:
-      approval:
-        - username: jenkins
-          newer-than: 48h
+      gerrit:
+        approval:
+          - username: jenkins
+            newer-than: 48h
 
 - pipeline:
     name: trigger
diff --git a/tests/fixtures/config/requirements/older-than/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/older-than/git/common-config/zuul.yaml
index 14541b6..77ee388 100644
--- a/tests/fixtures/config/requirements/older-than/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/older-than/git/common-config/zuul.yaml
@@ -11,9 +11,10 @@
       gerrit:
         verified: -1
     require:
-      approval:
-        - username: jenkins
-          older-than: 48h
+      gerrit:
+        approval:
+          - username: jenkins
+            older-than: 48h
 
 - pipeline:
     name: trigger
diff --git a/tests/fixtures/config/requirements/reject-username/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/reject-username/git/common-config/zuul.yaml
index 61f3819..9e9d000 100644
--- a/tests/fixtures/config/requirements/reject-username/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/reject-username/git/common-config/zuul.yaml
@@ -2,8 +2,9 @@
     name: pipeline
     manager: independent
     reject:
-      approval:
-        - username: jenkins
+      gerrit:
+        approval:
+          - username: jenkins
     trigger:
       gerrit:
         - event: comment-added
diff --git a/tests/fixtures/config/requirements/reject/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/reject/git/common-config/zuul.yaml
index 32a7582..b08a105 100644
--- a/tests/fixtures/config/requirements/reject/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/reject/git/common-config/zuul.yaml
@@ -2,16 +2,18 @@
     name: pipeline
     manager: independent
     require:
-      approval:
-        - username: jenkins
-          verified:
-            - 1
-            - 2
+      gerrit:
+        approval:
+          - username: jenkins
+            verified:
+              - 1
+              - 2
     reject:
-      approval:
-        - verified:
-            - -1
-            - -2
+      gerrit:
+        approval:
+          - verified:
+              - -1
+              - -2
     trigger:
       gerrit:
         - event: comment-added
diff --git a/tests/fixtures/config/requirements/state/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/state/git/common-config/zuul.yaml
index ffc3453..bd9dc8f 100644
--- a/tests/fixtures/config/requirements/state/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/state/git/common-config/zuul.yaml
@@ -2,7 +2,8 @@
     name: current-check
     manager: independent
     require:
-      current-patchset: true
+      gerrit:
+        current-patchset: true
     trigger:
       gerrit:
         - event: patchset-created
@@ -18,7 +19,8 @@
     name: open-check
     manager: independent
     require:
-      open: true
+      gerrit:
+        open: true
     trigger:
       gerrit:
         - event: patchset-created
@@ -34,7 +36,8 @@
     name: status-check
     manager: independent
     require:
-      status: NEW
+      gerrit:
+        status: NEW
     trigger:
       gerrit:
         - event: patchset-created
diff --git a/tests/fixtures/config/requirements/username/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/username/git/common-config/zuul.yaml
index bc1083a..455d9de 100644
--- a/tests/fixtures/config/requirements/username/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/username/git/common-config/zuul.yaml
@@ -11,8 +11,9 @@
       gerrit:
         verified: -1
     require:
-      approval:
-        - username: ^(jenkins|zuul)$
+      gerrit:
+        approval:
+          - username: ^(jenkins|zuul)$
 
 - pipeline:
     name: trigger
diff --git a/tests/fixtures/config/requirements/vote1/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/vote1/git/common-config/zuul.yaml
index 7d9164d..799282d 100644
--- a/tests/fixtures/config/requirements/vote1/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/vote1/git/common-config/zuul.yaml
@@ -2,9 +2,10 @@
     name: pipeline
     manager: independent
     require:
-      approval:
-        - username: jenkins
-          verified: 1
+      gerrit:
+        approval:
+          - username: jenkins
+            verified: 1
     trigger:
       gerrit:
         - event: comment-added
diff --git a/tests/fixtures/config/requirements/vote2/git/common-config/zuul.yaml b/tests/fixtures/config/requirements/vote2/git/common-config/zuul.yaml
index 7308c8a..f337371 100644
--- a/tests/fixtures/config/requirements/vote2/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/requirements/vote2/git/common-config/zuul.yaml
@@ -2,11 +2,12 @@
     name: pipeline
     manager: independent
     require:
-      approval:
-        - username: jenkins
-          verified:
-            - 1
-            - 2
+      gerrit:
+        approval:
+          - username: jenkins
+            verified:
+              - 1
+              - 2
     trigger:
       gerrit:
         - event: comment-added
diff --git a/tests/fixtures/config/single-tenant/git/common-config/zuul.yaml b/tests/fixtures/config/single-tenant/git/common-config/zuul.yaml
index 34bd9cd..2bb61ee 100644
--- a/tests/fixtures/config/single-tenant/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/single-tenant/git/common-config/zuul.yaml
@@ -69,7 +69,6 @@
 
 - job:
     name: project1-project2-integration
-    queue-name: integration
 
 - job:
     name: project-testfile
diff --git a/tests/fixtures/config/zuul-connections-multiple-gerrits/git/common-config/zuul.yaml b/tests/fixtures/config/zuul-connections-multiple-gerrits/git/common-config/zuul.yaml
index 961ff06..8f858cd 100644
--- a/tests/fixtures/config/zuul-connections-multiple-gerrits/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/zuul-connections-multiple-gerrits/git/common-config/zuul.yaml
@@ -24,6 +24,25 @@
       another_gerrit:
         verified: -1
 
+- pipeline:
+    name: common_check
+    manager: independent
+    trigger:
+      another_gerrit:
+        - event: patchset-created
+      review_gerrit:
+        - event: patchset-created
+    success:
+      review_gerrit:
+        verified: 1
+      another_gerrit:
+        verified: 1
+    failure:
+      review_gerrit:
+        verified: -1
+      another_gerrit:
+        verified: -1
+
 - job:
     name: project-test1
 
@@ -41,3 +60,16 @@
     another_check:
       jobs:
         - project-test2
+
+
+- project:
+    name: review.example.com/org/project2
+    common_check:
+      jobs:
+        - project-test1
+
+- project:
+    name: another.example.com/org/project2
+    common_check:
+      jobs:
+        - project-test2
diff --git a/tests/fixtures/config/zuul-connections-multiple-gerrits/git/org_project2/README b/tests/fixtures/config/zuul-connections-multiple-gerrits/git/org_project2/README
new file mode 100644
index 0000000..9daeafb
--- /dev/null
+++ b/tests/fixtures/config/zuul-connections-multiple-gerrits/git/org_project2/README
@@ -0,0 +1 @@
+test
diff --git a/tests/fixtures/config/zuul-connections-multiple-gerrits/main.yaml b/tests/fixtures/config/zuul-connections-multiple-gerrits/main.yaml
index f5bff21..38810fd 100644
--- a/tests/fixtures/config/zuul-connections-multiple-gerrits/main.yaml
+++ b/tests/fixtures/config/zuul-connections-multiple-gerrits/main.yaml
@@ -6,6 +6,8 @@
           - common-config
         untrusted-projects:
           - org/project1
+          - org/project2
       another_gerrit:
         untrusted-projects:
           - org/project1
+          - org/project2
diff --git a/tests/fixtures/config/zuultrigger/parent-change-enqueued/git/common-config/zuul.yaml b/tests/fixtures/config/zuultrigger/parent-change-enqueued/git/common-config/zuul.yaml
index 2b21c9b..351092c 100644
--- a/tests/fixtures/config/zuultrigger/parent-change-enqueued/git/common-config/zuul.yaml
+++ b/tests/fixtures/config/zuultrigger/parent-change-enqueued/git/common-config/zuul.yaml
@@ -2,8 +2,9 @@
     name: check
     manager: independent
     require:
-      approval:
-        - verified: -1
+      gerrit:
+        approval:
+          - verified: -1
     trigger:
       gerrit:
         - event: patchset-created
@@ -21,8 +22,9 @@
     name: gate
     manager: dependent
     require:
-      approval:
-        - verified: 1
+      gerrit:
+        approval:
+          - verified: 1
     trigger:
       gerrit:
         - event: comment-added
diff --git a/tests/fixtures/layout-live-reconfiguration-add-job.yaml b/tests/fixtures/layout-live-reconfiguration-add-job.yaml
deleted file mode 100644
index e4aea6f..0000000
--- a/tests/fixtures/layout-live-reconfiguration-add-job.yaml
+++ /dev/null
@@ -1,38 +0,0 @@
-pipelines:
-  - name: gate
-    manager: DependentPipelineManager
-    failure-message: Build failed.  For information on how to proceed, see http://wiki.example.org/Test_Failures
-    trigger:
-      gerrit:
-        - event: comment-added
-          approval:
-            - approved: 1
-    success:
-      gerrit:
-        verified: 2
-        submit: true
-    failure:
-      gerrit:
-        verified: -2
-    start:
-      gerrit:
-        verified: 0
-    precedence: high
-
-jobs:
-  - name: ^.*-merge$
-    failure-message: Unable to merge change
-    hold-following-changes: true
-  - name: project-testfile
-    files:
-      - '.*-requires'
-
-projects:
-  - name: org/project
-    merge-mode: cherry-pick
-    gate:
-      - project-merge:
-        - project-test1
-        - project-test2
-        - project-test3
-        - project-testfile
diff --git a/tests/fixtures/layout-live-reconfiguration-failed-job.yaml b/tests/fixtures/layout-live-reconfiguration-failed-job.yaml
deleted file mode 100644
index e811af1..0000000
--- a/tests/fixtures/layout-live-reconfiguration-failed-job.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-pipelines:
-  - name: check
-    manager: IndependentPipelineManager
-    trigger:
-      gerrit:
-        - event: patchset-created
-    success:
-      gerrit:
-        verified: 1
-    failure:
-      gerrit:
-        verified: -1
-
-jobs:
-  - name: ^.*-merge$
-    failure-message: Unable to merge change
-    hold-following-changes: true
-
-projects:
-  - name: org/project
-    merge-mode: cherry-pick
-    check:
-      - project-merge:
-        - project-test2
-        - project-testfile
diff --git a/tests/fixtures/layout-live-reconfiguration-shared-queue.yaml b/tests/fixtures/layout-live-reconfiguration-shared-queue.yaml
deleted file mode 100644
index ad3f666..0000000
--- a/tests/fixtures/layout-live-reconfiguration-shared-queue.yaml
+++ /dev/null
@@ -1,62 +0,0 @@
-pipelines:
-  - name: check
-    manager: IndependentPipelineManager
-    trigger:
-      gerrit:
-        - event: patchset-created
-    success:
-      gerrit:
-        verified: 1
-    failure:
-      gerrit:
-        verified: -1
-
-  - name: gate
-    manager: DependentPipelineManager
-    failure-message: Build failed.  For information on how to proceed, see http://wiki.example.org/Test_Failures
-    trigger:
-      gerrit:
-        - event: comment-added
-          approval:
-            - approved: 1
-    success:
-      gerrit:
-        verified: 2
-        submit: true
-    failure:
-      gerrit:
-        verified: -2
-    start:
-      gerrit:
-        verified: 0
-    precedence: high
-
-jobs:
-  - name: ^.*-merge$
-    failure-message: Unable to merge change
-    hold-following-changes: true
-  - name: project1-project2-integration
-    queue-name: integration
-
-projects:
-  - name: org/project1
-    check:
-      - project1-merge:
-        - project1-test1
-        - project1-test2
-    gate:
-      - project1-merge:
-        - project1-test1
-        - project1-test2
-
-  - name: org/project2
-    check:
-      - project2-merge:
-        - project2-test1
-        - project2-test2
-        - project1-project2-integration
-    gate:
-      - project2-merge:
-        - project2-test1
-        - project2-test2
-        - project1-project2-integration
diff --git a/tests/fixtures/layouts/files-github.yaml b/tests/fixtures/layouts/files-github.yaml
new file mode 100644
index 0000000..734b945
--- /dev/null
+++ b/tests/fixtures/layouts/files-github.yaml
@@ -0,0 +1,18 @@
+- pipeline:
+    name: check
+    manager: independent
+    trigger:
+      github:
+        - event: pull_request
+          action: opened
+
+- job:
+    name: project-test1
+    files:
+      - '.*-requires'
+
+- project:
+    name: org/project
+    check:
+      jobs:
+        - project-test1
diff --git a/tests/fixtures/layouts/ignore-dependencies.yaml b/tests/fixtures/layouts/ignore-dependencies.yaml
index 02aea36..86fe674 100644
--- a/tests/fixtures/layouts/ignore-dependencies.yaml
+++ b/tests/fixtures/layouts/ignore-dependencies.yaml
@@ -32,7 +32,6 @@
 
 - job:
     name: project1-project2-integration
-    queue-name: integration
 
 - project:
     name: org/project1
diff --git a/tests/fixtures/layouts/live-reconfiguration-add-job.yaml b/tests/fixtures/layouts/live-reconfiguration-add-job.yaml
new file mode 100644
index 0000000..5916282
--- /dev/null
+++ b/tests/fixtures/layouts/live-reconfiguration-add-job.yaml
@@ -0,0 +1,57 @@
+- pipeline:
+    name: gate
+    manager: dependent
+    failure-message: Build failed.  For information on how to proceed, see http://wiki.example.org/Test_Failures
+    trigger:
+      gerrit:
+        - event: comment-added
+          approval:
+            - approved: 1
+    success:
+      gerrit:
+        verified: 2
+        submit: true
+    failure:
+      gerrit:
+        verified: -2
+    start:
+      gerrit:
+        verified: 0
+    precedence: high
+
+- job:
+    name: project-merge
+    hold-following-changes: true
+
+- job:
+    name: project-test1
+
+- job:
+    name: project-test2
+
+- job:
+    name: project-test3
+
+- job:
+    name: project-testfile
+    files:
+      - '.*-requires'
+
+- project:
+    name: org/project
+    merge-mode: cherry-pick
+    gate:
+      jobs:
+      - project-merge
+      - project-test1:
+          dependencies:
+            - project-merge
+      - project-test2:
+          dependencies:
+            - project-merge
+      - project-test3:
+          dependencies:
+            - project-merge
+      - project-testfile:
+          dependencies:
+            - project-merge
diff --git a/tests/fixtures/layouts/live-reconfiguration-failed-job.yaml b/tests/fixtures/layouts/live-reconfiguration-failed-job.yaml
new file mode 100644
index 0000000..0907880
--- /dev/null
+++ b/tests/fixtures/layouts/live-reconfiguration-failed-job.yaml
@@ -0,0 +1,35 @@
+- pipeline:
+    name: check
+    manager: independent
+    trigger:
+      gerrit:
+        - event: patchset-created
+    success:
+      gerrit:
+        verified: 1
+    failure:
+      gerrit:
+        verified: -1
+
+- job:
+    name: project-merge
+    hold-following-changes: true
+
+- job:
+    name: project-test2
+
+- job:
+    name: project-testfile
+
+- project:
+    name: org/project
+    merge-mode: cherry-pick
+    check:
+      jobs:
+      - project-merge
+      - project-test2:
+          dependencies:
+            - project-merge
+      - project-testfile:
+          dependencies:
+            - project-merge
diff --git a/tests/fixtures/layouts/live-reconfiguration-shared-queue.yaml b/tests/fixtures/layouts/live-reconfiguration-shared-queue.yaml
new file mode 100644
index 0000000..bf4416a
--- /dev/null
+++ b/tests/fixtures/layouts/live-reconfiguration-shared-queue.yaml
@@ -0,0 +1,86 @@
+- pipeline:
+    name: check
+    manager: independent
+    trigger:
+      gerrit:
+        - event: patchset-created
+    success:
+      gerrit:
+        verified: 1
+    failure:
+      gerrit:
+        verified: -1
+
+- pipeline:
+    name: gate
+    manager: dependent
+    failure-message: Build failed.  For information on how to proceed, see http://wiki.example.org/Test_Failures
+    trigger:
+      gerrit:
+        - event: comment-added
+          approval:
+            - approved: 1
+    success:
+      gerrit:
+        verified: 2
+        submit: true
+    failure:
+      gerrit:
+        verified: -2
+    start:
+      gerrit:
+        verified: 0
+    precedence: high
+
+- job:
+    name: project-merge
+    hold-following-changes: true
+
+- job:
+    name: project-test1
+
+- job:
+    name: project-test2
+
+- job:
+    name: project1-project2-integration
+
+- project:
+    name: org/project1
+    check:
+      jobs:
+        - project-merge
+        - project-test1:
+            dependencies: project-merge
+        - project-test2:
+            dependencies: project-merge
+    gate:
+      queue: integrated
+      jobs:
+        - project-merge
+        - project-test1:
+            dependencies: project-merge
+        - project-test2:
+            dependencies: project-merge
+
+- project:
+    name: org/project2
+    check:
+      jobs:
+        - project-merge
+        - project-test1:
+            dependencies: project-merge
+        - project-test2:
+            dependencies: project-merge
+        - project1-project2-integration:
+            dependencies: project-merge
+    gate:
+      queue: integrated
+      jobs:
+        - project-merge
+        - project-test1:
+            dependencies: project-merge
+        - project-test2:
+            dependencies: project-merge
+        - project1-project2-integration:
+            dependencies: project-merge
diff --git a/tests/fixtures/layouts/merging-github.yaml b/tests/fixtures/layouts/merging-github.yaml
index 4e13063..9f43f75 100644
--- a/tests/fixtures/layouts/merging-github.yaml
+++ b/tests/fixtures/layouts/merging-github.yaml
@@ -2,6 +2,7 @@
     name: merge
     description: Pipeline for merging the pull request
     manager: independent
+    merge-failure-message: 'Merge failed'
     trigger:
       github:
         - event: pull_request
diff --git a/tests/fixtures/layouts/reporting-github.yaml b/tests/fixtures/layouts/reporting-github.yaml
index bcbac1b..c939f39 100644
--- a/tests/fixtures/layouts/reporting-github.yaml
+++ b/tests/fixtures/layouts/reporting-github.yaml
@@ -28,6 +28,7 @@
     success:
       github:
         comment: false
+        status: 'success'
     failure:
       github:
         comment: false
diff --git a/tests/fixtures/layouts/requirements-github.yaml b/tests/fixtures/layouts/requirements-github.yaml
new file mode 100644
index 0000000..9933f27
--- /dev/null
+++ b/tests/fixtures/layouts/requirements-github.yaml
@@ -0,0 +1,245 @@
+- pipeline:
+    name: pipeline
+    manager: independent
+    require:
+      github:
+        status: "zuul:check:success"
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: trigger_status
+    manager: independent
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'trigger me'
+          require-status: "zuul:check:success"
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: trigger
+    manager: independent
+    trigger:
+      github:
+        - event: pull_request
+          action: status
+          status: 'zuul:check:success'
+    success:
+      github:
+        status: 'success'
+    failure:
+      github:
+        status: 'failure'
+
+- pipeline:
+    name: reviewusername
+    manager: independent
+    require:
+      github:
+        review:
+          - username: '^(herp|derp)$'
+            type: approved
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: reviewreq
+    manager: independent
+    require:
+      github:
+        review:
+          - type: approved
+            permission: write
+    reject:
+      github:
+        review:
+          - type: changes_requested
+            permission: write
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: reviewuserstate
+    manager: independent
+    require:
+      github:
+        review:
+          - username: 'derp'
+            type: approved
+            permission: write
+    reject:
+      github:
+        review:
+          - type: changes_requested
+            permission: write
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: newer_than
+    manager: independent
+    require:
+      github:
+        review:
+          - type: approved
+            permission: write
+            newer-than: 1d
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: older_than
+    manager: independent
+    require:
+      github:
+        review:
+          - type: approved
+            permission: write
+            older-than: 1d
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: require_open
+    manager: independent
+    require:
+      github:
+        open: true
+    trigger:
+      github:
+        - event: pull_request
+          action: comment
+          comment: 'test me'
+    success:
+      github:
+        comment: true
+
+- pipeline:
+    name: require_current
+    manager: independent
+    require:
+      github:
+        current-patchset: true
+    trigger:
+      github:
+        - event: pull_request
+          action: changed
+    success:
+      github:
+        comment: true
+
+- job:
+    name: project1-pipeline
+- job:
+    name: project2-trigger
+- job:
+    name: project3-reviewusername
+- job:
+    name: project4-reviewreq
+- job:
+    name: project5-reviewuserstate
+- job:
+    name: project6-newerthan
+- job:
+    name: project7-olderthan
+- job:
+    name: project8-requireopen
+- job:
+    name: project9-requirecurrent
+
+- project:
+    name: org/project1
+    pipeline:
+      jobs:
+        - project1-pipeline
+    trigger_status:
+      jobs:
+        - project1-pipeline
+
+- project:
+    name: org/project2
+    trigger:
+      jobs:
+        - project2-trigger
+
+- project:
+    name: org/project3
+    reviewusername:
+      jobs:
+        - project3-reviewusername
+
+- project:
+    name: org/project4
+    reviewreq:
+      jobs:
+        - project4-reviewreq
+
+- project:
+    name: org/project5
+    reviewuserstate:
+      jobs:
+        - project5-reviewuserstate
+
+- project:
+    name: org/project6
+    newer_than:
+      jobs:
+        - project6-newerthan
+
+- project:
+    name: org/project7
+    older_than:
+      jobs:
+        - project7-olderthan
+
+- project:
+    name: org/project8
+    require_open:
+      jobs:
+        - project8-requireopen
+
+- project:
+    name: org/project9
+    require_current:
+      jobs:
+        - project9-requirecurrent
diff --git a/tests/fixtures/layouts/reviews-github.yaml b/tests/fixtures/layouts/reviews-github.yaml
new file mode 100644
index 0000000..1cc887a
--- /dev/null
+++ b/tests/fixtures/layouts/reviews-github.yaml
@@ -0,0 +1,21 @@
+- pipeline:
+    name: reviews
+    manager: independent
+    trigger:
+      github:
+        - event: pull_request_review
+          action: submitted
+          state: 'approve'
+    success:
+      github:
+        label:
+          - 'tests passed'
+
+- job:
+    name: project-reviews
+
+- project:
+    name: org/project
+    reviews:
+      jobs:
+        - project-reviews
diff --git a/tests/fixtures/zuul-connections-gerrit-and-github.conf b/tests/fixtures/zuul-connections-gerrit-and-github.conf
new file mode 100644
index 0000000..bd05c75
--- /dev/null
+++ b/tests/fixtures/zuul-connections-gerrit-and-github.conf
@@ -0,0 +1,31 @@
+[gearman]
+server=127.0.0.1
+
+[zuul]
+tenant_config=config/multi-driver/main.yaml
+job_name_in_report=true
+
+[merger]
+git_dir=/tmp/zuul-test/git
+git_user_email=zuul@example.com
+git_user_name=zuul
+zuul_url=http://zuul.example.com/p
+
+[executor]
+git_dir=/tmp/zuul-test/executor-git
+
+[connection gerrit]
+driver=gerrit
+server=review.example.com
+user=jenkins
+sshkey=none
+
+[connection github]
+driver=github
+
+[connection outgoing_smtp]
+driver=smtp
+server=localhost
+port=25
+default_from=zuul@example.com
+default_to=you@example.com
diff --git a/tests/fixtures/zuul-connections-merger.conf b/tests/fixtures/zuul-connections-merger.conf
new file mode 100644
index 0000000..7a1bc42
--- /dev/null
+++ b/tests/fixtures/zuul-connections-merger.conf
@@ -0,0 +1,35 @@
+[gearman]
+server=127.0.0.1
+
+[zuul]
+job_name_in_report=true
+status_url=http://zuul.example.com/status
+
+[merger]
+git_dir=/tmp/zuul-test/git
+git_user_email=zuul@example.com
+git_user_name=zuul
+zuul_url=http://zuul.example.com/p
+
+[executor]
+git_dir=/tmp/zuul-test/executor-git
+
+[connection github]
+driver=github
+
+[connection gerrit]
+driver=gerrit
+server=review.example.com
+user=jenkins
+sshkey=fake_id_rsa1
+
+[connection resultsdb]
+driver=sql
+dburi=$MYSQL_FIXTURE_DBURI$
+
+[connection smtp]
+driver=smtp
+server=localhost
+port=25
+default_from=zuul@example.com
+default_to=you@example.com
diff --git a/tests/fixtures/zuul-github-driver.conf b/tests/fixtures/zuul-github-driver.conf
index 58c7cd5..ab34619 100644
--- a/tests/fixtures/zuul-github-driver.conf
+++ b/tests/fixtures/zuul-github-driver.conf
@@ -20,3 +20,8 @@
 [connection github_ssh]
 driver=github
 sshkey=/home/zuul/.ssh/id_rsa
+
+[connection github_ent]
+driver=github
+sshkey=/home/zuul/.ssh/id_rsa
+git_host=github.enterprise.io
diff --git a/tests/unit/test_change_matcher.py b/tests/unit/test_change_matcher.py
index 0585322..6b161a1 100644
--- a/tests/unit/test_change_matcher.py
+++ b/tests/unit/test_change_matcher.py
@@ -125,12 +125,18 @@
     def test_matches_returns_false_when_not_all_files_match(self):
         self._test_matches(False, files=['/COMMIT_MSG', 'docs/foo', 'foo/bar'])
 
+    def test_matches_returns_true_when_single_file_does_not_match(self):
+        self._test_matches(True, files=['docs/foo'])
+
     def test_matches_returns_false_when_commit_message_matches(self):
         self._test_matches(False, files=['/COMMIT_MSG'])
 
     def test_matches_returns_true_when_all_files_match(self):
         self._test_matches(True, files=['/COMMIT_MSG', 'docs/foo'])
 
+    def test_matches_returns_true_when_single_file_matches(self):
+        self._test_matches(True, files=['docs/foo'])
+
 
 class TestMatchAll(BaseTestMatcher):
 
diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py
index db32938..142a248 100644
--- a/tests/unit/test_connection.py
+++ b/tests/unit/test_connection.py
@@ -265,3 +265,63 @@
         self.executor_server.hold_jobs_in_build = False
         self.executor_server.release()
         self.waitUntilSettled()
+
+    def test_multiple_project_separate_gerrits_common_pipeline(self):
+        self.executor_server.hold_jobs_in_build = True
+
+        A = self.fake_another_gerrit.addFakeChange(
+            'org/project2', 'master', 'A')
+        self.fake_another_gerrit.addEvent(A.getPatchsetCreatedEvent(1))
+
+        self.waitUntilSettled()
+
+        self.assertBuilds([dict(name='project-test2',
+                                changes='1,1',
+                                project='org/project2',
+                                pipeline='common_check')])
+
+        # NOTE(jamielennox): the tests back the git repo for both connections
+        # onto the same git repo on the file system. If we just create another
+        # fake change the fake_review_gerrit will try to create another 1,1
+        # change and git will fail to create the ref. Arbitrarily set it to get
+        # around the problem.
+        self.fake_review_gerrit.change_number = 50
+
+        B = self.fake_review_gerrit.addFakeChange(
+            'org/project2', 'master', 'B')
+        self.fake_review_gerrit.addEvent(B.getPatchsetCreatedEvent(1))
+
+        self.waitUntilSettled()
+
+        self.assertBuilds([
+            dict(name='project-test2',
+                 changes='1,1',
+                 project='org/project2',
+                 pipeline='common_check'),
+            dict(name='project-test1',
+                 changes='51,1',
+                 project='org/project2',
+                 pipeline='common_check'),
+        ])
+
+        self.executor_server.hold_jobs_in_build = False
+        self.executor_server.release()
+        self.waitUntilSettled()
+
+
+class TestConnectionsMerger(ZuulTestCase):
+    config_file = 'zuul-connections-merger.conf'
+    tenant_config_file = 'config/single-tenant/main.yaml'
+
+    def configure_connections(self):
+        super(TestConnectionsMerger, self).configure_connections(True)
+
+    def test_connections_merger(self):
+        "Test merger only configures source connections"
+
+        self.assertIn("gerrit", self.connections.connections)
+        self.assertIn("github", self.connections.connections)
+        self.assertNotIn("smtp", self.connections.connections)
+        self.assertNotIn("sql", self.connections.connections)
+        self.assertNotIn("timer", self.connections.connections)
+        self.assertNotIn("zuul", self.connections.connections)
diff --git a/tests/unit/test_encryption.py b/tests/unit/test_encryption.py
index 4dda78b..b424769 100644
--- a/tests/unit/test_encryption.py
+++ b/tests/unit/test_encryption.py
@@ -41,14 +41,14 @@
 
     def test_pkcs1_oaep(self):
         "Verify encryption and decryption"
-        orig_plaintext = "some text to encrypt"
+        orig_plaintext = b"some text to encrypt"
         ciphertext = encryption.encrypt_pkcs1_oaep(orig_plaintext, self.public)
         plaintext = encryption.decrypt_pkcs1_oaep(ciphertext, self.private)
         self.assertEqual(orig_plaintext, plaintext)
 
     def test_openssl_pkcs1_oaep(self):
         "Verify that we can decrypt something encrypted with OpenSSL"
-        orig_plaintext = "some text to encrypt"
+        orig_plaintext = b"some text to encrypt"
         pem_public = encryption.serialize_rsa_public_key(self.public)
         public_file = tempfile.NamedTemporaryFile(delete=False)
         try:
diff --git a/tests/unit/test_github_driver.py b/tests/unit/test_github_driver.py
index 3f567d2..227d659 100644
--- a/tests/unit/test_github_driver.py
+++ b/tests/unit/test_github_driver.py
@@ -12,17 +12,12 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
-import logging
 import re
 from testtools.matchers import MatchesRegex
 import time
 
 from tests.base import ZuulTestCase, simple_layout, random_sha1
 
-logging.basicConfig(level=logging.DEBUG,
-                    format='%(asctime)s %(name)-32s '
-                    '%(levelname)-8s %(message)s')
-
 
 class TestGithubDriver(ZuulTestCase):
     config_file = 'zuul-github-driver.conf'
@@ -65,6 +60,22 @@
 
         self.assertEqual(2, len(self.history))
 
+    @simple_layout('layouts/files-github.yaml', driver='github')
+    def test_pull_matched_file_event(self):
+        A = self.fake_github.openFakePullRequest(
+            'org/project', 'master', 'A',
+            files=['random.txt', 'build-requires'])
+        self.fake_github.emitEvent(A.getPullRequestOpenedEvent())
+        self.waitUntilSettled()
+        self.assertEqual(1, len(self.history))
+
+        # test_pull_unmatched_file_event
+        B = self.fake_github.openFakePullRequest('org/project', 'master', 'B',
+                                                 files=['random.txt'])
+        self.fake_github.emitEvent(B.getPullRequestOpenedEvent())
+        self.waitUntilSettled()
+        self.assertEqual(1, len(self.history))
+
     @simple_layout('layouts/basic-github.yaml', driver='github')
     def test_comment_event(self):
         A = self.fake_github.openFakePullRequest('org/project', 'master', 'A')
@@ -161,6 +172,21 @@
         self.assertEqual(2, len(self.history))
         self.assertEqual(['other label'], C.labels)
 
+    @simple_layout('layouts/reviews-github.yaml', driver='github')
+    def test_review_event(self):
+        A = self.fake_github.openFakePullRequest('org/project', 'master', 'A')
+        self.fake_github.emitEvent(A.getReviewAddedEvent('approve'))
+        self.waitUntilSettled()
+        self.assertEqual(1, len(self.history))
+        self.assertEqual('project-reviews', self.history[0].name)
+        self.assertEqual(['tests passed'], A.labels)
+
+        # test_review_unmatched_event
+        B = self.fake_github.openFakePullRequest('org/project', 'master', 'B')
+        self.fake_github.emitEvent(B.getReviewAddedEvent('comment'))
+        self.waitUntilSettled()
+        self.assertEqual(1, len(self.history))
+
     @simple_layout('layouts/dequeue-github.yaml', driver='github')
     def test_dequeue_pull_synchronized(self):
         self.executor_server.hold_jobs_in_build = True
@@ -214,6 +240,12 @@
         url = self.fake_github_ssh.real_getGitUrl('org/project')
         self.assertEqual('ssh://git@github.com/org/project.git', url)
 
+    @simple_layout('layouts/basic-github.yaml', driver='github')
+    def test_git_enterprise_url(self):
+        """Test that git_url option gives git url with proper host"""
+        url = self.fake_github_ent.real_getGitUrl('org/project')
+        self.assertEqual('ssh://git@github.enterprise.io/org/project.git', url)
+
     @simple_layout('layouts/reporting-github.yaml', driver='github')
     def test_reporting(self):
         # pipeline reports pull status both on start and success
@@ -221,20 +253,30 @@
         A = self.fake_github.openFakePullRequest('org/project', 'master', 'A')
         self.fake_github.emitEvent(A.getPullRequestOpenedEvent())
         self.waitUntilSettled()
-        self.assertIn('check', A.statuses)
-        check_status = A.statuses['check']
+        # We should have a status container for the head sha
+        self.assertIn(A.head_sha, A.statuses.keys())
+        # We should only have one status for the head sha
+        self.assertEqual(1, len(A.statuses[A.head_sha]))
+        check_status = A.statuses[A.head_sha][0]
+        check_url = ('http://zuul.example.com/status/#%s,%s' %
+                     (A.number, A.head_sha))
+        self.assertEqual('tenant-one/check', check_status['context'])
         self.assertEqual('Standard check', check_status['description'])
         self.assertEqual('pending', check_status['state'])
-        self.assertEqual('http://zuul.example.com/status', check_status['url'])
+        self.assertEqual(check_url, check_status['url'])
         self.assertEqual(0, len(A.comments))
 
         self.executor_server.hold_jobs_in_build = False
         self.executor_server.release()
         self.waitUntilSettled()
-        check_status = A.statuses['check']
-        self.assertEqual('Standard check', check_status['description'])
+        # We should only have two statuses for the head sha
+        self.assertEqual(2, len(A.statuses[A.head_sha]))
+        check_status = A.statuses[A.head_sha][0]
+        check_url = ('http://zuul.example.com/status/#%s,%s' %
+                     (A.number, A.head_sha))
+        self.assertEqual('tenant-one/check', check_status['context'])
         self.assertEqual('success', check_status['state'])
-        self.assertEqual('http://zuul.example.com/status', check_status['url'])
+        self.assertEqual(check_url, check_status['url'])
         self.assertEqual(1, len(A.comments))
         self.assertThat(A.comments[0],
                         MatchesRegex('.*Build succeeded.*', re.DOTALL))
@@ -244,7 +286,7 @@
         self.fake_github.emitEvent(
             A.getCommentAddedEvent('reporting check'))
         self.waitUntilSettled()
-        self.assertNotIn('reporting', A.statuses)
+        self.assertEqual(2, len(A.statuses[A.head_sha]))
         # comments increased by one for the start message
         self.assertEqual(2, len(A.comments))
         self.assertThat(A.comments[1],
@@ -252,16 +294,23 @@
         self.executor_server.hold_jobs_in_build = False
         self.executor_server.release()
         self.waitUntilSettled()
-        self.assertNotIn('reporting', A.statuses)
+        # pipeline reports success status
+        self.assertEqual(3, len(A.statuses[A.head_sha]))
+        report_status = A.statuses[A.head_sha][0]
+        self.assertEqual('tenant-one/reporting', report_status['context'])
+        self.assertEqual('success', report_status['state'])
         self.assertEqual(2, len(A.comments))
 
     @simple_layout('layouts/merging-github.yaml', driver='github')
     def test_report_pull_merge(self):
         # pipeline merges the pull request on success
-        A = self.fake_github.openFakePullRequest('org/project', 'master', 'A')
+        A = self.fake_github.openFakePullRequest('org/project', 'master',
+                                                 'PR title')
         self.fake_github.emitEvent(A.getCommentAddedEvent('merge me'))
         self.waitUntilSettled()
         self.assertTrue(A.is_merged)
+        self.assertThat(A.merge_message,
+                        MatchesRegex('.*PR title.*Reviewed-by.*', re.DOTALL))
 
         # pipeline merges the pull request on success after failure
         self.fake_github.merge_failure = True
@@ -286,6 +335,8 @@
         self.fake_github.emitEvent(D.getCommentAddedEvent('merge me'))
         self.waitUntilSettled()
         self.assertFalse(D.is_merged)
+        self.assertEqual(len(D.comments), 1)
+        self.assertEqual(D.comments[0], 'Merge failed')
 
     @simple_layout('layouts/dependent-github.yaml', driver='github')
     def test_parallel_changes(self):
diff --git a/tests/unit/test_github_requirements.py b/tests/unit/test_github_requirements.py
new file mode 100644
index 0000000..5dd6e80
--- /dev/null
+++ b/tests/unit/test_github_requirements.py
@@ -0,0 +1,328 @@
+#!/usr/bin/env python
+# Copyright (c) 2017 IBM Corp.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import time
+
+from tests.base import ZuulTestCase, simple_layout
+
+
+class TestGithubRequirements(ZuulTestCase):
+    """Test pipeline and trigger requirements"""
+    config_file = 'zuul-github-driver.conf'
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_pipeline_require_status(self):
+        "Test pipeline requirement: status"
+        A = self.fake_github.openFakePullRequest('org/project1', 'master', 'A')
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No status from zuul so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # An error status should not cause it to be enqueued
+        A.setStatus(A.head_sha, 'error', 'null', 'null', 'check')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A success status goes in
+        A.setStatus(A.head_sha, 'success', 'null', 'null', 'check')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project1-pipeline')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_trigger_require_status(self):
+        "Test trigger requirement: status"
+        A = self.fake_github.openFakePullRequest('org/project1', 'master', 'A')
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('trigger me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No status from zuul so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # An error status should not cause it to be enqueued
+        A.setStatus(A.head_sha, 'error', 'null', 'null', 'check')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A success status goes in
+        A.setStatus(A.head_sha, 'success', 'null', 'null', 'check')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project1-pipeline')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_trigger_on_status(self):
+        "Test trigger on: status"
+        A = self.fake_github.openFakePullRequest('org/project2', 'master', 'A')
+
+        # An error status should not cause it to be enqueued
+        A.setStatus(A.head_sha, 'error', 'null', 'null', 'check')
+        self.fake_github.emitEvent(A.getCommitStatusEvent('check',
+                                                          state='error'))
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A success status from unknown user should not cause it to be
+        # enqueued
+        A.setStatus(A.head_sha, 'success', 'null', 'null', 'check', user='foo')
+        self.fake_github.emitEvent(A.getCommitStatusEvent('check',
+                                                          state='success',
+                                                          user='foo'))
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A success status from zuul goes in
+        A.setStatus(A.head_sha, 'success', 'null', 'null', 'check')
+        self.fake_github.emitEvent(A.getCommitStatusEvent('check'))
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project2-trigger')
+
+        # An error status for a different context should not cause it to be
+        # enqueued
+        A.setStatus(A.head_sha, 'error', 'null', 'null', 'gate')
+        self.fake_github.emitEvent(A.getCommitStatusEvent('gate',
+                                                          state='error'))
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_pipeline_require_review_username(self):
+        "Test pipeline requirement: review username"
+
+        A = self.fake_github.openFakePullRequest('org/project3', 'master', 'A')
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No approval from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # Add an approved review from derp
+        A.addReview('derp', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project3-reviewusername')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_pipeline_require_review_state(self):
+        "Test pipeline requirement: review state"
+
+        A = self.fake_github.openFakePullRequest('org/project4', 'master', 'A')
+        # Add derp to writers
+        A.writers.append('derp')
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No positive review from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # A negative review from derp should not cause it to be enqueued
+        A.addReview('derp', 'CHANGES_REQUESTED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A positive from nobody should not cause it to be enqueued
+        A.addReview('nobody', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A positive review from derp should cause it to be enqueued
+        A.addReview('derp', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project4-reviewreq')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_pipeline_require_review_user_state(self):
+        "Test pipeline requirement: review state from user"
+
+        A = self.fake_github.openFakePullRequest('org/project5', 'master', 'A')
+        # Add derp and herp to writers
+        A.writers.extend(('derp', 'herp'))
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No positive review from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # A negative review from derp should not cause it to be enqueued
+        A.addReview('derp', 'CHANGES_REQUESTED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A positive from nobody should not cause it to be enqueued
+        A.addReview('nobody', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A positive review from herp (a writer) should not cause it to be
+        # enqueued
+        A.addReview('herp', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # A positive review from derp should cause it to be enqueued
+        A.addReview('derp', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project5-reviewuserstate')
+
+# TODO: Implement reject on approval username/state
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_pipeline_require_review_latest_user_state(self):
+        "Test pipeline requirement: review state from user"
+
+        A = self.fake_github.openFakePullRequest('org/project5', 'master', 'A')
+        # Add derp and herp to writers
+        A.writers.extend(('derp', 'herp'))
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No positive review from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # The first negative review from derp should not cause it to be
+        # enqueued
+        for i in range(1, 4):
+            submitted_at = time.time() - 72 * 60 * 60
+            A.addReview('derp', 'CHANGES_REQUESTED',
+                        submitted_at)
+            self.fake_github.emitEvent(comment)
+            self.waitUntilSettled()
+            self.assertEqual(len(self.history), 0)
+
+        # A positive review from derp should cause it to be enqueued
+        A.addReview('derp', 'APPROVED')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project5-reviewuserstate')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_require_review_newer_than(self):
+
+        A = self.fake_github.openFakePullRequest('org/project6', 'master', 'A')
+        # Add derp and herp to writers
+        A.writers.extend(('derp', 'herp'))
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No positive review from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # Add a too-old positive review, should not be enqueued
+        submitted_at = time.time() - 72 * 60 * 60
+        A.addReview('derp', 'APPROVED',
+                    submitted_at)
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # Add a recent positive review
+        submitted_at = time.time() - 12 * 60 * 60
+        A.addReview('derp', 'APPROVED', submitted_at)
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project6-newerthan')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_require_review_older_than(self):
+
+        A = self.fake_github.openFakePullRequest('org/project7', 'master', 'A')
+        # Add derp and herp to writers
+        A.writers.extend(('derp', 'herp'))
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # No positive review from derp so should not be enqueued
+        self.assertEqual(len(self.history), 0)
+
+        # Add a too-new positive, should not be enqueued
+        submitted_at = time.time() - 12 * 60 * 60
+        A.addReview('derp', 'APPROVED',
+                    submitted_at)
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 0)
+
+        # Add an old enough positive, should enqueue
+        submitted_at = time.time() - 72 * 60 * 60
+        A.addReview('herp', 'APPROVED', submitted_at)
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        self.assertEqual(len(self.history), 1)
+        self.assertEqual(self.history[0].name, 'project7-olderthan')
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_require_open(self):
+
+        A = self.fake_github.openFakePullRequest('org/project8', 'master', 'A')
+        # A comment event that we will keep submitting to trigger
+        comment = A.getCommentAddedEvent('test me')
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+
+        # PR is open, we should have enqueued
+        self.assertEqual(len(self.history), 1)
+
+        # close the PR and try again
+        A.state = 'closed'
+        self.fake_github.emitEvent(comment)
+        self.waitUntilSettled()
+        # PR is closed, should not trigger
+        self.assertEqual(len(self.history), 1)
+
+    @simple_layout('layouts/requirements-github.yaml', driver='github')
+    def test_require_current(self):
+
+        A = self.fake_github.openFakePullRequest('org/project9', 'master', 'A')
+        # A sync event that we will keep submitting to trigger
+        sync = A.getPullRequestSynchronizeEvent()
+        self.fake_github.emitEvent(sync)
+        self.waitUntilSettled()
+
+        # PR head is current should enqueue
+        self.assertEqual(len(self.history), 1)
+
+        # Add a commit to the PR, re-issue the original comment event
+        A.addCommit()
+        self.fake_github.emitEvent(sync)
+        self.waitUntilSettled()
+        # Event hash is not current, should not trigger
+        self.assertEqual(len(self.history), 1)
diff --git a/tests/unit/test_log_streamer.py b/tests/unit/test_log_streamer.py
new file mode 100644
index 0000000..3ea5a8e
--- /dev/null
+++ b/tests/unit/test_log_streamer.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import logging
+import socket
+import tempfile
+
+import zuul.lib.log_streamer
+import tests.base
+
+
+class TestLogStreamer(tests.base.BaseTestCase):
+
+    log = logging.getLogger("zuul.test.cloner")
+
+    def setUp(self):
+        super(TestLogStreamer, self).setUp()
+        self.host = '0.0.0.0'
+
+    def startStreamer(self, port, root=None):
+        if not root:
+            root = tempfile.gettempdir()
+        return zuul.lib.log_streamer.LogStreamer(None, self.host, port, root)
+
+    def test_start_stop(self):
+        port = 7900
+        streamer = self.startStreamer(port)
+        self.addCleanup(streamer.stop)
+
+        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.addCleanup(s.close)
+        self.assertEqual(0, s.connect_ex((self.host, port)))
+        s.close()
+
+        streamer.stop()
+
+        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.addCleanup(s.close)
+        self.assertNotEqual(0, s.connect_ex((self.host, port)))
+        s.close()
diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py
index d8480ea..5f968b4 100644
--- a/tests/unit/test_model.py
+++ b/tests/unit/test_model.py
@@ -73,11 +73,21 @@
         change.files = ['/COMMIT_MSG', 'docs/foo']
         self.assertFalse(self.job.changeMatches(change))
 
+    def test_change_matches_returns_false_for_single_matched_skip_if(self):
+        change = model.Change('project')
+        change.files = ['docs/foo']
+        self.assertFalse(self.job.changeMatches(change))
+
     def test_change_matches_returns_true_for_unmatched_skip_if(self):
         change = model.Change('project')
         change.files = ['/COMMIT_MSG', 'foo']
         self.assertTrue(self.job.changeMatches(change))
 
+    def test_change_matches_returns_true_for_single_unmatched_skip_if(self):
+        change = model.Change('project')
+        change.files = ['foo']
+        self.assertTrue(self.job.changeMatches(change))
+
     def test_job_sets_defaults_for_boolean_attributes(self):
         self.assertIsNotNone(self.job.voting)
 
diff --git a/tests/unit/test_multi_driver.py b/tests/unit/test_multi_driver.py
new file mode 100644
index 0000000..a1107de
--- /dev/null
+++ b/tests/unit/test_multi_driver.py
@@ -0,0 +1,45 @@
+# Copyright 2015 GoodData
+# Copyright (c) 2017 IBM Corp.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+from tests.base import ZuulTestCase
+
+
+class TestGerritAndGithub(ZuulTestCase):
+    config_file = 'zuul-connections-gerrit-and-github.conf'
+    tenant_config_file = 'config/multi-driver/main.yaml'
+
+    def setup_config(self):
+        super(TestGerritAndGithub, self).setup_config()
+
+    def test_multiple_project_gerrit_and_github(self):
+        self.executor_server.hold_jobs_in_build = True
+
+        A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
+        self.fake_gerrit.addEvent(A.getPatchsetCreatedEvent(1))
+
+        B = self.fake_github.openFakePullRequest('org/project1', 'master', 'B')
+        self.fake_github.emitEvent(B.getPullRequestOpenedEvent())
+
+        self.waitUntilSettled()
+
+        self.assertEqual(2, len(self.builds))
+        self.assertEqual('project-gerrit', self.builds[0].name)
+        self.assertEqual('project1-github', self.builds[1].name)
+        self.assertTrue(self.builds[0].hasChanges(A))
+        self.assertTrue(self.builds[1].hasChanges(B))
+
+        self.executor_server.hold_jobs_in_build = False
+        self.executor_server.release()
+        self.waitUntilSettled()
diff --git a/tests/unit/test_scheduler.py b/tests/unit/test_scheduler.py
index f67318d..f5c181b 100755
--- a/tests/unit/test_scheduler.py
+++ b/tests/unit/test_scheduler.py
@@ -530,8 +530,8 @@
         queue = self.gearman_server.getQueue()
         self.assertEqual(len(self.builds), 0)
         self.assertEqual(len(queue), 1)
-        self.assertEqual(queue[0].name, 'executor:execute')
-        job_args = json.loads(queue[0].arguments)
+        self.assertEqual(queue[0].name, b'executor:execute')
+        job_args = json.loads(queue[0].arguments.decode('utf8'))
         self.assertEqual(job_args['job'], 'project-merge')
         self.assertEqual(job_args['items'][0]['number'], '%d' % A.number)
 
@@ -547,17 +547,23 @@
         self.assertEqual(len(queue), 6)
 
         self.assertEqual(
-            json.loads(queue[0].arguments)['job'], 'project-test1')
+            json.loads(queue[0].arguments.decode('utf8'))['job'],
+            'project-test1')
         self.assertEqual(
-            json.loads(queue[1].arguments)['job'], 'project-test2')
+            json.loads(queue[1].arguments.decode('utf8'))['job'],
+            'project-test2')
         self.assertEqual(
-            json.loads(queue[2].arguments)['job'], 'project-test1')
+            json.loads(queue[2].arguments.decode('utf8'))['job'],
+            'project-test1')
         self.assertEqual(
-            json.loads(queue[3].arguments)['job'], 'project-test2')
+            json.loads(queue[3].arguments.decode('utf8'))['job'],
+            'project-test2')
         self.assertEqual(
-            json.loads(queue[4].arguments)['job'], 'project-test1')
+            json.loads(queue[4].arguments.decode('utf8'))['job'],
+            'project-test1')
         self.assertEqual(
-            json.loads(queue[5].arguments)['job'], 'project-test2')
+            json.loads(queue[5].arguments.decode('utf8'))['job'],
+            'project-test2')
 
         self.release(queue[0])
         self.waitUntilSettled()
@@ -984,8 +990,9 @@
         "Test that delayed check merge conflicts are handled properly"
 
         # Hold jobs in the gearman queue so that we can test whether
-        # the executor returns a merge failure after the scheduler has
-        # successfully merged.
+        # the executor sucesfully merges a change based on an old
+        # repo state (frozen by the scheduler) which would otherwise
+        # conflict.
         self.gearman_server.hold_jobs_in_queue = True
         A = self.fake_gerrit.addFakeChange('org/project',
                                            'master', 'A',
@@ -1002,6 +1009,7 @@
         self.fake_gerrit.addEvent(A.addApproval('approved', 1))
         self.waitUntilSettled()
         self.fake_gerrit.addEvent(B.getPatchsetCreatedEvent(1))
+        self.waitUntilSettled()
         self.fake_gerrit.addEvent(C.getPatchsetCreatedEvent(1))
         self.waitUntilSettled()
 
@@ -1057,9 +1065,12 @@
             dict(name='project-merge', result='SUCCESS', changes='1,1'),
             dict(name='project-test1', result='SUCCESS', changes='1,1'),
             dict(name='project-test2', result='SUCCESS', changes='1,1'),
-            dict(name='project-merge', result='MERGER_FAILURE', changes='2,1'),
-            dict(name='project-merge', result='MERGER_FAILURE',
-                 changes='2,1 3,1'),
+            dict(name='project-merge', result='SUCCESS', changes='2,1'),
+            dict(name='project-test1', result='SUCCESS', changes='2,1'),
+            dict(name='project-test2', result='SUCCESS', changes='2,1'),
+            dict(name='project-merge', result='SUCCESS', changes='2,1 3,1'),
+            dict(name='project-test1', result='SUCCESS', changes='2,1 3,1'),
+            dict(name='project-test2', result='SUCCESS', changes='2,1 3,1'),
         ], ordered=False)
 
     def test_post(self):
@@ -1499,8 +1510,8 @@
         tenant = self.sched.abide.tenants.get('tenant-one')
         trusted, project = tenant.getProject('org/project')
         url = self.fake_gerrit.getGitUrl(project)
-        self.merge_server.merger._addProject('review.example.com',
-                                             'org/project', url)
+        self.executor_server.merger._addProject('review.example.com',
+                                                'org/project', url)
         A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
         A.addPatchset(large=True)
         # TODOv3(jeblair): add hostname to upstream root
@@ -2164,12 +2175,6 @@
         self.assertEqual(set(['project-test-nomatch-starts-empty',
                               'project-test-nomatch-starts-full']), run_jobs)
 
-    @skip("Disabled for early v3 development")
-    def test_test_config(self):
-        "Test that we can test the config"
-        self.sched.testConfig(self.config.get('zuul', 'tenant_config'),
-                              self.connections)
-
     def test_queue_names(self):
         "Test shared change queue names"
         tenant = self.sched.abide.tenants.get('tenant-one')
@@ -2233,7 +2238,7 @@
         self.assertIn('Cache-Control', headers)
         self.assertIn('Last-Modified', headers)
         self.assertIn('Expires', headers)
-        data = f.read()
+        data = f.read().decode('utf8')
 
         self.executor_server.hold_jobs_in_build = False
         self.executor_server.release()
@@ -2293,13 +2298,11 @@
         self.assertEqual(A.data['status'], 'MERGED')
         self.assertEqual(A.reported, 2)
 
-    @skip("Disabled for early v3 development")
     def test_live_reconfiguration_merge_conflict(self):
         # A real-world bug: a change in a gate queue has a merge
         # conflict and a job is added to its project while it's
         # sitting in the queue.  The job gets added to the change and
         # enqueued and the change gets stuck.
-        self.worker.registerFunction('build:project-test3')
         self.executor_server.hold_jobs_in_build = True
 
         # This change is fine.  It's here to stop the queue long
@@ -2307,14 +2310,14 @@
         # reconfiguration, as well as to provide a conflict for the
         # next change.  This change will succeed and merge.
         A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
-        A.addPatchset(['conflict'])
+        A.addPatchset({'conflict': 'A'})
         A.addApproval('code-review', 2)
 
         # This change will be in merge conflict.  During the
         # reconfiguration, we will add a job.  We want to make sure
         # that doesn't cause it to get stuck.
         B = self.fake_gerrit.addFakeChange('org/project', 'master', 'B')
-        B.addPatchset(['conflict'])
+        B.addPatchset({'conflict': 'B'})
         B.addApproval('code-review', 2)
 
         self.fake_gerrit.addEvent(A.addApproval('approved', 1))
@@ -2330,8 +2333,8 @@
         self.assertEqual(len(self.history), 0)
 
         # Add the "project-test3" job.
-        self.updateConfigLayout(
-            'tests/fixtures/layout-live-reconfiguration-add-job.yaml')
+        self.commitConfigUpdate('common-config',
+                                'layouts/live-reconfiguration-add-job.yaml')
         self.sched.reconfigure(self.config)
         self.waitUntilSettled()
 
@@ -2353,19 +2356,17 @@
                          'SUCCESS')
         self.assertEqual(len(self.history), 4)
 
-    @skip("Disabled for early v3 development")
     def test_live_reconfiguration_failed_root(self):
         # An extrapolation of test_live_reconfiguration_merge_conflict
         # that tests a job added to a job tree with a failed root does
         # not run.
-        self.worker.registerFunction('build:project-test3')
         self.executor_server.hold_jobs_in_build = True
 
         # This change is fine.  It's here to stop the queue long
         # enough for the next change to be subject to the
         # reconfiguration.  This change will succeed and merge.
         A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
-        A.addPatchset(['conflict'])
+        A.addPatchset({'conflict': 'A'})
         A.addApproval('code-review', 2)
         self.fake_gerrit.addEvent(A.addApproval('approved', 1))
         self.waitUntilSettled()
@@ -2393,8 +2394,8 @@
         self.assertEqual(len(self.history), 2)
 
         # Add the "project-test3" job.
-        self.updateConfigLayout(
-            'tests/fixtures/layout-live-reconfiguration-add-job.yaml')
+        self.commitConfigUpdate('common-config',
+                                'layouts/live-reconfiguration-add-job.yaml')
         self.sched.reconfigure(self.config)
         self.waitUntilSettled()
 
@@ -2415,7 +2416,6 @@
         self.assertEqual(self.history[4].result, 'SUCCESS')
         self.assertEqual(len(self.history), 5)
 
-    @skip("Disabled for early v3 development")
     def test_live_reconfiguration_failed_job(self):
         # Test that a change with a removed failing job does not
         # disrupt reconfiguration.  If a change has a failed job and
@@ -2447,8 +2447,8 @@
         self.assertEqual(len(self.history), 2)
 
         # Remove the test1 job.
-        self.updateConfigLayout(
-            'tests/fixtures/layout-live-reconfiguration-failed-job.yaml')
+        self.commitConfigUpdate('common-config',
+                                'layouts/live-reconfiguration-failed-job.yaml')
         self.sched.reconfigure(self.config)
         self.waitUntilSettled()
 
@@ -2468,7 +2468,6 @@
         # Ensure the removed job was not included in the report.
         self.assertNotIn('project-test1', A.messages[0])
 
-    @skip("Disabled for early v3 development")
     def test_live_reconfiguration_shared_queue(self):
         # Test that a change with a failing job which was removed from
         # this project but otherwise still exists in the system does
@@ -2490,15 +2489,16 @@
         self.assertEqual(A.data['status'], 'NEW')
         self.assertEqual(A.reported, 0)
 
-        self.assertEqual(self.getJobFromHistory('project1-merge').result,
+        self.assertEqual(self.getJobFromHistory('project-merge').result,
                          'SUCCESS')
         self.assertEqual(self.getJobFromHistory(
             'project1-project2-integration').result, 'FAILURE')
         self.assertEqual(len(self.history), 2)
 
         # Remove the integration job.
-        self.updateConfigLayout(
-            'tests/fixtures/layout-live-reconfiguration-shared-queue.yaml')
+        self.commitConfigUpdate(
+            'common-config',
+            'layouts/live-reconfiguration-shared-queue.yaml')
         self.sched.reconfigure(self.config)
         self.waitUntilSettled()
 
@@ -2506,11 +2506,11 @@
         self.executor_server.release()
         self.waitUntilSettled()
 
-        self.assertEqual(self.getJobFromHistory('project1-merge').result,
+        self.assertEqual(self.getJobFromHistory('project-merge').result,
                          'SUCCESS')
-        self.assertEqual(self.getJobFromHistory('project1-test1').result,
+        self.assertEqual(self.getJobFromHistory('project-test1').result,
                          'SUCCESS')
-        self.assertEqual(self.getJobFromHistory('project1-test2').result,
+        self.assertEqual(self.getJobFromHistory('project-test2').result,
                          'SUCCESS')
         self.assertEqual(self.getJobFromHistory(
             'project1-project2-integration').result, 'FAILURE')
@@ -2522,7 +2522,6 @@
         # Ensure the removed job was not included in the report.
         self.assertNotIn('project1-project2-integration', A.messages[0])
 
-    @skip("Disabled for early v3 development")
     def test_double_live_reconfiguration_shared_queue(self):
         # This was a real-world regression.  A change is added to
         # gate; a reconfigure happens, a second change which depends
@@ -2724,7 +2723,7 @@
         req = urllib.request.Request(
             "http://localhost:%s/tenant-one/status" % port)
         f = urllib.request.urlopen(req)
-        data = f.read()
+        data = f.read().decode('utf8')
 
         self.executor_server.hold_jobs_in_build = False
         # Stop queuing timer triggered jobs so that the assertions
@@ -3351,7 +3350,7 @@
             if time.time() - start > 10:
                 raise Exception("Timeout waiting for gearman server to report "
                                 + "back to the client")
-            build = self.executor.builds.values()[0]
+            build = list(self.executor.builds.values())[0]
             if build.worker.name == "My Worker":
                 break
             else:
@@ -3524,7 +3523,7 @@
             if time.time() - start > 10:
                 raise Exception("Timeout waiting for gearman server to report "
                                 + "back to the client")
-            build = self.executor_client.builds.values()[0]
+            build = list(self.executor_client.builds.values())[0]
             if build.worker.name == "My Worker":
                 break
             else:
diff --git a/tests/unit/test_scheduler_cmd.py b/tests/unit/test_scheduler_cmd.py
new file mode 100644
index 0000000..ee6200f
--- /dev/null
+++ b/tests/unit/test_scheduler_cmd.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import os
+
+import testtools
+import zuul.cmd.scheduler
+
+from tests import base
+
+
+class TestSchedulerCmdArguments(testtools.TestCase):
+
+    def setUp(self):
+        super(TestSchedulerCmdArguments, self).setUp()
+        self.app = zuul.cmd.scheduler.Scheduler()
+
+    def test_test_config(self):
+        conf_path = os.path.join(base.FIXTURE_DIR, 'zuul.conf')
+        self.app.parse_arguments(['-t', '-c', conf_path])
+        self.assertTrue(self.app.args.validate)
+        self.app.read_config()
+        self.assertEqual(0, self.app.test_config())
diff --git a/tests/unit/test_webapp.py b/tests/unit/test_webapp.py
index 4511ec7..b2836ae 100644
--- a/tests/unit/test_webapp.py
+++ b/tests/unit/test_webapp.py
@@ -51,7 +51,7 @@
         req = urllib.request.Request(
             "http://localhost:%s/tenant-one/status" % self.port)
         f = urllib.request.urlopen(req)
-        data = json.loads(f.read())
+        data = json.loads(f.read().decode('utf8'))
 
         self.assertIn('pipelines', data)
 
@@ -60,7 +60,7 @@
         req = urllib.request.Request(
             "http://localhost:%s/tenant-one/status.json" % self.port)
         f = urllib.request.urlopen(req)
-        data = json.loads(f.read())
+        data = json.loads(f.read().decode('utf8'))
 
         self.assertIn('pipelines', data)
 
@@ -75,7 +75,7 @@
         req = urllib.request.Request(
             "http://localhost:%s/tenant-one/status/change/1,1" % self.port)
         f = urllib.request.urlopen(req)
-        data = json.loads(f.read())
+        data = json.loads(f.read().decode('utf8'))
 
         self.assertEqual(1, len(data), data)
         self.assertEqual("org/project", data[0]['project'])
@@ -83,13 +83,13 @@
         req = urllib.request.Request(
             "http://localhost:%s/tenant-one/status/change/2,1" % self.port)
         f = urllib.request.urlopen(req)
-        data = json.loads(f.read())
+        data = json.loads(f.read().decode('utf8'))
 
         self.assertEqual(1, len(data), data)
         self.assertEqual("org/project1", data[0]['project'], data)
 
     def test_webapp_keys(self):
-        with open(os.path.join(FIXTURE_DIR, 'public.pem')) as f:
+        with open(os.path.join(FIXTURE_DIR, 'public.pem'), 'rb') as f:
             public_pem = f.read()
 
         req = urllib.request.Request(
@@ -106,7 +106,7 @@
         req = urllib.request.Request(
             "http://localhost:%s/custom" % self.port)
         f = urllib.request.urlopen(req)
-        self.assertEqual('ok', f.read())
+        self.assertEqual(b'ok', f.read())
 
         self.webapp.unregister_path('/custom')
         self.assertRaises(urllib.error.HTTPError, urllib.request.urlopen, req)
diff --git a/tools/test-setup.sh b/tools/test-setup.sh
index 3bdedf5..d3697c9 100755
--- a/tools/test-setup.sh
+++ b/tools/test-setup.sh
@@ -35,3 +35,9 @@
     SET default_storage_engine=MYISAM;
     DROP DATABASE IF EXISTS openstack_citest;
     CREATE DATABASE openstack_citest CHARACTER SET utf8;"
+
+# TODO(pabelanger): Move this into bindep after we figure out how to enable our
+# PPA.
+sudo add-apt-repository ppa:openstack-ci-core/bubblewrap
+sudo apt-get update
+sudo apt-get --assume-yes install bubblewrap
diff --git a/tools/trigger-job.py b/tools/trigger-job.py
index 7123afc..dd69f1b 100755
--- a/tools/trigger-job.py
+++ b/tools/trigger-job.py
@@ -73,5 +73,6 @@
     while not job.complete:
         time.sleep(1)
 
+
 if __name__ == '__main__':
     main()
diff --git a/tools/update-storyboard.py b/tools/update-storyboard.py
index 12e6916..51434c9 100644
--- a/tools/update-storyboard.py
+++ b/tools/update-storyboard.py
@@ -96,5 +96,6 @@
         if ok_lanes and not task_found:
             add_task(sync, task, lanes[ok_lanes[0]])
 
+
 if __name__ == '__main__':
     main()
diff --git a/tox.ini b/tox.ini
index 8235483..9b97eca 100644
--- a/tox.ini
+++ b/tox.ini
@@ -51,6 +51,6 @@
 [flake8]
 # These are ignored intentionally in openstack-infra projects;
 # please don't submit patches that solely correct them or enable them.
-ignore = E125,E129,H
+ignore = E125,E129,E402,H,W503
 show-source = True
 exclude = .venv,.tox,dist,doc,build,*.egg
diff --git a/zuul/ansible/callback/zuul_stream.py b/zuul/ansible/callback/zuul_stream.py
index e6b3461..904316c 100644
--- a/zuul/ansible/callback/zuul_stream.py
+++ b/zuul/ansible/callback/zuul_stream.py
@@ -24,14 +24,14 @@
 
 
 def linesplit(socket):
-    buff = socket.recv(4096)
+    buff = socket.recv(4096).decode("utf-8")
     buffering = True
     while buffering:
         if "\n" in buff:
             (line, buff) = buff.split("\n", 1)
             yield line + "\n"
         else:
-            more = socket.recv(4096)
+            more = socket.recv(4096).decode("utf-8")
             if not more:
                 buffering = False
             else:
@@ -40,6 +40,32 @@
         yield buff
 
 
+def zuul_filter_result(result):
+    """Remove keys from shell/command output.
+
+    Zuul streams stdout into the log above, so including stdout and stderr
+    in the result dict that ansible displays in the logs is duplicate
+    noise. We keep stdout in the result dict so that other callback plugins
+    like ARA could also have access to it. But drop them here.
+
+    Remove changed so that we don't show a bunch of "changed" titles
+    on successful shell tasks, since that doesn't make sense from a Zuul
+    POV. The super class treats missing "changed" key as False.
+
+    Remove cmd because most of the script content where people want to
+    see the script run is run with -x. It's possible we may want to revist
+    this to be smarter about when we remove it - like, only remove it
+    if it has an embedded newline - so that for normal 'simple' uses
+    of cmd it'll echo what the command was for folks.
+    """
+
+    for key in ('changed', 'cmd',
+                'stderr', 'stderr_lines',
+                'stdout', 'stdout_lines'):
+        result.pop(key, None)
+    return result
+
+
 class CallbackModule(default.CallbackModule):
 
     '''
@@ -103,3 +129,37 @@
                         target=self._read_log, args=(host, ip))
                     p.daemon = True
                     p.start()
+
+    def v2_runner_on_failed(self, result, ignore_errors=False):
+        if result._task.action in ('command', 'shell'):
+            zuul_filter_result(result._result)
+        super(CallbackModule, self).v2_runner_on_failed(
+            result, ignore_errors=ignore_errors)
+
+    def v2_runner_on_ok(self, result):
+        if result._task.action in ('command', 'shell'):
+            zuul_filter_result(result._result)
+        else:
+            return super(CallbackModule, self).v2_runner_on_ok(result)
+
+        if self._play.strategy == 'free':
+            return super(CallbackModule, self).v2_runner_on_ok(result)
+
+        delegated_vars = result._result.get('_ansible_delegated_vars', None)
+
+        if delegated_vars:
+            msg = "ok: [{host} -> {delegated_host} %s]".format(
+                host=result._host.get_name(),
+                delegated_host=delegated_vars['ansible_host'])
+        else:
+            msg = "ok: [{host}]".format(host=result._host.get_name())
+
+        if result._task.loop and 'results' in result._result:
+            self._process_items(result)
+        else:
+            msg += " Runtime: {delta} Start: {start} End: {end}".format(
+                **result._result)
+
+        self._handle_warnings(result._result)
+
+        self._display.display(msg)
diff --git a/zuul/ansible/library/command.py b/zuul/ansible/library/command.py
index 328ae7b..52de5a4 100644
--- a/zuul/ansible/library/command.py
+++ b/zuul/ansible/library/command.py
@@ -123,6 +123,8 @@
 
 LOG_STREAM_FILE = '/tmp/console.log'
 PASSWD_ARG_RE = re.compile(r'^[-]{0,2}pass[-]?(word|wd)?')
+# List to save stdout log lines in as we collect them
+_log_lines = []
 
 
 class Console(object):
@@ -150,6 +152,7 @@
             line = fd.readline()
             if not line:
                 break
+            _log_lines.append(line)
             if not line.endswith('\n'):
                 line += '\n'
                 newline_warning = True
@@ -330,7 +333,8 @@
         # cmd.stdout.close()
 
         # ZUUL: stdout and stderr are in the console log file
-        stdout = ''
+        # ZUUL: return the saved log lines so we can ship them back
+        stdout = ''.join(_log_lines)
         stderr = ''
 
         rc = cmd.returncode
diff --git a/zuul/ansible/library/zuul_afs.py b/zuul/ansible/library/zuul_afs.py
index 3ba426b..710c15d 100644
--- a/zuul/ansible/library/zuul_afs.py
+++ b/zuul/ansible/library/zuul_afs.py
@@ -116,6 +116,7 @@
     module.exit_json(changed=True, build_roots=output)
 
 from ansible.module_utils.basic import *  # noqa
+from ansible.module_utils.basic import AnsibleModule
 
 if __name__ == '__main__':
     main()
diff --git a/zuul/ansible/library/zuul_console.py b/zuul/ansible/library/zuul_console.py
index 1932cf9..b1dc2d9 100644
--- a/zuul/ansible/library/zuul_console.py
+++ b/zuul/ansible/library/zuul_console.py
@@ -17,8 +17,10 @@
 
 import os
 import sys
+import select
 import socket
 import threading
+import time
 
 LOG_STREAM_FILE = '/tmp/console.log'
 LOG_STREAM_PORT = 19885
@@ -181,6 +183,7 @@
     s.run()
 
 from ansible.module_utils.basic import *  # noqa
+from ansible.module_utils.basic import AnsibleModule
 
 if __name__ == '__main__':
     main()
diff --git a/zuul/change_matcher.py b/zuul/change_matcher.py
index 1da1d2c..baea217 100644
--- a/zuul/change_matcher.py
+++ b/zuul/change_matcher.py
@@ -108,7 +108,9 @@
         yield self.commit_regex
 
     def matches(self, change):
-        if not (hasattr(change, 'files') and len(change.files) > 1):
+        if not (hasattr(change, 'files') and change.files):
+            return False
+        if len(change.files) == 1 and self.commit_regex.match(change.files[0]):
             return False
         for file_ in change.files:
             matched_file = False
diff --git a/zuul/cmd/__init__.py b/zuul/cmd/__init__.py
old mode 100644
new mode 100755
index f2a2612..d31c5b8
--- a/zuul/cmd/__init__.py
+++ b/zuul/cmd/__init__.py
@@ -98,6 +98,6 @@
         else:
             logging.basicConfig(level=logging.DEBUG)
 
-    def configure_connections(self):
+    def configure_connections(self, source_only=False):
         self.connections = zuul.lib.connections.ConnectionRegistry()
-        self.connections.configure(self.config)
+        self.connections.configure(self.config, source_only)
diff --git a/zuul/cmd/executor.py b/zuul/cmd/executor.py
old mode 100644
new mode 100755
index 96ba4b3..ea12b0b
--- a/zuul/cmd/executor.py
+++ b/zuul/cmd/executor.py
@@ -24,9 +24,11 @@
 
 import logging
 import os
+import pwd
 import socket
 import sys
 import signal
+import tempfile
 
 import zuul.cmd
 import zuul.executor.server
@@ -37,6 +39,9 @@
 # Similar situation with gear and statsd.
 
 
+FINGER_PORT = 79
+
+
 class Executor(zuul.cmd.ZuulApp):
 
     def parse_arguments(self):
@@ -72,15 +77,62 @@
         self.executor.stop()
         self.executor.join()
 
+    def start_log_streamer(self):
+        pipe_read, pipe_write = os.pipe()
+        child_pid = os.fork()
+        if child_pid == 0:
+            os.close(pipe_write)
+            import zuul.lib.log_streamer
+
+            self.log.info("Starting log streamer")
+            streamer = zuul.lib.log_streamer.LogStreamer(
+                self.user, '0.0.0.0', FINGER_PORT, self.jobroot_dir)
+
+            # Keep running until the parent dies:
+            pipe_read = os.fdopen(pipe_read)
+            pipe_read.read()
+            self.log.info("Stopping log streamer")
+            streamer.stop()
+            os._exit(0)
+        else:
+            os.close(pipe_read)
+            self.log_streamer_pid = child_pid
+
+    def change_privs(self):
+        '''
+        Drop our privileges to the zuul user.
+        '''
+        if os.getuid() != 0:
+            return
+        pw = pwd.getpwnam(self.user)
+        os.setgroups([])
+        os.setgid(pw.pw_gid)
+        os.setuid(pw.pw_uid)
+        os.umask(0o022)
+
     def main(self, daemon=True):
         # See comment at top of file about zuul imports
 
-        self.setup_logging('executor', 'log_config')
+        if self.config.has_option('executor', 'user'):
+            self.user = self.config.get('executor', 'user')
+        else:
+            self.user = 'zuul'
 
+        if self.config.has_option('zuul', 'jobroot_dir'):
+            self.jobroot_dir = os.path.expanduser(
+                self.config.get('zuul', 'jobroot_dir'))
+        else:
+            self.jobroot_dir = tempfile.gettempdir()
+
+        self.setup_logging('executor', 'log_config')
         self.log = logging.getLogger("zuul.Executor")
 
+        self.start_log_streamer()
+        self.change_privs()
+
         ExecutorServer = zuul.executor.server.ExecutorServer
         self.executor = ExecutorServer(self.config, self.connections,
+                                       jobdir_root=self.jobroot_dir,
                                        keep_jobdir=self.args.keep_jobdir)
         self.executor.start()
 
@@ -106,7 +158,7 @@
         server.send_command(server.args.command)
         sys.exit(0)
 
-    server.configure_connections()
+    server.configure_connections(source_only=True)
 
     if server.config.has_option('executor', 'pidfile'):
         pid_fn = os.path.expanduser(server.config.get('executor', 'pidfile'))
diff --git a/zuul/cmd/merger.py b/zuul/cmd/merger.py
old mode 100644
new mode 100755
index 797a990..686f34a
--- a/zuul/cmd/merger.py
+++ b/zuul/cmd/merger.py
@@ -77,7 +77,7 @@
     server.parse_arguments()
 
     server.read_config()
-    server.configure_connections()
+    server.configure_connections(source_only=True)
 
     if server.config.has_option('zuul', 'state_dir'):
         state_dir = os.path.expanduser(server.config.get('zuul', 'state_dir'))
diff --git a/zuul/cmd/scheduler.py b/zuul/cmd/scheduler.py
index f1d1015..5328bba 100755
--- a/zuul/cmd/scheduler.py
+++ b/zuul/cmd/scheduler.py
@@ -40,7 +40,7 @@
         super(Scheduler, self).__init__()
         self.gear_server_pid = None
 
-    def parse_arguments(self):
+    def parse_arguments(self, args=None):
         parser = argparse.ArgumentParser(description='Project gating system.')
         parser.add_argument('-c', dest='config',
                             help='specify the config file')
@@ -52,7 +52,7 @@
         parser.add_argument('--version', dest='version', action='version',
                             version=self._get_version(),
                             help='show zuul version')
-        self.args = parser.parse_args()
+        self.args = parser.parse_args(args)
 
     def reconfigure_handler(self, signum, frame):
         signal.signal(signal.SIGHUP, signal.SIG_IGN)
diff --git a/zuul/configloader.py b/zuul/configloader.py
index 070e731..7d03eef 100644
--- a/zuul/configloader.py
+++ b/zuul/configloader.py
@@ -10,6 +10,7 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+import base64
 from contextlib import contextmanager
 import copy
 import os
@@ -111,7 +112,7 @@
         r = super(ZuulSafeLoader, self).construct_mapping(node, deep)
         keys = frozenset(r.keys())
         if len(keys) == 1 and keys.intersection(self.zuul_node_types):
-            d = r.values()[0]
+            d = list(r.values())[0]
             if isinstance(d, dict):
                 d['_start_mark'] = node.start_mark
                 d['_source_context'] = self.zuul_context
@@ -142,7 +143,7 @@
     yaml_loader = yaml.SafeLoader
 
     def __init__(self, ciphertext):
-        self.ciphertext = ciphertext.decode('base64')
+        self.ciphertext = base64.b64decode(ciphertext)
 
     def __ne__(self, other):
         return not self.__eq__(other)
@@ -157,7 +158,8 @@
         return cls(node.value)
 
     def decrypt(self, private_key):
-        return encryption.decrypt_pkcs1_oaep(self.ciphertext, private_key)
+        return encryption.decrypt_pkcs1_oaep(self.ciphertext,
+                                             private_key).decode('utf8')
 
 
 class NodeSetParser(object):
@@ -229,7 +231,6 @@
 
         job = {vs.Required('name'): str,
                'parent': str,
-               'queue-name': str,
                'failure-message': str,
                'success-message': str,
                'failure-url': str,
@@ -493,7 +494,7 @@
                 attrs = dict(name=conf_job)
             elif isinstance(conf_job, dict):
                 # A dictionary in a job tree may override params
-                jobname, attrs = conf_job.items()[0]
+                jobname, attrs = list(conf_job.items())[0]
                 if attrs:
                     # We are overriding params, so make a new job def
                     attrs['name'] = jobname
@@ -518,6 +519,7 @@
             'templates': [str],
             'merge-mode': vs.Any('merge', 'merge-resolve',
                                  'cherry-pick'),
+            'default-branch': str,
             '_source_context': model.SourceContext,
             '_start_mark': yaml.Mark,
         }
@@ -553,15 +555,20 @@
             configs.extend([layout.project_templates[name]
                             for name in conf_templates])
             configs.append(project_template)
+            # Set the following values to the first one that we find and
+            # ignore subsequent settings.
             mode = conf.get('merge-mode')
             if mode and project_config.merge_mode is None:
-                # Set the merge mode to the first one that we find and
-                # ignore subsequent settings.
                 project_config.merge_mode = model.MERGER_MAP[mode]
+            default_branch = conf.get('default-branch')
+            if default_branch and project_config.default_branch is None:
+                project_config.default_branch = default_branch
         if project_config.merge_mode is None:
             # If merge mode was not specified in any project stanza,
             # set it to the default.
             project_config.merge_mode = model.MERGER_MAP['merge-resolve']
+        if project_config.default_branch is None:
+            project_config.default_branch = 'master'
         for pipeline in layout.pipelines.values():
             project_pipeline = model.ProjectPipelineConfig()
             queue_name = None
@@ -603,6 +610,8 @@
         methods = {
             'trigger': 'getTriggerSchema',
             'reporter': 'getReporterSchema',
+            'require': 'getRequireSchema',
+            'reject': 'getRejectSchema',
         }
 
         schema = {}
@@ -664,6 +673,10 @@
                     '_source_context': model.SourceContext,
                     '_start_mark': yaml.Mark,
                     }
+        pipeline['require'] = PipelineParser.getDriverSchema('require',
+                                                             connections)
+        pipeline['reject'] = PipelineParser.getDriverSchema('reject',
+                                                            connections)
         pipeline['trigger'] = vs.Required(
             PipelineParser.getDriverSchema('trigger', connections))
         for action in ['start', 'success', 'failure', 'merge-failure',
@@ -740,24 +753,21 @@
         pipeline.setManager(manager)
         layout.pipelines[conf['name']] = pipeline
 
-        if 'require' in conf or 'reject' in conf:
-            require = conf.get('require', {})
-            reject = conf.get('reject', {})
-            f = model.ChangeishFilter(
-                open=require.get('open'),
-                current_patchset=require.get('current-patchset'),
-                statuses=as_list(require.get('status')),
-                required_approvals=as_list(require.get('approval')),
-                reject_approvals=as_list(reject.get('approval'))
-            )
-            manager.changeish_filters.append(f)
+        for source_name, require_config in conf.get('require', {}).items():
+            source = connections.getSource(source_name)
+            manager.changeish_filters.extend(
+                source.getRequireFilters(require_config))
+
+        for source_name, reject_config in conf.get('reject', {}).items():
+            source = connections.getSource(source_name)
+            manager.changeish_filters.extend(
+                source.getRejectFilters(reject_config))
 
         for trigger_name, trigger_config in conf.get('trigger').items():
             trigger = connections.getTrigger(trigger_name, trigger_config)
             pipeline.triggers.append(trigger)
-
-            manager.event_filters += trigger.getEventFilters(
-                conf['trigger'][trigger_name])
+            manager.event_filters.extend(
+                trigger.getEventFilters(conf['trigger'][trigger_name]))
 
         return pipeline
 
diff --git a/zuul/driver/__init__.py b/zuul/driver/__init__.py
index 57b5cf9..671996a 100644
--- a/zuul/driver/__init__.py
+++ b/zuul/driver/__init__.py
@@ -191,6 +191,30 @@
         """
         pass
 
+    @abc.abstractmethod
+    def getRequireSchema(self):
+        """Get the schema for this driver's pipeline requirement filter.
+
+        This method is required by the interface.
+
+        :returns: A voluptuous schema.
+        :rtype: dict or Schema
+
+        """
+        pass
+
+    @abc.abstractmethod
+    def getRejectSchema(self):
+        """Get the schema for this driver's pipeline reject filter.
+
+        This method is required by the interface.
+
+        :returns: A voluptuous schema.
+        :rtype: dict or Schema
+
+        """
+        pass
+
 
 @six.add_metaclass(abc.ABCMeta)
 class ReporterInterface(object):
diff --git a/zuul/driver/gerrit/__init__.py b/zuul/driver/gerrit/__init__.py
index 3bc371e..76ab5b7 100644
--- a/zuul/driver/gerrit/__init__.py
+++ b/zuul/driver/gerrit/__init__.py
@@ -14,10 +14,10 @@
 
 from zuul.driver import Driver, ConnectionInterface, TriggerInterface
 from zuul.driver import SourceInterface, ReporterInterface
-import gerritconnection
-import gerrittrigger
-import gerritsource
-import gerritreporter
+from zuul.driver.gerrit import gerritconnection
+from zuul.driver.gerrit import gerrittrigger
+from zuul.driver.gerrit import gerritsource
+from zuul.driver.gerrit import gerritreporter
 
 
 class GerritDriver(Driver, ConnectionInterface, TriggerInterface,
@@ -41,3 +41,9 @@
 
     def getReporterSchema(self):
         return gerritreporter.getSchema()
+
+    def getRequireSchema(self):
+        return gerritsource.getRequireSchema()
+
+    def getRejectSchema(self):
+        return gerritsource.getRejectSchema()
diff --git a/zuul/driver/gerrit/gerritconnection.py b/zuul/driver/gerrit/gerritconnection.py
index 73979be..06962e5 100644
--- a/zuul/driver/gerrit/gerritconnection.py
+++ b/zuul/driver/gerrit/gerritconnection.py
@@ -20,14 +20,16 @@
 import time
 from six.moves import queue as Queue
 from six.moves import urllib
+from six.moves import shlex_quote
 import paramiko
 import logging
 import pprint
 import voluptuous as v
 
 from zuul.connection import BaseConnection
-from zuul.model import TriggerEvent, Change, Ref
+from zuul.model import Ref
 from zuul import exceptions
+from zuul.driver.gerrit.gerritmodel import GerritChange, GerritTriggerEvent
 
 
 # Walk the change dependency tree to find a cycle
@@ -72,7 +74,7 @@
         # should always be a constant number of seconds behind Gerrit.
         now = time.time()
         time.sleep(max((ts + self.delay) - now, 0.0))
-        event = TriggerEvent()
+        event = GerritTriggerEvent()
         event.type = data.get('type')
         event.trigger_name = 'gerrit'
         change = data.get('change')
@@ -171,11 +173,15 @@
         self._stopped = False
 
     def _read(self, fd):
-        l = fd.readline()
-        data = json.loads(l)
-        self.log.debug("Received data from Gerrit event stream: \n%s" %
-                       pprint.pformat(data))
-        self.gerrit_connection.addEvent(data)
+        while True:
+            l = fd.readline()
+            data = json.loads(l)
+            self.log.debug("Received data from Gerrit event stream: \n%s" %
+                           pprint.pformat(data))
+            self.gerrit_connection.addEvent(data)
+            # Continue until all the lines received are consumed
+            if fd._pos == fd._realpos:
+                break
 
     def _listen(self, stdout, stderr):
         poll = select.poll()
@@ -316,7 +322,7 @@
         if change and not refresh:
             return change
         if not change:
-            change = Change(None)
+            change = GerritChange(None)
             change.number = number
             change.patchset = patchset
         key = '%s,%s' % (change.number, change.patchset)
@@ -614,7 +620,7 @@
     def review(self, project, change, message, action={}):
         cmd = 'gerrit review --project %s' % project
         if message:
-            cmd += ' --message "%s"' % message
+            cmd += ' --message %s' % shlex_quote(message)
         for key, val in action.items():
             if val is True:
                 cmd += ' --%s' % key
@@ -719,13 +725,13 @@
         if stdin_data:
             stdin.write(stdin_data)
 
-        out = stdout.read()
+        out = stdout.read().decode('utf-8')
         self.log.debug("SSH received stdout:\n%s" % out)
 
         ret = stdout.channel.recv_exit_status()
         self.log.debug("SSH exit status: %s" % ret)
 
-        err = stderr.read()
+        err = stderr.read().decode('utf-8')
         self.log.debug("SSH received stderr:\n%s" % err)
         if ret:
             raise Exception("Gerrit error executing %s" % command)
diff --git a/zuul/driver/gerrit/gerritmodel.py b/zuul/driver/gerrit/gerritmodel.py
new file mode 100644
index 0000000..009a723
--- /dev/null
+++ b/zuul/driver/gerrit/gerritmodel.py
@@ -0,0 +1,343 @@
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import copy
+import re
+import time
+
+from zuul.model import EventFilter, RefFilter
+from zuul.model import Change, TriggerEvent
+from zuul.driver.util import time_to_seconds
+
+
+EMPTY_GIT_REF = '0' * 40  # git sha of all zeros, used during creates/deletes
+
+
+def normalize_category(name):
+    name = name.lower()
+    return re.sub(' ', '-', name)
+
+
+class GerritChange(Change):
+    def __init__(self, project):
+        super(GerritChange, self).__init__(project)
+        self.approvals = []
+
+
+class GerritTriggerEvent(TriggerEvent):
+    """Incoming event from an external system."""
+    def __init__(self):
+        super(GerritTriggerEvent, self).__init__()
+        self.approvals = []
+
+    def __repr__(self):
+        ret = '<GerritTriggerEvent %s %s' % (self.type,
+                                             self.canonical_project_name)
+
+        if self.branch:
+            ret += " %s" % self.branch
+        if self.change_number:
+            ret += " %s,%s" % (self.change_number, self.patch_number)
+        if self.approvals:
+            ret += ' ' + ', '.join(
+                ['%s:%s' % (a['type'], a['value']) for a in self.approvals])
+        ret += '>'
+
+        return ret
+
+    def isPatchsetCreated(self):
+        return 'patchset-created' == self.type
+
+    def isChangeAbandoned(self):
+        return 'change-abandoned' == self.type
+
+
+class GerritApprovalFilter(object):
+    def __init__(self, required_approvals=[], reject_approvals=[]):
+        self._required_approvals = copy.deepcopy(required_approvals)
+        self.required_approvals = self._tidy_approvals(required_approvals)
+        self._reject_approvals = copy.deepcopy(reject_approvals)
+        self.reject_approvals = self._tidy_approvals(reject_approvals)
+
+    def _tidy_approvals(self, approvals):
+        for a in approvals:
+            for k, v in a.items():
+                if k == 'username':
+                    a['username'] = re.compile(v)
+                elif k in ['email', 'email-filter']:
+                    a['email'] = re.compile(v)
+                elif k == 'newer-than':
+                    a[k] = time_to_seconds(v)
+                elif k == 'older-than':
+                    a[k] = time_to_seconds(v)
+            if 'email-filter' in a:
+                del a['email-filter']
+        return approvals
+
+    def _match_approval_required_approval(self, rapproval, approval):
+        # Check if the required approval and approval match
+        if 'description' not in approval:
+            return False
+        now = time.time()
+        by = approval.get('by', {})
+        for k, v in rapproval.items():
+            if k == 'username':
+                if (not v.search(by.get('username', ''))):
+                        return False
+            elif k == 'email':
+                if (not v.search(by.get('email', ''))):
+                        return False
+            elif k == 'newer-than':
+                t = now - v
+                if (approval['grantedOn'] < t):
+                        return False
+            elif k == 'older-than':
+                t = now - v
+                if (approval['grantedOn'] >= t):
+                    return False
+            else:
+                if not isinstance(v, list):
+                    v = [v]
+                if (normalize_category(approval['description']) != k or
+                        int(approval['value']) not in v):
+                    return False
+        return True
+
+    def matchesApprovals(self, change):
+        if (self.required_approvals and not change.approvals
+                or self.reject_approvals and not change.approvals):
+            # A change with no approvals can not match
+            return False
+
+        # TODO(jhesketh): If we wanted to optimise this slightly we could
+        # analyse both the REQUIRE and REJECT filters by looping over the
+        # approvals on the change and keeping track of what we have checked
+        # rather than needing to loop on the change approvals twice
+        return (self.matchesRequiredApprovals(change) and
+                self.matchesNoRejectApprovals(change))
+
+    def matchesRequiredApprovals(self, change):
+        # Check if any approvals match the requirements
+        for rapproval in self.required_approvals:
+            matches_rapproval = False
+            for approval in change.approvals:
+                if self._match_approval_required_approval(rapproval, approval):
+                    # We have a matching approval so this requirement is
+                    # fulfilled
+                    matches_rapproval = True
+                    break
+            if not matches_rapproval:
+                return False
+        return True
+
+    def matchesNoRejectApprovals(self, change):
+        # Check to make sure no approvals match a reject criteria
+        for rapproval in self.reject_approvals:
+            for approval in change.approvals:
+                if self._match_approval_required_approval(rapproval, approval):
+                    # A reject approval has been matched, so we reject
+                    # immediately
+                    return False
+        # To get here no rejects can have been matched so we should be good to
+        # queue
+        return True
+
+
+class GerritEventFilter(EventFilter, GerritApprovalFilter):
+    def __init__(self, trigger, types=[], branches=[], refs=[],
+                 event_approvals={}, comments=[], emails=[], usernames=[],
+                 required_approvals=[], reject_approvals=[],
+                 ignore_deletes=True):
+
+        EventFilter.__init__(self, trigger)
+
+        GerritApprovalFilter.__init__(self,
+                                      required_approvals=required_approvals,
+                                      reject_approvals=reject_approvals)
+
+        self._types = types
+        self._branches = branches
+        self._refs = refs
+        self._comments = comments
+        self._emails = emails
+        self._usernames = usernames
+        self.types = [re.compile(x) for x in types]
+        self.branches = [re.compile(x) for x in branches]
+        self.refs = [re.compile(x) for x in refs]
+        self.comments = [re.compile(x) for x in comments]
+        self.emails = [re.compile(x) for x in emails]
+        self.usernames = [re.compile(x) for x in usernames]
+        self.event_approvals = event_approvals
+        self.ignore_deletes = ignore_deletes
+
+    def __repr__(self):
+        ret = '<GerritEventFilter'
+
+        if self._types:
+            ret += ' types: %s' % ', '.join(self._types)
+        if self._branches:
+            ret += ' branches: %s' % ', '.join(self._branches)
+        if self._refs:
+            ret += ' refs: %s' % ', '.join(self._refs)
+        if self.ignore_deletes:
+            ret += ' ignore_deletes: %s' % self.ignore_deletes
+        if self.event_approvals:
+            ret += ' event_approvals: %s' % ', '.join(
+                ['%s:%s' % a for a in self.event_approvals.items()])
+        if self.required_approvals:
+            ret += ' required_approvals: %s' % ', '.join(
+                ['%s' % a for a in self._required_approvals])
+        if self.reject_approvals:
+            ret += ' reject_approvals: %s' % ', '.join(
+                ['%s' % a for a in self._reject_approvals])
+        if self._comments:
+            ret += ' comments: %s' % ', '.join(self._comments)
+        if self._emails:
+            ret += ' emails: %s' % ', '.join(self._emails)
+        if self._usernames:
+            ret += ' usernames: %s' % ', '.join(self._usernames)
+        ret += '>'
+
+        return ret
+
+    def matches(self, event, change):
+        # event types are ORed
+        matches_type = False
+        for etype in self.types:
+            if etype.match(event.type):
+                matches_type = True
+        if self.types and not matches_type:
+            return False
+
+        # branches are ORed
+        matches_branch = False
+        for branch in self.branches:
+            if branch.match(event.branch):
+                matches_branch = True
+        if self.branches and not matches_branch:
+            return False
+
+        # refs are ORed
+        matches_ref = False
+        if event.ref is not None:
+            for ref in self.refs:
+                if ref.match(event.ref):
+                    matches_ref = True
+        if self.refs and not matches_ref:
+            return False
+        if self.ignore_deletes and event.newrev == EMPTY_GIT_REF:
+            # If the updated ref has an empty git sha (all 0s),
+            # then the ref is being deleted
+            return False
+
+        # comments are ORed
+        matches_comment_re = False
+        for comment_re in self.comments:
+            if (event.comment is not None and
+                comment_re.search(event.comment)):
+                matches_comment_re = True
+        if self.comments and not matches_comment_re:
+            return False
+
+        # We better have an account provided by Gerrit to do
+        # email filtering.
+        if event.account is not None:
+            account_email = event.account.get('email')
+            # emails are ORed
+            matches_email_re = False
+            for email_re in self.emails:
+                if (account_email is not None and
+                        email_re.search(account_email)):
+                    matches_email_re = True
+            if self.emails and not matches_email_re:
+                return False
+
+            # usernames are ORed
+            account_username = event.account.get('username')
+            matches_username_re = False
+            for username_re in self.usernames:
+                if (account_username is not None and
+                    username_re.search(account_username)):
+                    matches_username_re = True
+            if self.usernames and not matches_username_re:
+                return False
+
+        # approvals are ANDed
+        for category, value in self.event_approvals.items():
+            matches_approval = False
+            for eapp in event.approvals:
+                if (normalize_category(eapp['description']) == category and
+                    int(eapp['value']) == int(value)):
+                    matches_approval = True
+            if not matches_approval:
+                return False
+
+        # required approvals are ANDed (reject approvals are ORed)
+        if not self.matchesApprovals(change):
+            return False
+
+        return True
+
+
+class GerritRefFilter(RefFilter, GerritApprovalFilter):
+    def __init__(self, open=None, current_patchset=None,
+                 statuses=[], required_approvals=[],
+                 reject_approvals=[]):
+        RefFilter.__init__(self)
+
+        GerritApprovalFilter.__init__(self,
+                                      required_approvals=required_approvals,
+                                      reject_approvals=reject_approvals)
+
+        self.open = open
+        self.current_patchset = current_patchset
+        self.statuses = statuses
+
+    def __repr__(self):
+        ret = '<GerritRefFilter'
+
+        if self.open is not None:
+            ret += ' open: %s' % self.open
+        if self.current_patchset is not None:
+            ret += ' current-patchset: %s' % self.current_patchset
+        if self.statuses:
+            ret += ' statuses: %s' % ', '.join(self.statuses)
+        if self.required_approvals:
+            ret += (' required-approvals: %s' %
+                    str(self.required_approvals))
+        if self.reject_approvals:
+            ret += (' reject-approvals: %s' %
+                    str(self.reject_approvals))
+        ret += '>'
+
+        return ret
+
+    def matches(self, change):
+        if self.open is not None:
+            if self.open != change.open:
+                return False
+
+        if self.current_patchset is not None:
+            if self.current_patchset != change.is_current_patchset:
+                return False
+
+        if self.statuses:
+            if change.status not in self.statuses:
+                return False
+
+        # required approvals are ANDed (reject approvals are ORed)
+        if not self.matchesApprovals(change):
+            return False
+
+        return True
diff --git a/zuul/driver/gerrit/gerritreporter.py b/zuul/driver/gerrit/gerritreporter.py
index a855db3..f8e8b03 100644
--- a/zuul/driver/gerrit/gerritreporter.py
+++ b/zuul/driver/gerrit/gerritreporter.py
@@ -15,7 +15,7 @@
 import logging
 import voluptuous as v
 
-
+from zuul.driver.gerrit.gerritsource import GerritSource
 from zuul.reporter import BaseReporter
 
 
@@ -25,14 +25,25 @@
     name = 'gerrit'
     log = logging.getLogger("zuul.GerritReporter")
 
-    def report(self, source, pipeline, item):
+    def report(self, pipeline, item):
         """Send a message to gerrit."""
+
+        # If the source is no GerritSource we cannot report anything here.
+        if not isinstance(item.change.project.source, GerritSource):
+            return
+
+        # For supporting several Gerrit connections we also must filter by
+        # the canonical hostname.
+        if item.change.project.source.connection.canonical_hostname != \
+                self.connection.canonical_hostname:
+            return
+
         message = self._formatItemReport(pipeline, item)
 
         self.log.debug("Report change %s, params %s, message: %s" %
                        (item.change, self.config, message))
         changeid = '%s,%s' % (item.change.number, item.change.patchset)
-        item.change._ref_sha = source.getRefSha(
+        item.change._ref_sha = item.change.project.source.getRefSha(
             item.change.project, 'refs/heads/' + item.change.branch)
 
         return self.connection.review(item.change.project.name, changeid,
diff --git a/zuul/driver/gerrit/gerritsource.py b/zuul/driver/gerrit/gerritsource.py
index e6230df..6cb0c39 100644
--- a/zuul/driver/gerrit/gerritsource.py
+++ b/zuul/driver/gerrit/gerritsource.py
@@ -13,8 +13,11 @@
 # under the License.
 
 import logging
+import voluptuous as vs
 from zuul.source import BaseSource
 from zuul.model import Project
+from zuul.driver.gerrit.gerritmodel import GerritRefFilter
+from zuul.driver.util import scalar_or_list, to_list
 
 
 class GerritSource(BaseSource):
@@ -59,3 +62,41 @@
 
     def _getGitwebUrl(self, project, sha=None):
         return self.connection._getGitwebUrl(project, sha)
+
+    def getRequireFilters(self, config):
+        f = GerritRefFilter(
+            open=config.get('open'),
+            current_patchset=config.get('current-patchset'),
+            statuses=to_list(config.get('status')),
+            required_approvals=to_list(config.get('approval')),
+        )
+        return [f]
+
+    def getRejectFilters(self, config):
+        f = GerritRefFilter(
+            reject_approvals=to_list(config.get('approval')),
+        )
+        return [f]
+
+
+approval = vs.Schema({'username': str,
+                      'email-filter': str,
+                      'email': str,
+                      'older-than': str,
+                      'newer-than': str,
+                      }, extra=vs.ALLOW_EXTRA)
+
+
+def getRequireSchema():
+    require = {'approval': scalar_or_list(approval),
+               'open': bool,
+               'current-patchset': bool,
+               'status': scalar_or_list(str)}
+
+    return require
+
+
+def getRejectSchema():
+    reject = {'approval': scalar_or_list(approval)}
+
+    return reject
diff --git a/zuul/driver/gerrit/gerrittrigger.py b/zuul/driver/gerrit/gerrittrigger.py
index 70c65fd..706b7df 100644
--- a/zuul/driver/gerrit/gerrittrigger.py
+++ b/zuul/driver/gerrit/gerrittrigger.py
@@ -14,8 +14,9 @@
 
 import logging
 import voluptuous as v
-from zuul.model import EventFilter
 from zuul.trigger import BaseTrigger
+from zuul.driver.gerrit.gerritmodel import GerritEventFilter
+from zuul.driver.util import scalar_or_list, to_list
 
 
 class GerritTrigger(BaseTrigger):
@@ -23,43 +24,36 @@
     log = logging.getLogger("zuul.GerritTrigger")
 
     def getEventFilters(self, trigger_conf):
-        def toList(item):
-            if not item:
-                return []
-            if isinstance(item, list):
-                return item
-            return [item]
-
         efilters = []
-        for trigger in toList(trigger_conf):
+        for trigger in to_list(trigger_conf):
             approvals = {}
-            for approval_dict in toList(trigger.get('approval')):
+            for approval_dict in to_list(trigger.get('approval')):
                 for key, val in approval_dict.items():
                     approvals[key] = val
             # Backwards compat for *_filter versions of these args
-            comments = toList(trigger.get('comment'))
+            comments = to_list(trigger.get('comment'))
             if not comments:
-                comments = toList(trigger.get('comment_filter'))
-            emails = toList(trigger.get('email'))
+                comments = to_list(trigger.get('comment_filter'))
+            emails = to_list(trigger.get('email'))
             if not emails:
-                emails = toList(trigger.get('email_filter'))
-            usernames = toList(trigger.get('username'))
+                emails = to_list(trigger.get('email_filter'))
+            usernames = to_list(trigger.get('username'))
             if not usernames:
-                usernames = toList(trigger.get('username_filter'))
+                usernames = to_list(trigger.get('username_filter'))
             ignore_deletes = trigger.get('ignore-deletes', True)
-            f = EventFilter(
+            f = GerritEventFilter(
                 trigger=self,
-                types=toList(trigger['event']),
-                branches=toList(trigger.get('branch')),
-                refs=toList(trigger.get('ref')),
+                types=to_list(trigger['event']),
+                branches=to_list(trigger.get('branch')),
+                refs=to_list(trigger.get('ref')),
                 event_approvals=approvals,
                 comments=comments,
                 emails=emails,
                 usernames=usernames,
                 required_approvals=(
-                    toList(trigger.get('require-approval'))
+                    to_list(trigger.get('require-approval'))
                 ),
-                reject_approvals=toList(
+                reject_approvals=to_list(
                     trigger.get('reject-approval')
                 ),
                 ignore_deletes=ignore_deletes
@@ -80,8 +74,6 @@
 
 
 def getSchema():
-    def toList(x):
-        return v.Any([x], x)
     variable_dict = v.Schema(dict)
 
     approval = v.Schema({'username': str,
@@ -93,25 +85,25 @@
 
     gerrit_trigger = {
         v.Required('event'):
-            toList(v.Any('patchset-created',
-                         'draft-published',
-                         'change-abandoned',
-                         'change-restored',
-                         'change-merged',
-                         'comment-added',
-                         'ref-updated')),
-        'comment_filter': toList(str),
-        'comment': toList(str),
-        'email_filter': toList(str),
-        'email': toList(str),
-        'username_filter': toList(str),
-        'username': toList(str),
-        'branch': toList(str),
-        'ref': toList(str),
+            scalar_or_list(v.Any('patchset-created',
+                                 'draft-published',
+                                 'change-abandoned',
+                                 'change-restored',
+                                 'change-merged',
+                                 'comment-added',
+                                 'ref-updated')),
+        'comment_filter': scalar_or_list(str),
+        'comment': scalar_or_list(str),
+        'email_filter': scalar_or_list(str),
+        'email': scalar_or_list(str),
+        'username_filter': scalar_or_list(str),
+        'username': scalar_or_list(str),
+        'branch': scalar_or_list(str),
+        'ref': scalar_or_list(str),
         'ignore-deletes': bool,
-        'approval': toList(variable_dict),
-        'require-approval': toList(approval),
-        'reject-approval': toList(approval),
+        'approval': scalar_or_list(variable_dict),
+        'require-approval': scalar_or_list(approval),
+        'reject-approval': scalar_or_list(approval),
     }
 
     return gerrit_trigger
diff --git a/zuul/driver/git/__init__.py b/zuul/driver/git/__init__.py
index abedf6a..0faa036 100644
--- a/zuul/driver/git/__init__.py
+++ b/zuul/driver/git/__init__.py
@@ -13,8 +13,8 @@
 # under the License.
 
 from zuul.driver import Driver, ConnectionInterface, SourceInterface
-import gitconnection
-import gitsource
+from zuul.driver.git import gitconnection
+from zuul.driver.git import gitsource
 
 
 class GitDriver(Driver, ConnectionInterface, SourceInterface):
@@ -25,3 +25,9 @@
 
     def getSource(self, connection):
         return gitsource.GitSource(self, connection)
+
+    def getRequireSchema(self):
+        return {}
+
+    def getRejectSchema(self):
+        return {}
diff --git a/zuul/driver/git/gitsource.py b/zuul/driver/git/gitsource.py
index 485a6e4..61a328e 100644
--- a/zuul/driver/git/gitsource.py
+++ b/zuul/driver/git/gitsource.py
@@ -53,3 +53,9 @@
 
     def getProjectOpenChanges(self, project):
         raise NotImplemented()
+
+    def getRequireFilters(self, config):
+        return []
+
+    def getRejectFilters(self, config):
+        return []
diff --git a/zuul/driver/github/__init__.py b/zuul/driver/github/__init__.py
index 2d6829d..f75e907 100644
--- a/zuul/driver/github/__init__.py
+++ b/zuul/driver/github/__init__.py
@@ -14,10 +14,10 @@
 
 from zuul.driver import Driver, ConnectionInterface, TriggerInterface
 from zuul.driver import SourceInterface
-import githubconnection
-import githubtrigger
-import githubsource
-import githubreporter
+from zuul.driver.github import githubconnection
+from zuul.driver.github import githubtrigger
+from zuul.driver.github import githubsource
+from zuul.driver.github import githubreporter
 
 
 class GithubDriver(Driver, ConnectionInterface, TriggerInterface,
@@ -41,3 +41,9 @@
 
     def getReporterSchema(self):
         return githubreporter.getSchema()
+
+    def getRequireSchema(self):
+        return githubsource.getRequireSchema()
+
+    def getRejectSchema(self):
+        return githubsource.getRejectSchema()
diff --git a/zuul/driver/github/githubconnection.py b/zuul/driver/github/githubconnection.py
index f2a8fc0..27ece54 100644
--- a/zuul/driver/github/githubconnection.py
+++ b/zuul/driver/github/githubconnection.py
@@ -12,11 +12,18 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+import collections
+import datetime
 import logging
 import hmac
 import hashlib
 import time
 
+import cachecontrol
+from cachecontrol.cache import DictCache
+import iso8601
+import jwt
+import requests
 import webob
 import webob.dec
 import voluptuous as v
@@ -24,8 +31,28 @@
 from github3.exceptions import MethodNotAllowed
 
 from zuul.connection import BaseConnection
-from zuul.model import PullRequest, Ref, GithubTriggerEvent
+from zuul.model import Ref
 from zuul.exceptions import MergeFailure
+from zuul.driver.github.githubmodel import PullRequest, GithubTriggerEvent
+
+ACCESS_TOKEN_URL = 'https://api.github.com/installations/%s/access_tokens'
+PREVIEW_JSON_ACCEPT = 'application/vnd.github.machine-man-preview+json'
+
+
+class UTC(datetime.tzinfo):
+    """UTC"""
+
+    def utcoffset(self, dt):
+        return datetime.timedelta(0)
+
+    def tzname(self, dt):
+        return "UTC"
+
+    def dst(self, dt):
+        return datetime.timedelta(0)
+
+
+utc = UTC()
 
 
 class GithubWebhookListener():
@@ -64,17 +91,38 @@
             raise webob.exc.HTTPBadRequest(message)
 
         try:
-            event = method(request)
+            json_body = request.json_body
+        except:
+            message = 'Exception deserializing JSON body'
+            self.log.exception(message)
+            raise webob.exc.HTTPBadRequest(message)
+
+        # If there's any installation mapping information in the body then
+        # update the project mapping before any requests are made.
+        installation_id = json_body.get('installation', {}).get('id')
+        project_name = json_body.get('repository', {}).get('full_name')
+
+        if installation_id and project_name:
+            old_id = self.connection.installation_map.get(project_name)
+
+            if old_id and old_id != installation_id:
+                msg = "Unexpected installation_id change for %s. %d -> %d."
+                self.log.warning(msg, project_name, old_id, installation_id)
+
+            self.connection.installation_map[project_name] = installation_id
+
+        try:
+            event = method(json_body)
         except:
             self.log.exception('Exception when handling event:')
+            event = None
 
         if event:
             event.project_hostname = self.connection.canonical_hostname
             self.log.debug('Scheduling github event: {0}'.format(event.type))
             self.connection.sched.addEvent(event)
 
-    def _event_push(self, request):
-        body = request.json_body
+    def _event_push(self, body):
         base_repo = body.get('repository')
 
         event = GithubTriggerEvent()
@@ -94,12 +142,12 @@
 
         return event
 
-    def _event_pull_request(self, request):
-        body = request.json_body
+    def _event_pull_request(self, body):
         action = body.get('action')
         pr_body = body.get('pull_request')
 
         event = self._pull_request_to_event(pr_body)
+        event.account = self._get_sender(body)
 
         event.type = 'pull_request'
         if action == 'opened':
@@ -121,9 +169,8 @@
 
         return event
 
-    def _event_issue_comment(self, request):
+    def _event_issue_comment(self, body):
         """Handles pull request comments"""
-        body = request.json_body
         action = body.get('action')
         if action != 'created':
             return
@@ -135,11 +182,48 @@
             return
 
         event = self._pull_request_to_event(pr_body)
+        event.account = self._get_sender(body)
         event.comment = body.get('comment').get('body')
         event.type = 'pull_request'
         event.action = 'comment'
         return event
 
+    def _event_pull_request_review(self, body):
+        """Handles pull request reviews"""
+        pr_body = body.get('pull_request')
+        if pr_body is None:
+            return
+
+        review = body.get('review')
+        if review is None:
+            return
+
+        event = self._pull_request_to_event(pr_body)
+        event.state = review.get('state')
+        event.account = self._get_sender(body)
+        event.type = 'pull_request_review'
+        event.action = body.get('action')
+        return event
+
+    def _event_status(self, body):
+        action = body.get('action')
+        if action == 'pending':
+            return
+        pr_body = self.connection.getPullBySha(body['sha'])
+        if pr_body is None:
+            return
+
+        event = self._pull_request_to_event(pr_body)
+        event.account = self._get_sender(body)
+        event.type = 'pull_request'
+        event.action = 'status'
+        # Github API is silly. Webhook blob sets author data in
+        # 'sender', but API call to get status puts it in 'creator'.
+        # Duplicate the data so our code can look in one place
+        body['creator'] = body['sender']
+        event.status = "%s:%s:%s" % _status_as_tuple(body)
+        return event
+
     def _issue_to_pull_request(self, body):
         number = body.get('issue').get('number')
         project_name = body.get('repository').get('full_name')
@@ -191,26 +275,75 @@
         event.refspec = "refs/pull/" + str(pr_body.get('number')) + "/head"
         event.patch_number = head.get('sha')
 
+        event.title = pr_body.get('title')
+
         return event
 
+    def _get_sender(self, body):
+        login = body.get('sender').get('login')
+        if login:
+            return self.connection.getUser(login)
+
+
+class GithubUser(collections.Mapping):
+    log = logging.getLogger('zuul.GithubUser')
+
+    def __init__(self, github, username):
+        self._github = github
+        self._username = username
+        self._data = None
+
+    def __getitem__(self, key):
+        if self._data is None:
+            self._data = self._init_data()
+        return self._data[key]
+
+    def __iter__(self):
+        return iter(self._data)
+
+    def __len__(self):
+        return len(self._data)
+
+    def _init_data(self):
+        user = self._github.user(self._username)
+        log_rate_limit(self.log, self._github)
+        data = {
+            'username': user.login,
+            'name': user.name,
+            'email': user.email
+        }
+        return data
+
 
 class GithubConnection(BaseConnection):
     driver_name = 'github'
     log = logging.getLogger("connection.github")
     payload_path = 'payload'
-    git_user = 'git'
-    git_host = 'github.com'
 
     def __init__(self, driver, connection_name, connection_config):
         super(GithubConnection, self).__init__(
             driver, connection_name, connection_config)
-        self.github = None
-        self.canonical_hostname = self.connection_config.get(
-            'canonical_hostname', 'github.com')
         self._change_cache = {}
         self.projects = {}
+        self.git_ssh_key = self.connection_config.get('sshkey')
+        self.git_host = self.connection_config.get('git_host', 'github.com')
+        self.canonical_hostname = self.connection_config.get(
+            'canonical_hostname', self.git_host)
         self.source = driver.getSource(self)
-        self._git_ssh = bool(self.connection_config.get('sshkey', None))
+
+        self._github = None
+        self.app_id = None
+        self.app_key = None
+
+        self.installation_map = {}
+        self.installation_token_cache = {}
+
+        # NOTE(jamielennox): Better here would be to cache to memcache or file
+        # or something external - but zuul already sucks at restarting so in
+        # memory probably doesn't make this much worse.
+        self.cache_adapter = cachecontrol.CacheControlAdapter(
+            DictCache(),
+            cache_etags=True)
 
     def onLoad(self):
         webhook_listener = GithubWebhookListener(self)
@@ -221,16 +354,107 @@
     def onStop(self):
         self.unregisterHttpHandler(self.payload_path)
 
-    def _authenticateGithubAPI(self):
-        token = self.connection_config.get('api_token', None)
-        if token is not None:
-            self.github = github3.login(token=token)
-            self.log.info("Github API Authentication successful.")
+    def _createGithubClient(self):
+        if self.git_host != 'github.com':
+            url = 'https://%s/' % self.git_host
+            github = github3.GitHubEnterprise(url)
         else:
-            self.github = None
-            self.log.info(
-                "No Github credentials found in zuul configuration, cannot "
-                "authenticate.")
+            github = github3.GitHub()
+
+        # anything going through requests to http/s goes through cache
+        github.session.mount('http://', self.cache_adapter)
+        github.session.mount('https://', self.cache_adapter)
+        return github
+
+    def _authenticateGithubAPI(self):
+        config = self.connection_config
+
+        api_token = config.get('api_token')
+
+        app_id = config.get('app_id')
+        app_key = None
+        app_key_file = config.get('app_key')
+
+        self._github = self._createGithubClient()
+
+        if api_token:
+            self._github.login(token=api_token)
+
+        if app_key_file:
+            try:
+                with open(app_key_file, 'r') as f:
+                    app_key = f.read()
+            except IOError:
+                m = "Failed to open app key file for reading: %s"
+                self.log.error(m, app_key_file)
+
+        if (app_id or app_key) and \
+                not (app_id and app_key):
+            self.log.warning("You must provide an app_id and "
+                             "app_key to use installation based "
+                             "authentication")
+
+            return
+
+        if app_id:
+            self.app_id = int(app_id)
+        if app_key:
+            self.app_key = app_key
+
+    def _get_installation_key(self, project, user_id=None):
+        installation_id = self.installation_map.get(project)
+
+        if not installation_id:
+            self.log.error("No installation ID available for project %s",
+                           project)
+            return ''
+
+        now = datetime.datetime.now(utc)
+        token, expiry = self.installation_token_cache.get(installation_id,
+                                                          (None, None))
+
+        if ((not expiry) or (not token) or (now >= expiry)):
+            expiry = now + datetime.timedelta(minutes=5)
+
+            data = {'iat': now, 'exp': expiry, 'iss': self.app_id}
+            app_token = jwt.encode(data,
+                                   self.app_key,
+                                   algorithm='RS256')
+
+            url = ACCESS_TOKEN_URL % installation_id
+            headers = {'Accept': PREVIEW_JSON_ACCEPT,
+                       'Authorization': 'Bearer %s' % app_token}
+            json_data = {'user_id': user_id} if user_id else None
+
+            response = requests.post(url, headers=headers, json=json_data)
+            response.raise_for_status()
+
+            data = response.json()
+
+            expiry = iso8601.parse_date(data['expires_at'])
+            expiry -= datetime.timedelta(minutes=2)
+            token = data['token']
+
+            self.installation_token_cache[installation_id] = (token, expiry)
+
+        return token
+
+    def getGithubClient(self,
+                        project=None,
+                        user_id=None,
+                        use_app=True):
+        # if you're authenticating for a project and you're an integration then
+        # you need to use the installation specific token. There are some
+        # operations that are not yet supported by integrations so
+        # use_app lets you use api_key auth.
+        if use_app and project and self.app_id:
+            github = self._createGithubClient()
+            github.login(token=self._get_installation_key(project, user_id))
+            return github
+
+        # if we're using api_key authentication then this is already token
+        # authenticated, if not then anonymous is the best we have.
+        return self._github
 
     def maintainCache(self, relevant):
         for key, change in self._change_cache.items():
@@ -250,23 +474,37 @@
             change.url = event.change_url
             change.updated_at = self._ghTimestampToDate(event.updated_at)
             change.patchset = event.patch_number
+            change.files = self.getPullFileNames(project, change.number)
+            change.title = event.title
+            change.status = self._get_statuses(project, event.patch_number)
+            change.reviews = self.getPullReviews(project, change.number)
+            change.source_event = event
+            change.open = self.getPullOpen(project, change.number)
+            change.is_current_patchset = self.getIsCurrent(project,
+                                                           change.number,
+                                                           event.patch_number)
         elif event.ref:
             change = Ref(project)
             change.ref = event.ref
             change.oldrev = event.oldrev
             change.newrev = event.newrev
             change.url = self.getGitwebUrl(project, sha=event.newrev)
+            change.source_event = event
         else:
             change = Ref(project)
         return change
 
     def getGitUrl(self, project):
-        if self._git_ssh:
-            url = 'ssh://%s@%s/%s.git' % \
-                (self.git_user, self.git_host, project)
-        else:
-            url = 'https://%s/%s' % (self.git_host, project)
-        return url
+        if self.git_ssh_key:
+            return 'ssh://git@%s/%s.git' % (self.git_host, project)
+
+        if self.app_id:
+            installation_key = self._get_installation_key(project)
+            return 'https://x-access-token:%s@%s/%s' % (installation_key,
+                                                        self.git_host,
+                                                        project)
+
+        return 'https://%s/%s' % (self.git_host, project)
 
     def getGitwebUrl(self, project, sha=None):
         url = 'https://%s/%s' % (self.git_host, project)
@@ -281,17 +519,22 @@
         self.projects[project.name] = project
 
     def getProjectBranches(self, project):
+        github = self.getGithubClient()
         owner, proj = project.name.split('/')
-        repository = self.github.repository(owner, proj)
+        repository = github.repository(owner, proj)
         branches = [branch.name for branch in repository.branches()]
+        log_rate_limit(self.log, github)
         return branches
 
     def getPullUrl(self, project, number):
         return '%s/pull/%s' % (self.getGitwebUrl(project), number)
 
     def getPull(self, project_name, number):
+        github = self.getGithubClient(project_name)
         owner, proj = project_name.split('/')
-        return self.github.pull_request(owner, proj, number).as_dict()
+        pr = github.pull_request(owner, proj, number).as_dict()
+        log_rate_limit(self.log, github)
+        return pr
 
     def canMerge(self, change, allow_needs):
         # This API call may get a false (null) while GitHub is calculating
@@ -306,42 +549,230 @@
         # For now, just send back a True value.
         return True
 
-    def commentPull(self, project, pr_number, message):
+    def getPullBySha(self, sha):
+        query = '%s type:pr is:open' % sha
+        pulls = []
+        github = self.getGithubClient()
+        for issue in github.search_issues(query=query):
+            pr_url = issue.issue.pull_request().as_dict().get('url')
+            if not pr_url:
+                continue
+            # the issue provides no good description of the project :\
+            owner, project, _, number = pr_url.split('/')[4:]
+            github = self.getGithubClient("%s/%s" % (owner, project))
+            pr = github.pull_request(owner, project, number)
+            if pr.head.sha != sha:
+                continue
+            if pr.as_dict() in pulls:
+                continue
+            pulls.append(pr.as_dict())
+
+        log_rate_limit(self.log, github)
+        if len(pulls) > 1:
+            raise Exception('Multiple pulls found with head sha %s' % sha)
+
+        if len(pulls) == 0:
+            return None
+        return pulls.pop()
+
+    def getPullFileNames(self, project, number):
+        github = self.getGithubClient(project)
+        owner, proj = project.name.split('/')
+        filenames = [f.filename for f in
+                     github.pull_request(owner, proj, number).files()]
+        log_rate_limit(self.log, github)
+        return filenames
+
+    def getPullReviews(self, project, number):
+        owner, proj = project.name.split('/')
+
+        revs = self._getPullReviews(owner, proj, number)
+
+        reviews = {}
+        for rev in revs:
+            user = rev.get('user').get('login')
+            review = {
+                'by': {
+                    'username': user,
+                    'email': rev.get('user').get('email'),
+                },
+                'grantedOn': int(time.mktime(self._ghTimestampToDate(
+                                             rev.get('submitted_at')))),
+            }
+
+            review['type'] = rev.get('state').lower()
+            review['submitted_at'] = rev.get('submitted_at')
+
+            # Get user's rights. A user always has read to leave a review
+            review['permission'] = 'read'
+            permission = self.getRepoPermission(project.name, user)
+            if permission == 'write':
+                review['permission'] = 'write'
+            if permission == 'admin':
+                review['permission'] = 'admin'
+
+            if user not in reviews:
+                reviews[user] = review
+            else:
+                # if there are multiple reviews per user, keep the newest
+                # note that this breaks the ability to set the 'older-than'
+                # option on a review requirement.
+                if review['grantedOn'] > reviews[user]['grantedOn']:
+                    reviews[user] = review
+
+        return reviews.values()
+
+    def _getPullReviews(self, owner, project, number):
+        # make a list out of the reviews so that we complete our
+        # API transaction
+        # reviews are not yet supported by integrations, use api_key:
+        # https://platform.github.community/t/api-endpoint-for-pr-reviews/409
+        github = self.getGithubClient("%s/%s" % (owner, project),
+                                      use_app=False)
+        reviews = [review.as_dict() for review in
+                   github.pull_request(owner, project, number).reviews()]
+
+        log_rate_limit(self.log, github)
+        return reviews
+
+    def getUser(self, login):
+        return GithubUser(self.getGithubClient(), login)
+
+    def getUserUri(self, login):
+        return 'https://%s/%s' % (self.git_host, login)
+
+    def getRepoPermission(self, project, login):
+        github = self.getGithubClient(project)
         owner, proj = project.split('/')
-        repository = self.github.repository(owner, proj)
+        # This gets around a missing API call
+        # need preview header
+        headers = {'Accept': 'application/vnd.github.korra-preview'}
+
+        # Create a repo object
+        repository = github.repository(owner, project)
+        # Build up a URL
+        url = repository._build_url('collaborators', login, 'permission',
+                                    base_url=repository._api)
+        # Get the data
+        perms = repository._get(url, headers=headers)
+
+        log_rate_limit(self.log, github)
+
+        # no known user, maybe deleted since review?
+        if perms.status_code == 404:
+            return 'none'
+
+        # get permissions from the data
+        return perms.json()['permission']
+
+    def commentPull(self, project, pr_number, message):
+        github = self.getGithubClient(project)
+        owner, proj = project.split('/')
+        repository = github.repository(owner, proj)
         pull_request = repository.issue(pr_number)
         pull_request.create_comment(message)
+        log_rate_limit(self.log, github)
 
-    def mergePull(self, project, pr_number, sha=None):
+    def mergePull(self, project, pr_number, commit_message='', sha=None):
+        github = self.getGithubClient(project)
         owner, proj = project.split('/')
-        pull_request = self.github.pull_request(owner, proj, pr_number)
+        pull_request = github.pull_request(owner, proj, pr_number)
         try:
-            result = pull_request.merge(sha=sha)
+            result = pull_request.merge(commit_message=commit_message, sha=sha)
         except MethodNotAllowed as e:
             raise MergeFailure('Merge was not successful due to mergeability'
                                ' conflict, original error is %s' % e)
+        log_rate_limit(self.log, github)
         if not result:
             raise Exception('Pull request was not merged')
 
+    def getCommitStatuses(self, project, sha):
+        github = self.getGithubClient(project)
+        owner, proj = project.split('/')
+        repository = github.repository(owner, proj)
+        commit = repository.commit(sha)
+        # make a list out of the statuses so that we complete our
+        # API transaction
+        statuses = [status.as_dict() for status in commit.statuses()]
+
+        log_rate_limit(self.log, github)
+        return statuses
+
     def setCommitStatus(self, project, sha, state, url='', description='',
                         context=''):
+        github = self.getGithubClient(project)
         owner, proj = project.split('/')
-        repository = self.github.repository(owner, proj)
+        repository = github.repository(owner, proj)
         repository.create_status(sha, state, url, description, context)
+        log_rate_limit(self.log, github)
 
     def labelPull(self, project, pr_number, label):
+        github = self.getGithubClient(project)
         owner, proj = project.split('/')
-        pull_request = self.github.issue(owner, proj, pr_number)
+        pull_request = github.issue(owner, proj, pr_number)
         pull_request.add_labels(label)
+        log_rate_limit(self.log, github)
 
     def unlabelPull(self, project, pr_number, label):
+        github = self.getGithubClient(project)
         owner, proj = project.split('/')
-        pull_request = self.github.issue(owner, proj, pr_number)
+        pull_request = github.issue(owner, proj, pr_number)
         pull_request.remove_label(label)
+        log_rate_limit(self.log, github)
+
+    def getPullOpen(self, project, number):
+        pr = self.getPull(project, number)
+        return pr.get('state') == 'open'
+
+    def getIsCurrent(self, project, number, sha):
+        pr = self.getPull(project, number)
+        return pr.get('head').get('sha') == sha
 
     def _ghTimestampToDate(self, timestamp):
         return time.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')
 
+    def _get_statuses(self, project, sha):
+        # A ref can have more than one status from each context,
+        # however the API returns them in order, newest first.
+        # So we can keep track of which contexts we've already seen
+        # and throw out the rest. Our unique key is based on
+        # the user and the context, since context is free form and anybody
+        # can put whatever they want there. We want to ensure we track it
+        # by user, so that we can require/trigger by user too.
+        seen = []
+        statuses = []
+        for status in self.getCommitStatuses(project.name, sha):
+            stuple = _status_as_tuple(status)
+            if "%s:%s" % (stuple[0], stuple[1]) not in seen:
+                statuses.append("%s:%s:%s" % stuple)
+                seen.append("%s:%s" % (stuple[0], stuple[1]))
+
+        return statuses
+
+
+def _status_as_tuple(status):
+    """Translate a status into a tuple of user, context, state"""
+
+    creator = status.get('creator')
+    if not creator:
+        user = "Unknown"
+    else:
+        user = creator.get('login')
+    context = status.get('context')
+    state = status.get('state')
+    return (user, context, state)
+
+
+def log_rate_limit(log, github):
+    try:
+        rate_limit = github.rate_limit()
+        remaining = rate_limit['resources']['core']['remaining']
+        reset = rate_limit['resources']['core']['reset']
+    except:
+        return
+    log.debug('GitHub API rate limit remaining: %s reset: %s' %
+              (remaining, reset))
+
 
 def getSchema():
     github_connection = v.Any(str, v.Schema({}, extra=True))
diff --git a/zuul/driver/github/githubmodel.py b/zuul/driver/github/githubmodel.py
new file mode 100644
index 0000000..3e25115
--- /dev/null
+++ b/zuul/driver/github/githubmodel.py
@@ -0,0 +1,309 @@
+# Copyright 2015 Hewlett-Packard Development Company, L.P.
+# Copyright 2017 IBM Corp.
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import copy
+import re
+import time
+
+from zuul.model import Change, TriggerEvent, EventFilter, RefFilter
+from zuul.driver.util import time_to_seconds
+
+
+EMPTY_GIT_REF = '0' * 40  # git sha of all zeros, used during creates/deletes
+
+
+class PullRequest(Change):
+    def __init__(self, project):
+        super(PullRequest, self).__init__(project)
+        self.updated_at = None
+        self.title = None
+        self.reviews = []
+
+    def isUpdateOf(self, other):
+        if (hasattr(other, 'number') and self.number == other.number and
+            hasattr(other, 'patchset') and self.patchset != other.patchset and
+            hasattr(other, 'updated_at') and
+            self.updated_at > other.updated_at):
+            return True
+        return False
+
+
+class GithubTriggerEvent(TriggerEvent):
+    def __init__(self):
+        super(GithubTriggerEvent, self).__init__()
+        self.title = None
+        self.label = None
+        self.unlabel = None
+
+    def isPatchsetCreated(self):
+        if self.type == 'pull_request':
+            return self.action in ['opened', 'changed']
+        return False
+
+    def isChangeAbandoned(self):
+        if self.type == 'pull_request':
+            return 'closed' == self.action
+        return False
+
+
+class GithubCommonFilter(object):
+    def __init__(self, required_reviews=[], required_statuses=[]):
+        self._required_reviews = copy.deepcopy(required_reviews)
+        self.required_reviews = self._tidy_reviews(required_reviews)
+        self.required_statuses = required_statuses
+
+    def _tidy_reviews(self, reviews):
+        for r in reviews:
+            for k, v in r.items():
+                if k == 'username':
+                    r['username'] = re.compile(v)
+                elif k == 'email':
+                    r['email'] = re.compile(v)
+                elif k == 'newer-than':
+                    r[k] = time_to_seconds(v)
+                elif k == 'older-than':
+                    r[k] = time_to_seconds(v)
+        return reviews
+
+    def _match_review_required_review(self, rreview, review):
+        # Check if the required review and review match
+        now = time.time()
+        by = review.get('by', {})
+        for k, v in rreview.items():
+            if k == 'username':
+                if (not v.search(by.get('username', ''))):
+                        return False
+            elif k == 'email':
+                if (not v.search(by.get('email', ''))):
+                        return False
+            elif k == 'newer-than':
+                t = now - v
+                if (review['grantedOn'] < t):
+                        return False
+            elif k == 'older-than':
+                t = now - v
+                if (review['grantedOn'] >= t):
+                    return False
+            elif k == 'type':
+                if review['type'] != v:
+                    return False
+            elif k == 'permission':
+                # If permission is read, we've matched. You must have read
+                # to provide a review. Write or admin permission is different.
+                if v != 'read':
+                    if review['permission'] != v:
+                        return False
+        return True
+
+    def matchesReviews(self, change):
+        if self.required_reviews and not change.reviews:
+            # No reviews means no matching
+            return False
+
+        return self.matchesRequiredReviews(change)
+
+    def matchesRequiredReviews(self, change):
+        for rreview in self.required_reviews:
+            matches_review = False
+            for review in change.reviews:
+                if self._match_review_required_review(rreview, review):
+                    # Consider matched if any review matches
+                    matches_review = True
+                    break
+            if not matches_review:
+                return False
+        return True
+
+    def matchesRequiredStatuses(self, change):
+        # statuses are ORed
+        # A PR head can have multiple statuses on it. If the change
+        # statuses and the filter statuses are a null intersection, there
+        # are no matches and we return false
+        if self.required_statuses:
+            if set(change.status).isdisjoint(set(self.required_statuses)):
+                return False
+        return True
+
+
+class GithubEventFilter(EventFilter, GithubCommonFilter):
+    def __init__(self, trigger, types=[], branches=[], refs=[],
+                 comments=[], actions=[], labels=[], unlabels=[],
+                 states=[], statuses=[], required_statuses=[],
+                 ignore_deletes=True):
+
+        EventFilter.__init__(self, trigger)
+
+        GithubCommonFilter.__init__(self, required_statuses=required_statuses)
+
+        self._types = types
+        self._branches = branches
+        self._refs = refs
+        self._comments = comments
+        self.types = [re.compile(x) for x in types]
+        self.branches = [re.compile(x) for x in branches]
+        self.refs = [re.compile(x) for x in refs]
+        self.comments = [re.compile(x) for x in comments]
+        self.actions = actions
+        self.labels = labels
+        self.unlabels = unlabels
+        self.states = states
+        self.statuses = statuses
+        self.required_statuses = required_statuses
+        self.ignore_deletes = ignore_deletes
+
+    def __repr__(self):
+        ret = '<GithubEventFilter'
+
+        if self._types:
+            ret += ' types: %s' % ', '.join(self._types)
+        if self._branches:
+            ret += ' branches: %s' % ', '.join(self._branches)
+        if self._refs:
+            ret += ' refs: %s' % ', '.join(self._refs)
+        if self.ignore_deletes:
+            ret += ' ignore_deletes: %s' % self.ignore_deletes
+        if self._comments:
+            ret += ' comments: %s' % ', '.join(self._comments)
+        if self.actions:
+            ret += ' actions: %s' % ', '.join(self.actions)
+        if self.labels:
+            ret += ' labels: %s' % ', '.join(self.labels)
+        if self.unlabels:
+            ret += ' unlabels: %s' % ', '.join(self.unlabels)
+        if self.states:
+            ret += ' states: %s' % ', '.join(self.states)
+        if self.statuses:
+            ret += ' statuses: %s' % ', '.join(self.statuses)
+        if self.required_statuses:
+            ret += ' required_statuses: %s' % ', '.join(self.required_statuses)
+        ret += '>'
+
+        return ret
+
+    def matches(self, event, change):
+        # event types are ORed
+        matches_type = False
+        for etype in self.types:
+            if etype.match(event.type):
+                matches_type = True
+        if self.types and not matches_type:
+            return False
+
+        # branches are ORed
+        matches_branch = False
+        for branch in self.branches:
+            if branch.match(event.branch):
+                matches_branch = True
+        if self.branches and not matches_branch:
+            return False
+
+        # refs are ORed
+        matches_ref = False
+        if event.ref is not None:
+            for ref in self.refs:
+                if ref.match(event.ref):
+                    matches_ref = True
+        if self.refs and not matches_ref:
+            return False
+        if self.ignore_deletes and event.newrev == EMPTY_GIT_REF:
+            # If the updated ref has an empty git sha (all 0s),
+            # then the ref is being deleted
+            return False
+
+        # comments are ORed
+        matches_comment_re = False
+        for comment_re in self.comments:
+            if (event.comment is not None and
+                comment_re.search(event.comment)):
+                matches_comment_re = True
+        if self.comments and not matches_comment_re:
+            return False
+
+        # actions are ORed
+        matches_action = False
+        for action in self.actions:
+            if (event.action == action):
+                matches_action = True
+        if self.actions and not matches_action:
+            return False
+
+        # labels are ORed
+        if self.labels and event.label not in self.labels:
+            return False
+
+        # unlabels are ORed
+        if self.unlabels and event.unlabel not in self.unlabels:
+            return False
+
+        # states are ORed
+        if self.states and event.state not in self.states:
+            return False
+
+        # statuses are ORed
+        if self.statuses and event.status not in self.statuses:
+            return False
+
+        if not self.matchesRequiredStatuses(change):
+            return False
+
+        return True
+
+
+class GithubRefFilter(RefFilter, GithubCommonFilter):
+    def __init__(self, statuses=[], required_reviews=[], open=None,
+                 current_patchset=None):
+        RefFilter.__init__(self)
+
+        GithubCommonFilter.__init__(self, required_reviews=required_reviews,
+                                    required_statuses=statuses)
+        self.statuses = statuses
+        self.open = open
+        self.current_patchset = current_patchset
+
+    def __repr__(self):
+        ret = '<GithubRefFilter'
+
+        if self.statuses:
+            ret += ' statuses: %s' % ', '.join(self.statuses)
+        if self.required_reviews:
+            ret += (' required-reviews: %s' %
+                    str(self.required_reviews))
+        if self.open:
+            ret += ' open: %s' % self.open
+        if self.current_patchset:
+            ret += ' current-patchset: %s' % self.current_patchset
+
+        ret += '>'
+
+        return ret
+
+    def matches(self, change):
+        if not self.matchesRequiredStatuses(change):
+            return False
+
+        if self.open is not None:
+            if self.open != change.open:
+                return False
+
+        if self.current_patchset is not None:
+            if self.current_patchset != change.is_current_patchset:
+                return False
+
+        # required reviews are ANDed
+        if not self.matchesReviews(change):
+            return False
+
+        return True
diff --git a/zuul/driver/github/githubreporter.py b/zuul/driver/github/githubreporter.py
index 159103c..68c6af0 100644
--- a/zuul/driver/github/githubreporter.py
+++ b/zuul/driver/github/githubreporter.py
@@ -18,6 +18,7 @@
 
 from zuul.reporter import BaseReporter
 from zuul.exceptions import MergeFailure
+from zuul.driver.util import scalar_or_list
 
 
 class GithubReporter(BaseReporter):
@@ -38,7 +39,7 @@
         if not isinstance(self._unlabels, list):
             self._unlabels = [self._unlabels]
 
-    def report(self, source, pipeline, item):
+    def report(self, pipeline, item):
         """Comment on PR and set commit status."""
         if self._create_comment:
             self.addPullComment(pipeline, item)
@@ -49,11 +50,14 @@
         if (self._merge and
             hasattr(item.change, 'number')):
             self.mergePull(item)
+            if not item.change.is_merged:
+                msg = self._formatItemReportMergeFailure(pipeline, item)
+                self.addPullComment(pipeline, item, msg)
         if self._labels or self._unlabels:
             self.setLabels(item)
 
-    def addPullComment(self, pipeline, item):
-        message = self._formatItemReport(pipeline, item)
+    def addPullComment(self, pipeline, item, comment=None):
+        message = comment or self._formatItemReport(pipeline, item)
         project = item.change.project.name
         pr_number = item.change.number
         self.log.debug(
@@ -64,11 +68,14 @@
     def setPullStatus(self, pipeline, item):
         project = item.change.project.name
         sha = item.change.patchset
-        context = pipeline.name
+        context = '%s/%s' % (pipeline.layout.tenant.name, pipeline.name)
         state = self._commit_status
         url = ''
         if self.connection.sched.config.has_option('zuul', 'status_url'):
-            url = self.connection.sched.config.get('zuul', 'status_url')
+            base = self.connection.sched.config.get('zuul', 'status_url')
+            url = '%s/#%s,%s' % (base,
+                                 item.change.number,
+                                 item.change.patchset)
         description = ''
         if pipeline.description:
             description = pipeline.description
@@ -88,13 +95,22 @@
         sha = item.change.patchset
         self.log.debug('Reporting change %s, params %s, merging via API' %
                        (item.change, self.config))
-        try:
-            self.connection.mergePull(project, pr_number, sha)
-        except MergeFailure:
-            time.sleep(2)
-            self.log.debug('Trying to merge change %s again...' % item.change)
-            self.connection.mergePull(project, pr_number, sha)
-        item.change.is_merged = True
+        message = self._formatMergeMessage(item.change)
+
+        for i in [1, 2]:
+            try:
+                self.connection.mergePull(project, pr_number, message, sha)
+                item.change.is_merged = True
+                return
+            except MergeFailure:
+                self.log.exception(
+                    'Merge attempt of change %s  %s/2 failed.' %
+                    (item.change, i), exc_info=True)
+                if i == 1:
+                    time.sleep(2)
+        self.log.warning(
+            'Merge of change %s failed after 2 attempts, giving up' %
+            item.change)
 
     def setLabels(self, item):
         project = item.change.project.name
@@ -110,16 +126,40 @@
         for label in self._unlabels:
                 self.connection.unlabelPull(project, pr_number, label)
 
+    def _formatMergeMessage(self, change):
+        message = ''
+
+        if change.title:
+            message += change.title
+
+        account = change.source_event.account
+        if not account:
+            return message
+
+        username = account['username']
+        name = account['name']
+        email = account['email']
+        message += '\n\nReviewed-by: '
+
+        if name:
+            message += name
+        if email:
+            if name:
+                message += ' '
+            message += '<' + email + '>'
+        if name or email:
+            message += '\n             '
+        message += self.connection.getUserUri(username)
+
+        return message
+
 
 def getSchema():
-    def toList(x):
-        return v.Any([x], x)
-
     github_reporter = v.Schema({
         'status': v.Any('pending', 'success', 'failure'),
         'comment': bool,
         'merge': bool,
-        'label': toList(str),
-        'unlabel': toList(str)
+        'label': scalar_or_list(str),
+        'unlabel': scalar_or_list(str)
     })
     return github_reporter
diff --git a/zuul/driver/github/githubsource.py b/zuul/driver/github/githubsource.py
index a638122..58ca2b9 100644
--- a/zuul/driver/github/githubsource.py
+++ b/zuul/driver/github/githubsource.py
@@ -14,9 +14,12 @@
 
 import logging
 import time
+import voluptuous as v
 
 from zuul.source import BaseSource
 from zuul.model import Project
+from zuul.driver.github.githubmodel import GithubRefFilter
+from zuul.driver.util import scalar_or_list, to_list
 
 
 class GithubSource(BaseSource):
@@ -84,5 +87,43 @@
         """Get the git-web url for a project."""
         return self.connection.getGitwebUrl(project, sha)
 
+    def getPullFiles(self, project, number):
+        """Get filenames of the pull request"""
+        return self.connection.getPullFileNames(project, number)
+
     def _ghTimestampToDate(self, timestamp):
         return time.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')
+
+    def getRequireFilters(self, config):
+        f = GithubRefFilter(
+            statuses=to_list(config.get('status')),
+            required_reviews=to_list(config.get('review')),
+            open=config.get('open'),
+            current_patchset=config.get('current-patchset'),
+        )
+        return [f]
+
+    def getRejectFilters(self, config):
+        return []
+
+
+review = v.Schema({'username': str,
+                   'email': str,
+                   'older-than': str,
+                   'newer-than': str,
+                   'type': str,
+                   'permission': v.Any('read', 'write', 'admin'),
+                   })
+
+
+def getRequireSchema():
+    require = {'status': scalar_or_list(str),
+               'review': scalar_or_list(review),
+               'open': bool,
+               'current-patchset': bool}
+    return require
+
+
+def getRejectSchema():
+    reject = {'review': scalar_or_list(review)}
+    return reject
diff --git a/zuul/driver/github/githubtrigger.py b/zuul/driver/github/githubtrigger.py
index 541c783..328879d 100644
--- a/zuul/driver/github/githubtrigger.py
+++ b/zuul/driver/github/githubtrigger.py
@@ -14,8 +14,9 @@
 
 import logging
 import voluptuous as v
-from zuul.model import EventFilter
 from zuul.trigger import BaseTrigger
+from zuul.driver.github.githubmodel import GithubEventFilter
+from zuul.driver.util import scalar_or_list, to_list
 
 
 class GithubTrigger(BaseTrigger):
@@ -23,24 +24,20 @@
     log = logging.getLogger("zuul.trigger.GithubTrigger")
 
     def getEventFilters(self, trigger_config):
-        def toList(item):
-            if not item:
-                return []
-            if isinstance(item, list):
-                return item
-            return [item]
-
         efilters = []
-        for trigger in toList(trigger_config):
-            f = EventFilter(
+        for trigger in to_list(trigger_config):
+            f = GithubEventFilter(
                 trigger=self,
-                types=toList(trigger['event']),
-                actions=toList(trigger.get('action')),
-                branches=toList(trigger.get('branch')),
-                refs=toList(trigger.get('ref')),
-                comments=toList(trigger.get('comment')),
-                labels=toList(trigger.get('label')),
-                unlabels=toList(trigger.get('unlabel'))
+                types=to_list(trigger['event']),
+                actions=to_list(trigger.get('action')),
+                branches=to_list(trigger.get('branch')),
+                refs=to_list(trigger.get('ref')),
+                comments=to_list(trigger.get('comment')),
+                labels=to_list(trigger.get('label')),
+                unlabels=to_list(trigger.get('unlabel')),
+                states=to_list(trigger.get('state')),
+                statuses=to_list(trigger.get('status')),
+                required_statuses=to_list(trigger.get('require-status'))
             )
             efilters.append(f)
 
@@ -51,19 +48,20 @@
 
 
 def getSchema():
-    def toList(x):
-        return v.Any([x], x)
-
     github_trigger = {
         v.Required('event'):
-            toList(v.Any('pull_request',
-                         'push')),
-        'action': toList(str),
-        'branch': toList(str),
-        'ref': toList(str),
-        'comment': toList(str),
-        'label': toList(str),
-        'unlabel': toList(str),
+            scalar_or_list(v.Any('pull_request',
+                                 'pull_request_review',
+                                 'push')),
+        'action': scalar_or_list(str),
+        'branch': scalar_or_list(str),
+        'ref': scalar_or_list(str),
+        'comment': scalar_or_list(str),
+        'label': scalar_or_list(str),
+        'unlabel': scalar_or_list(str),
+        'state': scalar_or_list(str),
+        'require-status': scalar_or_list(str),
+        'status': scalar_or_list(str)
     }
 
     return github_trigger
diff --git a/zuul/driver/smtp/__init__.py b/zuul/driver/smtp/__init__.py
index 0745644..b914c81 100644
--- a/zuul/driver/smtp/__init__.py
+++ b/zuul/driver/smtp/__init__.py
@@ -13,8 +13,8 @@
 # under the License.
 
 from zuul.driver import Driver, ConnectionInterface, ReporterInterface
-import smtpconnection
-import smtpreporter
+from zuul.driver.smtp import smtpconnection
+from zuul.driver.smtp import smtpreporter
 
 
 class SMTPDriver(Driver, ConnectionInterface, ReporterInterface):
diff --git a/zuul/driver/smtp/smtpreporter.py b/zuul/driver/smtp/smtpreporter.py
index dd618ef..35eb69f 100644
--- a/zuul/driver/smtp/smtpreporter.py
+++ b/zuul/driver/smtp/smtpreporter.py
@@ -24,7 +24,7 @@
     name = 'smtp'
     log = logging.getLogger("zuul.SMTPReporter")
 
-    def report(self, source, pipeline, item):
+    def report(self, pipeline, item):
         """Send the compiled report message via smtp."""
         message = self._formatItemReport(pipeline, item)
 
diff --git a/zuul/driver/sql/__init__.py b/zuul/driver/sql/__init__.py
index a5f8923..3748e47 100644
--- a/zuul/driver/sql/__init__.py
+++ b/zuul/driver/sql/__init__.py
@@ -13,8 +13,8 @@
 # under the License.
 
 from zuul.driver import Driver, ConnectionInterface, ReporterInterface
-import sqlconnection
-import sqlreporter
+from zuul.driver.sql import sqlconnection
+from zuul.driver.sql import sqlreporter
 
 
 class SQLDriver(Driver, ConnectionInterface, ReporterInterface):
diff --git a/zuul/driver/sql/alembic_reporter/env.py b/zuul/driver/sql/alembic_reporter/env.py
index 56a5b7e..4542a22 100644
--- a/zuul/driver/sql/alembic_reporter/env.py
+++ b/zuul/driver/sql/alembic_reporter/env.py
@@ -64,6 +64,7 @@
         with context.begin_transaction():
             context.run_migrations()
 
+
 if context.is_offline_mode():
     run_migrations_offline()
 else:
diff --git a/zuul/driver/sql/sqlreporter.py b/zuul/driver/sql/sqlreporter.py
index d6e547d..46d538a 100644
--- a/zuul/driver/sql/sqlreporter.py
+++ b/zuul/driver/sql/sqlreporter.py
@@ -31,7 +31,7 @@
         # TODO(jeblair): document this is stored as NULL if unspecified
         self.result_score = config.get('score', None)
 
-    def report(self, source, pipeline, item):
+    def report(self, pipeline, item):
         """Create an entry into a database."""
 
         if not self.connection.tables_established:
diff --git a/zuul/driver/timer/__init__.py b/zuul/driver/timer/__init__.py
index 115e6af..cdaea74 100644
--- a/zuul/driver/timer/__init__.py
+++ b/zuul/driver/timer/__init__.py
@@ -20,8 +20,8 @@
 from apscheduler.triggers.cron import CronTrigger
 
 from zuul.driver import Driver, TriggerInterface
-from zuul.model import TriggerEvent
-import timertrigger
+from zuul.driver.timer import timertrigger
+from zuul.driver.timer.timermodel import TimerTriggerEvent
 
 
 class TimerDriver(Driver, TriggerInterface):
@@ -81,7 +81,7 @@
     def _onTrigger(self, tenant, pipeline_name, timespec):
         for project_name in tenant.layout.project_configs.keys():
             project_hostname, project_name = project_name.split('/', 1)
-            event = TriggerEvent()
+            event = TimerTriggerEvent()
             event.type = 'timer'
             event.timespec = timespec
             event.forced_pipeline = pipeline_name
diff --git a/zuul/driver/timer/timermodel.py b/zuul/driver/timer/timermodel.py
new file mode 100644
index 0000000..d6f1415
--- /dev/null
+++ b/zuul/driver/timer/timermodel.py
@@ -0,0 +1,62 @@
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import re
+
+from zuul.model import EventFilter, TriggerEvent
+
+
+class TimerEventFilter(EventFilter):
+    def __init__(self, trigger, types=[], timespecs=[]):
+        EventFilter.__init__(self, trigger)
+
+        self._types = types
+        self.types = [re.compile(x) for x in types]
+        self.timespecs = timespecs
+
+    def __repr__(self):
+        ret = '<TimerEventFilter'
+
+        if self._types:
+            ret += ' types: %s' % ', '.join(self._types)
+        if self.timespecs:
+            ret += ' timespecs: %s' % ', '.join(self.timespecs)
+        ret += '>'
+
+        return ret
+
+    def matches(self, event, change):
+        # event types are ORed
+        matches_type = False
+        for etype in self.types:
+            if etype.match(event.type):
+                matches_type = True
+        if self.types and not matches_type:
+            return False
+
+        # timespecs are ORed
+        matches_timespec = False
+        for timespec in self.timespecs:
+            if (event.timespec == timespec):
+                matches_timespec = True
+        if self.timespecs and not matches_timespec:
+            return False
+
+        return True
+
+
+class TimerTriggerEvent(TriggerEvent):
+    def __init__(self):
+        super(TimerTriggerEvent, self).__init__()
+        self.timespec = None
diff --git a/zuul/driver/timer/timertrigger.py b/zuul/driver/timer/timertrigger.py
index b0f282c..81b41a1 100644
--- a/zuul/driver/timer/timertrigger.py
+++ b/zuul/driver/timer/timertrigger.py
@@ -15,26 +15,20 @@
 
 import voluptuous as v
 
-from zuul.model import EventFilter
 from zuul.trigger import BaseTrigger
+from zuul.driver.timer.timermodel import TimerEventFilter
+from zuul.driver.util import to_list
 
 
 class TimerTrigger(BaseTrigger):
     name = 'timer'
 
     def getEventFilters(self, trigger_conf):
-        def toList(item):
-            if not item:
-                return []
-            if isinstance(item, list):
-                return item
-            return [item]
-
         efilters = []
-        for trigger in toList(trigger_conf):
-            f = EventFilter(trigger=self,
-                            types=['timer'],
-                            timespecs=toList(trigger['time']))
+        for trigger in to_list(trigger_conf):
+            f = TimerEventFilter(trigger=self,
+                                 types=['timer'],
+                                 timespecs=to_list(trigger['time']))
 
             efilters.append(f)
 
diff --git a/zuul/driver/util.py b/zuul/driver/util.py
new file mode 100644
index 0000000..902ce76
--- /dev/null
+++ b/zuul/driver/util.py
@@ -0,0 +1,43 @@
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+# Utility methods to promote consistent configuration among drivers.
+
+import voluptuous as vs
+
+
+def time_to_seconds(s):
+    if s.endswith('s'):
+        return int(s[:-1])
+    if s.endswith('m'):
+        return int(s[:-1]) * 60
+    if s.endswith('h'):
+        return int(s[:-1]) * 60 * 60
+    if s.endswith('d'):
+        return int(s[:-1]) * 24 * 60 * 60
+    if s.endswith('w'):
+        return int(s[:-1]) * 7 * 24 * 60 * 60
+    raise Exception("Unable to parse time value: %s" % s)
+
+
+def scalar_or_list(x):
+    return vs.Any([x], x)
+
+
+def to_list(item):
+    if not item:
+        return []
+    if isinstance(item, list):
+        return item
+    return [item]
diff --git a/zuul/driver/zuul/__init__.py b/zuul/driver/zuul/__init__.py
index 8c9d795..08612dc 100644
--- a/zuul/driver/zuul/__init__.py
+++ b/zuul/driver/zuul/__init__.py
@@ -15,9 +15,9 @@
 import logging
 
 from zuul.driver import Driver, TriggerInterface
-from zuul.model import TriggerEvent
+from zuul.driver.zuul.zuulmodel import ZuulTriggerEvent
 
-import zuultrigger
+from zuul.driver.zuul import zuultrigger
 
 PARENT_CHANGE_ENQUEUED = 'parent-change-enqueued'
 PROJECT_CHANGE_MERGED = 'project-change-merged'
@@ -73,7 +73,7 @@
             self._createProjectChangeMergedEvent(open_change)
 
     def _createProjectChangeMergedEvent(self, change):
-        event = TriggerEvent()
+        event = ZuulTriggerEvent()
         event.type = PROJECT_CHANGE_MERGED
         event.trigger_name = self.name
         event.project_hostname = change.project.canonical_hostname
@@ -94,7 +94,7 @@
             self._createParentChangeEnqueuedEvent(needs, pipeline)
 
     def _createParentChangeEnqueuedEvent(self, change, pipeline):
-        event = TriggerEvent()
+        event = ZuulTriggerEvent()
         event.type = PARENT_CHANGE_ENQUEUED
         event.trigger_name = self.name
         event.pipeline_name = pipeline.name
diff --git a/zuul/driver/zuul/zuulmodel.py b/zuul/driver/zuul/zuulmodel.py
new file mode 100644
index 0000000..036f6d2
--- /dev/null
+++ b/zuul/driver/zuul/zuulmodel.py
@@ -0,0 +1,63 @@
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import re
+
+from zuul.model import EventFilter, TriggerEvent
+
+
+class ZuulEventFilter(EventFilter):
+    def __init__(self, trigger, types=[], pipelines=[]):
+        EventFilter.__init__(self, trigger)
+
+        self._types = types
+        self._pipelines = pipelines
+        self.types = [re.compile(x) for x in types]
+        self.pipelines = [re.compile(x) for x in pipelines]
+
+    def __repr__(self):
+        ret = '<ZuulEventFilter'
+
+        if self._types:
+            ret += ' types: %s' % ', '.join(self._types)
+        if self._pipelines:
+            ret += ' pipelines: %s' % ', '.join(self._pipelines)
+        ret += '>'
+
+        return ret
+
+    def matches(self, event, change):
+        # event types are ORed
+        matches_type = False
+        for etype in self.types:
+            if etype.match(event.type):
+                matches_type = True
+        if self.types and not matches_type:
+            return False
+
+        # pipelines are ORed
+        matches_pipeline = False
+        for epipe in self.pipelines:
+            if epipe.match(event.pipeline_name):
+                matches_pipeline = True
+        if self.pipelines and not matches_pipeline:
+            return False
+
+        return True
+
+
+class ZuulTriggerEvent(TriggerEvent):
+    def __init__(self):
+        super(ZuulTriggerEvent, self).__init__()
+        self.pipeline_name = None
diff --git a/zuul/driver/zuul/zuultrigger.py b/zuul/driver/zuul/zuultrigger.py
index c0c2fb3..628687e 100644
--- a/zuul/driver/zuul/zuultrigger.py
+++ b/zuul/driver/zuul/zuultrigger.py
@@ -15,8 +15,9 @@
 
 import logging
 import voluptuous as v
-from zuul.model import EventFilter
 from zuul.trigger import BaseTrigger
+from zuul.driver.zuul.zuulmodel import ZuulEventFilter
+from zuul.driver.util import scalar_or_list, to_list
 
 
 class ZuulTrigger(BaseTrigger):
@@ -29,25 +30,12 @@
         self._handle_project_change_merged_events = False
 
     def getEventFilters(self, trigger_conf):
-        def toList(item):
-            if not item:
-                return []
-            if isinstance(item, list):
-                return item
-            return [item]
-
         efilters = []
-        for trigger in toList(trigger_conf):
-            f = EventFilter(
+        for trigger in to_list(trigger_conf):
+            f = ZuulEventFilter(
                 trigger=self,
-                types=toList(trigger['event']),
-                pipelines=toList(trigger.get('pipeline')),
-                required_approvals=(
-                    toList(trigger.get('require-approval'))
-                ),
-                reject_approvals=toList(
-                    trigger.get('reject-approval')
-                ),
+                types=to_list(trigger['event']),
+                pipelines=to_list(trigger.get('pipeline')),
             )
             efilters.append(f)
 
@@ -55,9 +43,6 @@
 
 
 def getSchema():
-    def toList(x):
-        return v.Any([x], x)
-
     approval = v.Schema({'username': str,
                          'email-filter': str,
                          'email': str,
@@ -67,11 +52,11 @@
 
     zuul_trigger = {
         v.Required('event'):
-        toList(v.Any('parent-change-enqueued',
-                     'project-change-merged')),
-        'pipeline': toList(str),
-        'require-approval': toList(approval),
-        'reject-approval': toList(approval),
+        scalar_or_list(v.Any('parent-change-enqueued',
+                             'project-change-merged')),
+        'pipeline': scalar_or_list(str),
+        'require-approval': scalar_or_list(approval),
+        'reject-approval': scalar_or_list(approval),
     }
 
     return zuul_trigger
diff --git a/zuul/executor/ansiblelaunchserver.py b/zuul/executor/ansiblelaunchserver.py
index 0202bdd..18762b2 100644
--- a/zuul/executor/ansiblelaunchserver.py
+++ b/zuul/executor/ansiblelaunchserver.py
@@ -59,7 +59,7 @@
     return bool(x)
 
 
-class LaunchGearWorker(gear.Worker):
+class LaunchGearWorker(gear.TextWorker):
     def __init__(self, *args, **kw):
         self.__launch_server = kw.pop('launch_server')
         super(LaunchGearWorker, self).__init__(*args, **kw)
@@ -71,7 +71,7 @@
         return super(LaunchGearWorker, self).handleNoop(packet)
 
 
-class NodeGearWorker(gear.Worker):
+class NodeGearWorker(gear.TextWorker):
     MASS_DO = 101
 
     def sendMassDo(self, functions):
diff --git a/zuul/executor/client.py b/zuul/executor/client.py
index 9f234e9..0d40716 100644
--- a/zuul/executor/client.py
+++ b/zuul/executor/client.py
@@ -169,7 +169,8 @@
         self.log.debug("Function %s is not registered" % name)
         return False
 
-    def execute(self, job, item, pipeline, dependent_items=[]):
+    def execute(self, job, item, pipeline, dependent_items=[],
+                merger_items=[]):
         tenant = pipeline.layout.tenant
         uuid = str(uuid4().hex)
         self.log.info(
@@ -179,8 +180,11 @@
                 item.current_build_set.getJobNodeSet(job.name),
                 item.change,
                 [x.change for x in dependent_items]))
+
         dependent_items = dependent_items[:]
         dependent_items.reverse()
+        all_items = dependent_items + [item]
+
         # TODOv3(jeblair): This ansible vars data structure will
         # replace the environment variables below.
         project = dict(
@@ -210,7 +214,7 @@
             changes_str = '^'.join(
                 ['%s:%s:%s' % (i.change.project.name, i.change.branch,
                                i.change.refspec)
-                 for i in dependent_items + [item]])
+                 for i in all_items])
             params['ZUUL_BRANCH'] = item.change.branch
             params['ZUUL_CHANGES'] = changes_str
             params['ZUUL_REF'] = ('refs/zuul/%s/%s' %
@@ -220,7 +224,7 @@
 
             zuul_changes = ' '.join(['%s,%s' % (i.change.number,
                                                 i.change.patchset)
-                                     for i in dependent_items + [item]])
+                                     for i in all_items])
             params['ZUUL_CHANGE_IDS'] = zuul_changes
             params['ZUUL_CHANGE'] = str(item.change.number)
             params['ZUUL_PATCHSET'] = str(item.change.patchset)
@@ -253,13 +257,11 @@
         # ZUUL_OLDREV
         # ZUUL_NEWREV
 
-        all_items = dependent_items + [item]
-        merger_items = [i.makeMergerItem() for i in all_items]
-
         params['job'] = job.name
         params['timeout'] = job.timeout
         params['items'] = merger_items
         params['projects'] = []
+        params['repo_state'] = item.current_build_set.repo_state
 
         if job.name != 'noop':
             params['playbooks'] = [x.toDict() for x in job.run]
@@ -284,21 +286,28 @@
                 params['vars'][secret.name] = copy.deepcopy(secret.secret_data)
         params['vars']['zuul'] = zuul_params
         projects = set()
+
+        def make_project_dict(project):
+            project_config = item.current_build_set.layout.project_configs.get(
+                project.canonical_name, None)
+            if project_config:
+                project_default_branch = project_config.default_branch
+            else:
+                project_default_branch = 'master'
+            connection = project.source.connection
+            return dict(connection=connection.connection_name,
+                        name=project.name,
+                        default_branch=project_default_branch)
+
         if job.repos:
             for repo in job.repos:
                 (trusted, project) = tenant.getProject(repo)
-                connection = project.source.connection
-                params['projects'].append(
-                    dict(connection=connection.connection_name,
-                         name=project.name))
+                params['projects'].append(make_project_dict(project))
                 projects.add(project)
         for item in all_items:
             if item.change.project not in projects:
                 project = item.change.project
-                connection = item.change.project.source.connection
-                params['projects'].append(
-                    dict(connection=connection.connection_name,
-                         name=project.name))
+                params['projects'].append(make_project_dict(project))
                 projects.add(project)
 
         build = Build(job, uuid)
@@ -308,8 +317,8 @@
             self.sched.onBuildCompleted(build, 'SUCCESS')
             return build
 
-        gearman_job = gear.Job('executor:execute', json.dumps(params),
-                               unique=uuid)
+        gearman_job = gear.TextJob('executor:execute', json.dumps(params),
+                                   unique=uuid)
         build.__gearman_job = gearman_job
         build.__gearman_manager = None
         self.builds[uuid] = build
@@ -438,7 +447,7 @@
         job.connection.sendAdminRequest(req, timeout=300)
         self.log.debug("Response to cancel build %s request: %s" %
                        (build, req.response.strip()))
-        if req.response.startswith("OK"):
+        if req.response.startswith(b"OK"):
             try:
                 del self.builds[job.unique]
             except:
@@ -452,8 +461,8 @@
                            (build,))
         stop_uuid = str(uuid4().hex)
         data = dict(uuid=build.__gearman_job.unique)
-        stop_job = gear.Job("executor:stop:%s" % build.__gearman_manager,
-                            json.dumps(data), unique=stop_uuid)
+        stop_job = gear.TextJob("executor:stop:%s" % build.__gearman_manager,
+                                json.dumps(data), unique=stop_uuid)
         self.meta_jobs[stop_uuid] = stop_job
         self.log.debug("Submitting stop job: %s", stop_job)
         self.gearman.submitJob(stop_job, precedence=gear.PRECEDENCE_HIGH,
diff --git a/zuul/executor/server.py b/zuul/executor/server.py
index 4801de2..bb3ea9e 100644
--- a/zuul/executor/server.py
+++ b/zuul/executor/server.py
@@ -80,7 +80,15 @@
 
 
 class JobDir(object):
-    def __init__(self, root=None, keep=False):
+    def __init__(self, root, keep, build_uuid):
+        '''
+        :param str root: Root directory for the individual job directories.
+            Can be None to use the default system temp root directory.
+        :param bool keep: If True, do not delete the job directory.
+        :param str build_uuid: The unique build UUID. If supplied, this will
+            be used as the temp job directory name. Using this will help the
+            log streaming daemon find job logs.
+        '''
         # root
         #   ansible
         #     trusted.cfg
@@ -89,7 +97,12 @@
         #     src
         #     logs
         self.keep = keep
-        self.root = tempfile.mkdtemp(dir=root)
+        if root:
+            tmpdir = root
+        else:
+            tmpdir = tempfile.gettempdir()
+        self.root = os.path.join(tmpdir, build_uuid)
+        os.mkdir(self.root, 0o700)
         # Work
         self.work_root = os.path.join(self.root, 'work')
         os.makedirs(self.work_root)
@@ -219,6 +232,16 @@
             self.condition.release()
 
 
+def _copy_ansible_files(python_module, target_dir):
+        library_path = os.path.dirname(os.path.abspath(python_module.__file__))
+        for fn in os.listdir(library_path):
+            full_path = os.path.join(library_path, fn)
+            if os.path.isdir(full_path):
+                shutil.copytree(full_path, os.path.join(target_dir, fn))
+            else:
+                shutil.copy(os.path.join(library_path, fn), target_dir)
+
+
 class ExecutorServer(object):
     log = logging.getLogger("zuul.ExecutorServer")
 
@@ -286,25 +309,10 @@
         if not os.path.exists(self.lookup_dir):
             os.makedirs(self.lookup_dir)
 
-        library_path = os.path.dirname(os.path.abspath(
-            zuul.ansible.library.__file__))
-        for fn in os.listdir(library_path):
-            shutil.copy(os.path.join(library_path, fn), self.library_dir)
-
-        action_path = os.path.dirname(os.path.abspath(
-            zuul.ansible.action.__file__))
-        for fn in os.listdir(action_path):
-            shutil.copy(os.path.join(action_path, fn), self.action_dir)
-
-        callback_path = os.path.dirname(os.path.abspath(
-            zuul.ansible.callback.__file__))
-        for fn in os.listdir(callback_path):
-            shutil.copy(os.path.join(callback_path, fn), self.callback_dir)
-
-        lookup_path = os.path.dirname(os.path.abspath(
-            zuul.ansible.lookup.__file__))
-        for fn in os.listdir(lookup_path):
-            shutil.copy(os.path.join(lookup_path, fn), self.lookup_dir)
+        _copy_ansible_files(zuul.ansible.library, self.library_dir)
+        _copy_ansible_files(zuul.ansible.action, self.action_dir)
+        _copy_ansible_files(zuul.ansible.callback, self.callback_dir)
+        _copy_ansible_files(zuul.ansible.lookup, self.lookup_dir)
 
         self.job_workers = {}
 
@@ -320,7 +328,7 @@
             port = self.config.get('gearman', 'port')
         else:
             port = 4730
-        self.worker = gear.Worker('Zuul Executor Server')
+        self.worker = gear.TextWorker('Zuul Executor Server')
         self.worker.addServer(server, port)
         self.log.debug("Waiting for server")
         self.worker.waitForServer()
@@ -354,7 +362,7 @@
         self.command_socket.stop()
         self.update_queue.put(None)
 
-        for job_worker in self.job_workers.values():
+        for job_worker in list(self.job_workers.values()):
             try:
                 job_worker.stop()
             except Exception:
@@ -390,7 +398,7 @@
     def runCommand(self):
         while self._command_running:
             try:
-                command = self.command_socket.get()
+                command = self.command_socket.get().decode('utf8')
                 if command != '_stop':
                     self.command_map[command]()
             except Exception:
@@ -445,7 +453,8 @@
                         job.sendWorkFail()
                 except Exception:
                     self.log.exception("Exception while running job")
-                    job.sendWorkException(traceback.format_exc())
+                    job.sendWorkException(
+                        traceback.format_exc().encode('utf8'))
             except gear.InterruptedError:
                 pass
             except Exception:
@@ -488,16 +497,14 @@
 
     def merge(self, job):
         args = json.loads(job.arguments)
-        ret = self.merger.mergeChanges(args['items'], args.get('files'))
+        ret = self.merger.mergeChanges(args['items'], args.get('files'),
+                                       args.get('repo_state'))
         result = dict(merged=(ret is not None),
                       zuul_url=self.zuul_url)
-        if args.get('files'):
-            if ret:
-                result['commit'], result['files'] = ret
-            else:
-                result['commit'], result['files'] = (None, None)
+        if ret is None:
+            result['commit'] = result['files'] = result['repo_state'] = None
         else:
-            result['commit'] = ret
+            result['commit'], result['files'], result['repo_state'] = ret
         job.sendWorkComplete(json.dumps(result))
 
 
@@ -537,8 +544,9 @@
 
     def execute(self):
         try:
-            self.jobdir = JobDir(root=self.executor_server.jobdir_root,
-                                 keep=self.executor_server.keep_jobdir)
+            self.jobdir = JobDir(self.executor_server.jobdir_root,
+                                 self.executor_server.keep_jobdir,
+                                 str(self.job.unique))
             self._execute()
         except Exception:
             self.log.exception("Exception while executing job")
@@ -592,13 +600,10 @@
 
         merge_items = [i for i in args['items'] if i.get('refspec')]
         if merge_items:
-            commit = self.doMergeChanges(merge_items)
-            if not commit:
+            if not self.doMergeChanges(merge_items, args['repo_state']):
                 # There was a merge conflict and we have already sent
                 # a work complete result, don't run any jobs
                 return
-        else:
-            commit = args['items'][-1]['newrev']  # noqa
 
         # Delete the origin remote from each repo we set up since
         # it will not be valid within the jobs.
@@ -641,14 +646,15 @@
         result = dict(result=result)
         self.job.sendWorkComplete(json.dumps(result))
 
-    def doMergeChanges(self, items):
+    def doMergeChanges(self, items, repo_state):
         # Get a merger in order to update the repos involved in this job.
         merger = self.executor_server._getMerger(self.jobdir.src_root)
-        commit = merger.mergeChanges(items)  # noqa
-        if not commit:  # merge conflict
+        ret = merger.mergeChanges(items, repo_state=repo_state)
+        if not ret:  # merge conflict
             result = dict(result='MERGER_FAILURE')
             self.job.sendWorkComplete(json.dumps(result))
-        return commit
+            return False
+        return True
 
     def runPlaybooks(self, args):
         result = None
@@ -942,7 +948,7 @@
             for item in self.getHostList(args):
                 inventory.write(item['name'])
                 for k, v in item['host_vars'].items():
-                    inventory.write(' %s=%s' % (k, v))
+                    inventory.write(' %s="%s"' % (k, v))
                 inventory.write('\n')
                 for key in item['host_keys']:
                     keys.append(key)
diff --git a/zuul/lib/cloner.py b/zuul/lib/cloner.py
index bec8ebe..3070be6 100644
--- a/zuul/lib/cloner.py
+++ b/zuul/lib/cloner.py
@@ -102,7 +102,8 @@
             new_repo = git.Repo.clone_from(git_cache, dest)
             self.log.info("Updating origin remote in repo %s to %s",
                           project, git_upstream)
-            new_repo.remotes.origin.config_writer.set('url', git_upstream)
+            new_repo.remotes.origin.config_writer.set('url',
+                                                      git_upstream).release()
         else:
             self.log.info("Creating repo %s from upstream %s",
                           project, git_upstream)
diff --git a/zuul/lib/commandsocket.py b/zuul/lib/commandsocket.py
index 1b7fed9..ae62204 100644
--- a/zuul/lib/commandsocket.py
+++ b/zuul/lib/commandsocket.py
@@ -18,7 +18,7 @@
 import os
 import socket
 import threading
-import Queue
+from six.moves import queue
 
 
 class CommandSocket(object):
@@ -27,7 +27,7 @@
     def __init__(self, path):
         self.running = False
         self.path = path
-        self.queue = Queue.Queue()
+        self.queue = queue.Queue()
 
     def start(self):
         self.running = True
@@ -46,14 +46,14 @@
         self.running = False
         s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
         s.connect(self.path)
-        s.sendall('_stop\n')
+        s.sendall(b'_stop\n')
         # The command '_stop' will be ignored by our listener, so
         # directly inject it into the queue so that consumers of this
         # class which are waiting in .get() are awakened.  They can
         # either handle '_stop' or just ignore the unknown command and
         # then check to see if they should continue to run before
         # re-entering their loop.
-        self.queue.put('_stop')
+        self.queue.put(b'_stop')
         self.socket_thread.join()
 
     def _socketListener(self):
@@ -61,10 +61,10 @@
             try:
                 s, addr = self.socket.accept()
                 self.log.debug("Accepted socket connection %s" % (s,))
-                buf = ''
+                buf = b''
                 while True:
                     buf += s.recv(1)
-                    if buf[-1] == '\n':
+                    if buf[-1:] == b'\n':
                         break
                 buf = buf.strip()
                 self.log.debug("Received %s from socket" % (buf,))
@@ -72,7 +72,7 @@
                 # Because we use '_stop' internally to wake up a
                 # waiting thread, don't allow it to actually be
                 # injected externally.
-                if buf != '_stop':
+                if buf != b'_stop':
                     self.queue.put(buf)
             except Exception:
                 self.log.exception("Exception in socket handler")
diff --git a/zuul/lib/connections.py b/zuul/lib/connections.py
index f5cce7b..9908fff 100644
--- a/zuul/lib/connections.py
+++ b/zuul/lib/connections.py
@@ -23,6 +23,7 @@
 import zuul.driver.timer
 import zuul.driver.sql
 from zuul.connection import BaseConnection
+from zuul.driver import SourceInterface
 
 
 class DefaultConnection(BaseConnection):
@@ -78,7 +79,7 @@
         for driver in self.drivers.values():
             driver.stop()
 
-    def configure(self, config):
+    def configure(self, config, source_only=False):
         # Register connections from the config
         connections = {}
 
@@ -100,6 +101,13 @@
                                 % (con_config['driver'], con_name))
 
             driver = self.drivers[con_driver]
+
+            # The merger and the reporter only needs source driver.
+            # This makes sure Reporter like the SQLDriver are only created by
+            # the scheduler process
+            if source_only and not isinstance(driver, SourceInterface):
+                continue
+
             connection = driver.getConnection(con_name, con_config)
             connections[con_name] = connection
 
@@ -130,10 +138,11 @@
 
         # Create default connections for drivers which need no
         # connection information (e.g., 'timer' or 'zuul').
-        for driver in self.drivers.values():
-            if not hasattr(driver, 'getConnection'):
-                connections[driver.name] = DefaultConnection(
-                    driver, driver.name, {})
+        if not source_only:
+            for driver in self.drivers.values():
+                if not hasattr(driver, 'getConnection'):
+                    connections[driver.name] = DefaultConnection(
+                        driver, driver.name, {})
 
         self.connections = connections
 
diff --git a/zuul/lib/log_streamer.py b/zuul/lib/log_streamer.py
new file mode 100644
index 0000000..6aa51a6
--- /dev/null
+++ b/zuul/lib/log_streamer.py
@@ -0,0 +1,205 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2016 IBM Corp.
+# Copyright 2017 Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import os
+import os.path
+import pwd
+import re
+import select
+import socket
+import threading
+import time
+
+try:
+    import SocketServer as ss  # python 2.x
+except ImportError:
+    import socketserver as ss  # python 3
+
+
+class Log(object):
+
+    def __init__(self, path):
+        self.path = path
+        self.file = open(path)
+        self.stat = os.stat(path)
+        self.size = self.stat.st_size
+
+
+class RequestHandler(ss.BaseRequestHandler):
+    '''
+    Class to handle a single log streaming request.
+
+    The log streaming code was blatantly stolen from zuul_console.py. Only
+    the (class/method/attribute) names were changed to protect the innocent.
+    '''
+
+    def handle(self):
+        build_uuid = self.request.recv(1024).decode("utf-8")
+        build_uuid = build_uuid.rstrip()
+
+        # validate build ID
+        if not re.match("[0-9A-Fa-f]+$", build_uuid):
+            msg = 'Build ID %s is not valid' % build_uuid
+            self.request.sendall(msg.encode("utf-8"))
+            return
+
+        job_dir = os.path.join(self.server.jobdir_root, build_uuid)
+        if not os.path.exists(job_dir):
+            msg = 'Build ID %s not found' % build_uuid
+            self.request.sendall(msg.encode("utf-8"))
+            return
+
+        # check if log file exists
+        log_file = os.path.join(job_dir, 'ansible', 'ansible_log.txt')
+        if not os.path.exists(log_file):
+            msg = 'Log not found for build ID %s' % build_uuid
+            self.request.sendall(msg.encode("utf-8"))
+            return
+
+        self.stream_log(log_file)
+
+    def stream_log(self, log_file):
+        log = None
+        while True:
+            if log is not None:
+                try:
+                    log.file.close()
+                except:
+                    pass
+            while True:
+                log = self.chunk_log(log_file)
+                if log:
+                    break
+                time.sleep(0.5)
+            while True:
+                if self.follow_log(log):
+                    break
+                else:
+                    return
+
+    def chunk_log(self, log_file):
+        try:
+            log = Log(log_file)
+        except Exception:
+            return
+        while True:
+            chunk = log.file.read(4096)
+            if not chunk:
+                break
+            self.request.send(chunk.encode('utf-8'))
+        return log
+
+    def follow_log(self, log):
+        while True:
+            # As long as we have unread data, keep reading/sending
+            while True:
+                chunk = log.file.read(4096)
+                if chunk:
+                    self.request.send(chunk.encode('utf-8'))
+                else:
+                    break
+
+            # At this point, we are waiting for more data to be written
+            time.sleep(0.5)
+
+            # Check to see if the remote end has sent any data, if so,
+            # discard
+            r, w, e = select.select([self.request], [], [self.request], 0)
+            if self.request in e:
+                return False
+            if self.request in r:
+                ret = self.request.recv(1024)
+                # Discard anything read, if input is eof, it has
+                # disconnected.
+                if not ret:
+                    return False
+
+            # See if the file has been truncated
+            try:
+                st = os.stat(log.path)
+                if (st.st_ino != log.stat.st_ino or
+                    st.st_size < log.size):
+                    return True
+            except Exception:
+                return True
+            log.size = st.st_size
+
+
+class CustomForkingTCPServer(ss.ForkingTCPServer):
+    '''
+    Custom version that allows us to drop privileges after port binding.
+    '''
+    def __init__(self, *args, **kwargs):
+        self.user = kwargs.pop('user')
+        self.jobdir_root = kwargs.pop('jobdir_root')
+        # For some reason, setting custom attributes does not work if we
+        # call the base class __init__ first. Wha??
+        ss.ForkingTCPServer.__init__(self, *args, **kwargs)
+
+    def change_privs(self):
+        '''
+        Drop our privileges to the zuul user.
+        '''
+        if os.getuid() != 0:
+            return
+        pw = pwd.getpwnam(self.user)
+        os.setgroups([])
+        os.setgid(pw.pw_gid)
+        os.setuid(pw.pw_uid)
+        os.umask(0o022)
+
+    def server_bind(self):
+        self.allow_reuse_address = True
+        ss.ForkingTCPServer.server_bind(self)
+        if self.user:
+            self.change_privs()
+
+    def server_close(self):
+        '''
+        Overridden from base class to shutdown the socket immediately.
+        '''
+        try:
+            self.socket.shutdown(socket.SHUT_RD)
+            self.socket.close()
+        except socket.error as e:
+            # If it's already closed, don't error.
+            if e.errno == socket.EBADF:
+                return
+            raise
+
+
+class LogStreamer(object):
+    '''
+    Class implementing log streaming over the finger daemon port.
+    '''
+
+    def __init__(self, user, host, port, jobdir_root):
+        self.server = CustomForkingTCPServer((host, port),
+                                             RequestHandler,
+                                             user=user,
+                                             jobdir_root=jobdir_root)
+
+        # We start the actual serving within a thread so we can return to
+        # the owner.
+        self.thd = threading.Thread(target=self.server.serve_forever)
+        self.thd.daemon = True
+        self.thd.start()
+
+    def stop(self):
+        if self.thd.isAlive():
+            self.server.shutdown()
+            self.server.server_close()
diff --git a/zuul/manager/__init__.py b/zuul/manager/__init__.py
index bdfde48..7649944 100644
--- a/zuul/manager/__init__.py
+++ b/zuul/manager/__init__.py
@@ -146,20 +146,17 @@
 
     def reportStart(self, item):
         if not self.pipeline._disabled:
-            source = item.change.project.source
             try:
                 self.log.info("Reporting start, action %s item %s" %
                               (self.pipeline.start_actions, item))
-                ret = self.sendReport(self.pipeline.start_actions,
-                                      source, item)
+                ret = self.sendReport(self.pipeline.start_actions, item)
                 if ret:
                     self.log.error("Reporting item start %s received: %s" %
                                    (item, ret))
             except:
                 self.log.exception("Exception while reporting start:")
 
-    def sendReport(self, action_reporters, source, item,
-                   message=None):
+    def sendReport(self, action_reporters, item, message=None):
         """Sends the built message off to configured reporters.
 
         Takes the action_reporters, item, message and extra options and
@@ -168,7 +165,7 @@
         report_errors = []
         if len(action_reporters) > 0:
             for reporter in action_reporters:
-                ret = reporter.report(source, self.pipeline, item)
+                ret = reporter.report(self.pipeline, item)
                 if ret:
                     report_errors.append(ret)
             if len(report_errors) == 0:
@@ -192,17 +189,6 @@
     def getFailingDependentItems(self, item):
         return None
 
-    def getDependentItems(self, item):
-        orig_item = item
-        items = []
-        while item.item_ahead:
-            items.append(item.item_ahead)
-            item = item.item_ahead
-        self.log.info("Change %s depends on changes %s" %
-                      (orig_item.change,
-                       [x.change for x in items]))
-        return items
-
     def getItemForChange(self, change):
         for item in self.pipeline.getAllItems():
             if item.change.equals(change):
@@ -364,7 +350,7 @@
 
     def _executeJobs(self, item, jobs):
         self.log.debug("Executing jobs for change %s" % item.change)
-        dependent_items = self.getDependentItems(item)
+        build_set = item.current_build_set
         for job in jobs:
             self.log.debug("Found job %s for change %s" % (job, item.change))
             try:
@@ -372,7 +358,8 @@
                 self.sched.nodepool.useNodeSet(nodeset)
                 build = self.sched.executor.execute(job, item,
                                                     self.pipeline,
-                                                    dependent_items)
+                                                    build_set.dependent_items,
+                                                    build_set.merger_items)
                 self.log.debug("Adding build %s of job %s to item %s" %
                                (build, job, item))
                 item.addBuild(build)
@@ -426,7 +413,7 @@
             build.result = 'CANCELED'
             canceled = True
             canceled_jobs.add(build.job.name)
-        for jobname, nodeset in old_build_set.nodesets.items()[:]:
+        for jobname, nodeset in list(old_build_set.nodesets.items()):
             if jobname in canceled_jobs:
                 continue
             self.sched.nodepool.returnNodeSet(nodeset)
@@ -502,16 +489,11 @@
 
         self.log.debug("Scheduling merge for item %s (files: %s)" %
                        (item, files))
-        dependent_items = self.getDependentItems(item)
-        dependent_items.reverse()
-        all_items = dependent_items + [item]
-        merger_items = [i.makeMergerItem() for i in all_items]
         build_set = item.current_build_set
         build_set.merge_state = build_set.PENDING
-        self.sched.merger.mergeChanges(merger_items,
-                                       item.current_build_set,
-                                       files,
-                                       self.pipeline.precedence)
+        self.sched.merger.mergeChanges(build_set.merger_items,
+                                       item.current_build_set, files,
+                                       precedence=self.pipeline.precedence)
         return False
 
     def prepareItem(self, item):
@@ -522,6 +504,10 @@
             build_set.setConfiguration()
         if build_set.merge_state == build_set.NEW:
             return self.scheduleMerge(item, ['zuul.yaml', '.zuul.yaml'])
+        if build_set.merge_state == build_set.PENDING:
+            return False
+        if build_set.unable_to_merge:
+            return False
         if build_set.config_error:
             return False
         return True
@@ -680,6 +666,7 @@
         if event.merged:
             build_set.commit = event.commit
             build_set.files.setFiles(event.files)
+            build_set.repo_state = event.repo_state
         elif event.updated:
             build_set.commit = item.change.newrev
         if not build_set.commit:
@@ -733,7 +720,6 @@
 
     def _reportItem(self, item):
         self.log.debug("Reporting change %s" % item.change)
-        source = item.change.project.source
         ret = True  # Means error as returned by trigger.report
         if item.getConfigError():
             self.log.debug("Invalid config for change %s" % item.change)
@@ -768,7 +754,7 @@
             try:
                 self.log.info("Reporting item %s, actions: %s" %
                               (item, actions))
-                ret = self.sendReport(actions, source, item)
+                ret = self.sendReport(actions, item)
                 if ret:
                     self.log.error("Reporting item %s received: %s" %
                                    (item, ret))
diff --git a/zuul/merger/client.py b/zuul/merger/client.py
index 642bc1b..c98f20e 100644
--- a/zuul/merger/client.py
+++ b/zuul/merger/client.py
@@ -56,7 +56,7 @@
         self.__merge_client.onBuildCompleted(job)
 
 
-class MergeJob(gear.Job):
+class MergeJob(gear.TextJob):
     def __init__(self, *args, **kw):
         super(MergeJob, self).__init__(*args, **kw)
         self.__event = threading.Event()
@@ -107,18 +107,13 @@
                                timeout=300)
         return job
 
-    def mergeChanges(self, items, build_set, files=None,
+    def mergeChanges(self, items, build_set, files=None, repo_state=None,
                      precedence=zuul.model.PRECEDENCE_NORMAL):
         data = dict(items=items,
-                    files=files)
+                    files=files,
+                    repo_state=repo_state)
         self.submitJob('merger:merge', data, build_set, precedence)
 
-    def updateRepo(self, connection_name, project_name, build_set,
-                   precedence=zuul.model.PRECEDENCE_NORMAL):
-        data = dict(connection=connection_name,
-                    project=project_name)
-        self.submitJob('merger:update', data, build_set, precedence)
-
     def getFiles(self, connection_name, project_name, branch, files,
                  precedence=zuul.model.PRECEDENCE_HIGH):
         data = dict(connection=connection_name,
@@ -135,6 +130,7 @@
         updated = data.get('updated', False)
         commit = data.get('commit')
         files = data.get('files', {})
+        repo_state = data.get('repo_state', {})
         job.files = files
         self.log.info("Merge %s complete, merged: %s, updated: %s, "
                       "commit: %s" %
@@ -142,7 +138,8 @@
         job.setComplete()
         if job.build_set:
             self.sched.onMergeCompleted(job.build_set, zuul_url,
-                                        merged, updated, commit, files)
+                                        merged, updated, commit, files,
+                                        repo_state)
         # The test suite expects the job to be removed from the
         # internal account after the wake flag is set.
         self.jobs.remove(job)
diff --git a/zuul/merger/merger.py b/zuul/merger/merger.py
index 75c51af..ee83fa0 100644
--- a/zuul/merger/merger.py
+++ b/zuul/merger/merger.py
@@ -14,6 +14,7 @@
 # under the License.
 
 import git
+import gitdb
 import os
 import logging
 
@@ -64,13 +65,12 @@
                                                       self.local_path))
             git.Repo.clone_from(self.remote_url, self.local_path)
         repo = git.Repo(self.local_path)
-        if self.email:
-            repo.config_writer().set_value('user', 'email',
-                                           self.email)
-        if self.username:
-            repo.config_writer().set_value('user', 'name',
-                                           self.username)
-        repo.config_writer().write()
+        with repo.config_writer() as config_writer:
+            if self.email:
+                config_writer.set_value('user', 'email', self.email)
+            if self.username:
+                config_writer.set_value('user', 'name', self.username)
+            config_writer.write()
         self._initialized = True
 
     def isInitialized(self):
@@ -125,6 +125,26 @@
         ref = repo.refs[refname]
         return ref.commit
 
+    def getRefs(self):
+        repo = self.createRepoObject()
+        return repo.refs
+
+    def setRefs(self, refs):
+        repo = self.createRepoObject()
+        current_refs = {}
+        for ref in repo.refs:
+            current_refs[ref.path] = ref
+        unseen = set(current_refs.keys())
+        for path, hexsha in refs.items():
+            binsha = gitdb.util.to_bin_sha(hexsha)
+            obj = git.objects.Object.new_from_sha(repo, binsha)
+            self.log.debug("Create reference %s", path)
+            git.refs.Reference.create(repo, path, obj, force=True)
+            unseen.discard(path)
+        for path in unseen:
+            self.log.debug("Delete reference %s", path)
+            git.refs.SymbolicReference.delete(repo, ref.path)
+
     def checkout(self, ref):
         repo = self.createRepoObject()
         self.log.debug("Checking out %s" % ref)
@@ -200,7 +220,7 @@
             tree = repo.commit(commit).tree
         for fn in files:
             if fn in tree:
-                ret[fn] = tree[fn].data_stream.read()
+                ret[fn] = tree[fn].data_stream.read().decode('utf8')
             else:
                 ret[fn] = None
         return ret
@@ -286,6 +306,31 @@
             raise Exception("Project %s/%s does not have branch %s" %
                             (connection_name, project_name, branch))
 
+    def _saveRepoState(self, connection_name, project_name, repo,
+                       repo_state):
+        projects = repo_state.setdefault(connection_name, {})
+        project = projects.setdefault(project_name, {})
+        if project:
+            # We already have a state for this project.
+            return
+        for ref in repo.getRefs():
+            if ref.path.startswith('refs/zuul'):
+                continue
+            if ref.path.startswith('refs/remotes'):
+                continue
+            project[ref.path] = ref.object.hexsha
+
+    def _restoreRepoState(self, connection_name, project_name, repo,
+                          repo_state):
+        projects = repo_state.get(connection_name, {})
+        project = projects.get(project_name, {})
+        if not project:
+            # We don't have a state for this project.
+            return
+        self.log.debug("Restore repo state for project %s/%s",
+                       connection_name, project_name)
+        repo.setRefs(project)
+
     def _mergeChange(self, item, ref):
         repo = self.getRepo(item['connection'], item['project'])
         try:
@@ -315,27 +360,13 @@
 
         return commit
 
-    def _mergeItem(self, item, recent):
+    def _mergeItem(self, item, recent, repo_state):
         self.log.debug("Processing refspec %s for project %s/%s / %s ref %s" %
                        (item['refspec'], item['connection'],
                         item['project'], item['branch'], item['ref']))
         repo = self.getRepo(item['connection'], item['project'])
         key = (item['connection'], item['project'], item['branch'])
 
-        # See if we have a commit for this change already in this repo
-        zuul_ref = item['branch'] + '/' + item['ref']
-        with repo.createRepoObject().git.custom_environment(
-            GIT_SSH_COMMAND=self._get_ssh_cmd(item['connection'])):
-            commit = repo.getCommitFromRef(zuul_ref)
-            if commit:
-                self.log.debug(
-                    "Found commit %s for ref %s" % (commit, zuul_ref))
-                # Store this as the most recent commit for this
-                # project-branch
-                recent[key] = commit
-                return commit
-
-        self.log.debug("Unable to find commit for ref %s" % (zuul_ref,))
         # We need to merge the change
         # Get the most recent commit for this project-branch
         base = recent.get(key)
@@ -348,7 +379,14 @@
             except Exception:
                 self.log.exception("Unable to reset repo %s" % repo)
                 return None
+            self._restoreRepoState(item['connection'], item['project'], repo,
+                                   repo_state)
+
             base = repo.getBranchHead(item['branch'])
+            # Save the repo state so that later mergers can repeat
+            # this process.
+            self._saveRepoState(item['connection'], item['project'], repo,
+                                repo_state)
         else:
             self.log.debug("Found base commit %s for %s" % (base, key,))
         # Merge the change
@@ -363,20 +401,26 @@
             # commits of each project-branch
             for key, mrc in recent.items():
                 connection, project, branch = key
+                zuul_ref = None
                 try:
                     repo = self.getRepo(connection, project)
                     zuul_ref = branch + '/' + item['ref']
-                    repo.createZuulRef(zuul_ref, mrc)
+                    if not repo.getCommitFromRef(zuul_ref):
+                        repo.createZuulRef(zuul_ref, mrc)
                 except Exception:
                     self.log.exception("Unable to set zuul ref %s for "
                                        "item %s" % (zuul_ref, item))
                     return None
             return commit
 
-    def mergeChanges(self, items, files=None):
+    def mergeChanges(self, items, files=None, repo_state=None):
+        # connection+project+branch -> commit
         recent = {}
         commit = None
         read_files = []
+        # connection -> project -> ref -> commit
+        if repo_state is None:
+            repo_state = {}
         for item in items:
             if item.get("number") and item.get("patchset"):
                 self.log.debug("Merging for change %s,%s." %
@@ -384,7 +428,7 @@
             elif item.get("newrev") and item.get("oldrev"):
                 self.log.debug("Merging for rev %s with oldrev %s." %
                                (item["newrev"], item["oldrev"]))
-            commit = self._mergeItem(item, recent)
+            commit = self._mergeItem(item, recent, repo_state)
             if not commit:
                 return None
             if files:
@@ -395,9 +439,7 @@
                     project=item['project'],
                     branch=item['branch'],
                     files=repo_files))
-        if files:
-            return commit.hexsha, read_files
-        return commit.hexsha
+        return commit.hexsha, read_files, repo_state
 
     def getFiles(self, connection_name, project_name, branch, files):
         repo = self.getRepo(connection_name, project_name)
diff --git a/zuul/merger/server.py b/zuul/merger/server.py
index 39551c9..15f1a41 100644
--- a/zuul/merger/server.py
+++ b/zuul/merger/server.py
@@ -54,7 +54,7 @@
             port = self.config.get('gearman', 'port')
         else:
             port = 4730
-        self.worker = gear.Worker('Zuul Merger')
+        self.worker = gear.TextWorker('Zuul Merger')
         self.worker.addServer(server, port)
         self.log.debug("Waiting for server")
         self.worker.waitForServer()
@@ -67,7 +67,6 @@
 
     def register(self):
         self.worker.registerFunction("merger:merge")
-        self.worker.registerFunction("merger:update")
         self.worker.registerFunction("merger:cat")
 
     def stop(self):
@@ -88,9 +87,6 @@
                     if job.name == 'merger:merge':
                         self.log.debug("Got merge job: %s" % job.unique)
                         self.merge(job)
-                    elif job.name == 'merger:update':
-                        self.log.debug("Got update job: %s" % job.unique)
-                        self.update(job)
                     elif job.name == 'merger:cat':
                         self.log.debug("Got cat job: %s" % job.unique)
                         self.cat(job)
@@ -107,23 +103,14 @@
 
     def merge(self, job):
         args = json.loads(job.arguments)
-        ret = self.merger.mergeChanges(args['items'], args.get('files'))
+        ret = self.merger.mergeChanges(args['items'], args.get('files'),
+                                       args.get('repo_state'))
         result = dict(merged=(ret is not None),
                       zuul_url=self.zuul_url)
-        if args.get('files'):
-            if ret:
-                result['commit'], result['files'] = ret
-            else:
-                result['commit'], result['files'] = (None, None)
+        if ret is None:
+            result['commit'] = result['files'] = result['repo_state'] = None
         else:
-            result['commit'] = ret
-        job.sendWorkComplete(json.dumps(result))
-
-    def update(self, job):
-        args = json.loads(job.arguments)
-        self.merger.updateRepo(args['connection'], args['project'])
-        result = dict(updated=True,
-                      zuul_url=self.zuul_url)
+            result['commit'], result['files'], result['repo_state'] = ret
         job.sendWorkComplete(json.dumps(result))
 
     def cat(self, job):
diff --git a/zuul/model.py b/zuul/model.py
index f7aa8f9..30bcb9b 100644
--- a/zuul/model.py
+++ b/zuul/model.py
@@ -16,7 +16,6 @@
 import copy
 import logging
 import os
-import re
 import struct
 import time
 from uuid import uuid4
@@ -28,8 +27,6 @@
                                   'ordereddict.OrderedDict'])
 
 
-EMPTY_GIT_REF = '0' * 40  # git sha of all zeros, used during creates/deletes
-
 MERGER_MERGE = 1          # "git merge"
 MERGER_MERGE_RESOLVE = 2  # "git merge -s resolve"
 MERGER_CHERRY_PICK = 3    # "git cherry-pick"
@@ -78,25 +75,6 @@
                    STATE_DELETING])
 
 
-def time_to_seconds(s):
-    if s.endswith('s'):
-        return int(s[:-1])
-    if s.endswith('m'):
-        return int(s[:-1]) * 60
-    if s.endswith('h'):
-        return int(s[:-1]) * 60 * 60
-    if s.endswith('d'):
-        return int(s[:-1]) * 24 * 60 * 60
-    if s.endswith('w'):
-        return int(s[:-1]) * 7 * 24 * 60 * 60
-    raise Exception("Unable to parse time value: %s" % s)
-
-
-def normalizeCategory(name):
-    name = name.lower()
-    return re.sub(' ', '-', name)
-
-
 class Attributes(object):
     """A class to hold attributes for string formatting."""
 
@@ -467,7 +445,7 @@
         self.nodes[node.name] = node
 
     def getNodes(self):
-        return self.nodes.values()
+        return list(self.nodes.values())
 
     def __repr__(self):
         if self.name:
@@ -490,9 +468,10 @@
         self.stat = None
         self.uid = uuid4().hex
         self.id = None
-        # Zuul internal failure flag (not stored in ZK so it's not
+        # Zuul internal flags (not stored in ZK so they are not
         # overwritten).
         self.failed = False
+        self.canceled = False
 
     @property
     def fulfilled(self):
@@ -681,6 +660,8 @@
     def __repr__(self):
         return '<ZuulRole %s %s>' % (self.project_name, self.target_name)
 
+    __hash__ = object.__hash__
+
     def __eq__(self, other):
         if not isinstance(other, ZuulRole):
             return False
@@ -808,6 +789,8 @@
                 return False
         return True
 
+    __hash__ = object.__hash__
+
     def __str__(self):
         return self.name
 
@@ -985,7 +968,7 @@
             raise
 
     def getJobs(self):
-        return self.jobs.values()  # Report in the order of the layout config
+        return list(self.jobs.values())  # Report in the order of layout cfg
 
     def _getDirectDependentJobs(self, parent_job):
         ret = set()
@@ -1148,7 +1131,6 @@
 
     def __init__(self, item):
         self.item = item
-        self.other_changes = []
         self.builds = {}
         self.result = None
         self.next_build_set = None
@@ -1156,6 +1138,8 @@
         self.ref = None
         self.commit = None
         self.zuul_url = None
+        self.dependent_items = None
+        self.merger_items = None
         self.unable_to_merge = False
         self.config_error = None  # None or an error message string.
         self.failing_reasons = []
@@ -1163,6 +1147,7 @@
         self.nodesets = {}  # job -> nodeset
         self.node_requests = {}  # job -> reqs
         self.files = RepoFiles()
+        self.repo_state = {}
         self.layout = None
         self.tries = {}
 
@@ -1176,13 +1161,19 @@
         # The change isn't enqueued until after it's created
         # so we don't know what the other changes ahead will be
         # until jobs start.
-        if not self.other_changes:
+        if self.dependent_items is None:
+            items = []
             next_item = self.item.item_ahead
             while next_item:
-                self.other_changes.append(next_item.change)
+                items.append(next_item)
                 next_item = next_item.item_ahead
+            self.dependent_items = items
         if not self.ref:
             self.ref = 'Z' + uuid4().hex
+        if self.merger_items is None:
+            items = [self.item] + self.dependent_items
+            items.reverse()
+            self.merger_items = [i.makeMergerItem() for i in items]
 
     def getStateName(self, state_num):
         return self.states_map.get(
@@ -1202,7 +1193,7 @@
         return self.builds.get(job_name)
 
     def getBuilds(self):
-        keys = self.builds.keys()
+        keys = list(self.builds.keys())
         keys.sort()
         return [self.builds.get(x) for x in keys]
 
@@ -1231,12 +1222,29 @@
         del self.node_requests[job_name]
 
     def getTries(self, job_name):
-        return self.tries.get(job_name)
+        return self.tries.get(job_name, 0)
 
     def getMergeMode(self):
-        if self.layout:
+        # We may be called before this build set has a shadow layout
+        # (ie, we are called to perform the merge to create that
+        # layout).  It's possible that the change we are merging will
+        # update the merge-mode for the project, but there's not much
+        # we can do about that here.  Instead, do the best we can by
+        # using the nearest shadow layout to determine the merge mode,
+        # or if that fails, the current live layout, or if that fails,
+        # use the default: merge-resolve.
+        item = self.item
+        layout = None
+        while item:
+            layout = item.current_build_set.layout
+            if layout:
+                break
+            item = item.item_ahead
+        if not layout:
+            layout = self.item.pipeline.layout
+        if layout:
             project = self.item.change.project
-            project_config = self.layout.project_configs.get(
+            project_config = layout.project_configs.get(
                 project.canonical_name)
             if project_config:
                 return project_config.merge_mode
@@ -1526,11 +1534,11 @@
         except KeyError as e:
             self.log.error("Error while formatting url for job %s: unknown "
                            "key %s in pattern %s"
-                           % (job, e.message, url_pattern))
+                           % (job, e.args[0], url_pattern))
         except AttributeError as e:
             self.log.error("Error while formatting url for job %s: unknown "
                            "attribute %s in pattern %s"
-                           % (job, e.message, url_pattern))
+                           % (job, e.args[0], url_pattern))
         except Exception:
             self.log.exception("Error while formatting url for job %s with "
                                "pattern %s:" % (job, url_pattern))
@@ -1805,11 +1813,12 @@
         self.can_merge = False
         self.is_merged = False
         self.failed_to_merge = False
-        self.approvals = []
         self.open = None
         self.status = None
         self.owner = None
 
+        self.source_event = None
+
     def _id(self):
         return '%s,%s' % (self.number, self.patchset)
 
@@ -1856,23 +1865,10 @@
                           patchset=self.patchset)
 
 
-class PullRequest(Change):
-    def __init__(self, project):
-        super(PullRequest, self).__init__(project)
-        self.updated_at = None
-
-    def isUpdateOf(self, other):
-        if (hasattr(other, 'number') and self.number == other.number and
-            hasattr(other, 'patchset') and self.patchset != other.patchset and
-            hasattr(other, 'updated_at') and
-            self.updated_at > other.updated_at):
-            return True
-        return False
-
-
 class TriggerEvent(object):
     """Incoming event from an external system."""
     def __init__(self):
+        # TODO(jeblair): further reduce this list
         self.data = None
         # common
         self.type = None
@@ -1888,19 +1884,13 @@
         self.change_url = None
         self.patch_number = None
         self.refspec = None
-        self.approvals = []
         self.branch = None
         self.comment = None
-        self.label = None
-        self.unlabel = None
+        self.state = None
         # ref-updated
         self.ref = None
         self.oldrev = None
         self.newrev = None
-        # timer
-        self.timespec = None
-        # zuultrigger
-        self.pipeline_name = None
         # For events that arrive with a destination pipeline (eg, from
         # an admin command, etc):
         self.forced_pipeline = None
@@ -1909,363 +1899,35 @@
     def canonical_project_name(self):
         return self.project_hostname + '/' + self.project_name
 
-    def __repr__(self):
-        ret = '<TriggerEvent %s %s' % (self.type, self.canonical_project_name)
-
-        if self.branch:
-            ret += " %s" % self.branch
-        if self.change_number:
-            ret += " %s,%s" % (self.change_number, self.patch_number)
-        if self.approvals:
-            ret += ' ' + ', '.join(
-                ['%s:%s' % (a['type'], a['value']) for a in self.approvals])
-        ret += '>'
-
-        return ret
-
     def isPatchsetCreated(self):
-        return 'patchset-created' == self.type
-
-    def isChangeAbandoned(self):
-        return 'change-abandoned' == self.type
-
-
-class GithubTriggerEvent(TriggerEvent):
-
-    def isPatchsetCreated(self):
-        if self.type == 'pull_request':
-            return self.action in ['opened', 'changed']
         return False
 
     def isChangeAbandoned(self):
-        if self.type == 'pull_request':
-            return 'closed' == self.action
         return False
 
 
 class BaseFilter(object):
     """Base Class for filtering which Changes and Events to process."""
-    def __init__(self, required_approvals=[], reject_approvals=[]):
-        self._required_approvals = copy.deepcopy(required_approvals)
-        self.required_approvals = self._tidy_approvals(required_approvals)
-        self._reject_approvals = copy.deepcopy(reject_approvals)
-        self.reject_approvals = self._tidy_approvals(reject_approvals)
-
-    def _tidy_approvals(self, approvals):
-        for a in approvals:
-            for k, v in a.items():
-                if k == 'username':
-                    a['username'] = re.compile(v)
-                elif k in ['email', 'email-filter']:
-                    a['email'] = re.compile(v)
-                elif k == 'newer-than':
-                    a[k] = time_to_seconds(v)
-                elif k == 'older-than':
-                    a[k] = time_to_seconds(v)
-            if 'email-filter' in a:
-                del a['email-filter']
-        return approvals
-
-    def _match_approval_required_approval(self, rapproval, approval):
-        # Check if the required approval and approval match
-        if 'description' not in approval:
-            return False
-        now = time.time()
-        by = approval.get('by', {})
-        for k, v in rapproval.items():
-            if k == 'username':
-                if (not v.search(by.get('username', ''))):
-                        return False
-            elif k == 'email':
-                if (not v.search(by.get('email', ''))):
-                        return False
-            elif k == 'newer-than':
-                t = now - v
-                if (approval['grantedOn'] < t):
-                        return False
-            elif k == 'older-than':
-                t = now - v
-                if (approval['grantedOn'] >= t):
-                    return False
-            else:
-                if not isinstance(v, list):
-                    v = [v]
-                if (normalizeCategory(approval['description']) != k or
-                        int(approval['value']) not in v):
-                    return False
-        return True
-
-    def matchesApprovals(self, change):
-        if (self.required_approvals and not change.approvals
-                or self.reject_approvals and not change.approvals):
-            # A change with no approvals can not match
-            return False
-
-        # TODO(jhesketh): If we wanted to optimise this slightly we could
-        # analyse both the REQUIRE and REJECT filters by looping over the
-        # approvals on the change and keeping track of what we have checked
-        # rather than needing to loop on the change approvals twice
-        return (self.matchesRequiredApprovals(change) and
-                self.matchesNoRejectApprovals(change))
-
-    def matchesRequiredApprovals(self, change):
-        # Check if any approvals match the requirements
-        for rapproval in self.required_approvals:
-            matches_rapproval = False
-            for approval in change.approvals:
-                if self._match_approval_required_approval(rapproval, approval):
-                    # We have a matching approval so this requirement is
-                    # fulfilled
-                    matches_rapproval = True
-                    break
-            if not matches_rapproval:
-                return False
-        return True
-
-    def matchesNoRejectApprovals(self, change):
-        # Check to make sure no approvals match a reject criteria
-        for rapproval in self.reject_approvals:
-            for approval in change.approvals:
-                if self._match_approval_required_approval(rapproval, approval):
-                    # A reject approval has been matched, so we reject
-                    # immediately
-                    return False
-        # To get here no rejects can have been matched so we should be good to
-        # queue
-        return True
+    pass
 
 
 class EventFilter(BaseFilter):
     """Allows a Pipeline to only respond to certain events."""
-    def __init__(self, trigger, types=[], branches=[], refs=[],
-                 event_approvals={}, comments=[], emails=[], usernames=[],
-                 timespecs=[], required_approvals=[], reject_approvals=[],
-                 pipelines=[], actions=[], labels=[], unlabels=[],
-                 ignore_deletes=True):
-        super(EventFilter, self).__init__(
-            required_approvals=required_approvals,
-            reject_approvals=reject_approvals)
+    def __init__(self, trigger):
+        super(EventFilter, self).__init__()
         self.trigger = trigger
-        self._types = types
-        self._branches = branches
-        self._refs = refs
-        self._comments = comments
-        self._emails = emails
-        self._usernames = usernames
-        self._pipelines = pipelines
-        self.types = [re.compile(x) for x in types]
-        self.branches = [re.compile(x) for x in branches]
-        self.refs = [re.compile(x) for x in refs]
-        self.comments = [re.compile(x) for x in comments]
-        self.emails = [re.compile(x) for x in emails]
-        self.usernames = [re.compile(x) for x in usernames]
-        self.pipelines = [re.compile(x) for x in pipelines]
-        self.actions = actions
-        self.event_approvals = event_approvals
-        self.timespecs = timespecs
-        self.labels = labels
-        self.unlabels = unlabels
-        self.ignore_deletes = ignore_deletes
 
-    def __repr__(self):
-        ret = '<EventFilter'
-
-        if self._types:
-            ret += ' types: %s' % ', '.join(self._types)
-        if self._pipelines:
-            ret += ' pipelines: %s' % ', '.join(self._pipelines)
-        if self._branches:
-            ret += ' branches: %s' % ', '.join(self._branches)
-        if self._refs:
-            ret += ' refs: %s' % ', '.join(self._refs)
-        if self.ignore_deletes:
-            ret += ' ignore_deletes: %s' % self.ignore_deletes
-        if self.event_approvals:
-            ret += ' event_approvals: %s' % ', '.join(
-                ['%s:%s' % a for a in self.event_approvals.items()])
-        if self.required_approvals:
-            ret += ' required_approvals: %s' % ', '.join(
-                ['%s' % a for a in self._required_approvals])
-        if self.reject_approvals:
-            ret += ' reject_approvals: %s' % ', '.join(
-                ['%s' % a for a in self._reject_approvals])
-        if self._comments:
-            ret += ' comments: %s' % ', '.join(self._comments)
-        if self._emails:
-            ret += ' emails: %s' % ', '.join(self._emails)
-        if self._usernames:
-            ret += ' username_filters: %s' % ', '.join(self._usernames)
-        if self.timespecs:
-            ret += ' timespecs: %s' % ', '.join(self.timespecs)
-        if self.actions:
-            ret += ' actions: %s' % ', '.join(self.actions)
-        if self.labels:
-            ret += ' labels: %s' % ', '.join(self.labels)
-        if self.unlabels:
-            ret += ' unlabels: %s' % ', '.join(self.unlabels)
-        ret += '>'
-
-        return ret
-
-    def matches(self, event, change):
-        # event types are ORed
-        matches_type = False
-        for etype in self.types:
-            if etype.match(event.type):
-                matches_type = True
-        if self.types and not matches_type:
-            return False
-
-        # pipelines are ORed
-        matches_pipeline = False
-        for epipe in self.pipelines:
-            if epipe.match(event.pipeline_name):
-                matches_pipeline = True
-        if self.pipelines and not matches_pipeline:
-            return False
-
-        # branches are ORed
-        matches_branch = False
-        for branch in self.branches:
-            if branch.match(event.branch):
-                matches_branch = True
-        if self.branches and not matches_branch:
-            return False
-
-        # refs are ORed
-        matches_ref = False
-        if event.ref is not None:
-            for ref in self.refs:
-                if ref.match(event.ref):
-                    matches_ref = True
-        if self.refs and not matches_ref:
-            return False
-        if self.ignore_deletes and event.newrev == EMPTY_GIT_REF:
-            # If the updated ref has an empty git sha (all 0s),
-            # then the ref is being deleted
-            return False
-
-        # comments are ORed
-        matches_comment_re = False
-        for comment_re in self.comments:
-            if (event.comment is not None and
-                comment_re.search(event.comment)):
-                matches_comment_re = True
-        if self.comments and not matches_comment_re:
-            return False
-
-        # We better have an account provided by Gerrit to do
-        # email filtering.
-        if event.account is not None:
-            account_email = event.account.get('email')
-            # emails are ORed
-            matches_email_re = False
-            for email_re in self.emails:
-                if (account_email is not None and
-                        email_re.search(account_email)):
-                    matches_email_re = True
-            if self.emails and not matches_email_re:
-                return False
-
-            # usernames are ORed
-            account_username = event.account.get('username')
-            matches_username_re = False
-            for username_re in self.usernames:
-                if (account_username is not None and
-                    username_re.search(account_username)):
-                    matches_username_re = True
-            if self.usernames and not matches_username_re:
-                return False
-
-        # approvals are ANDed
-        for category, value in self.event_approvals.items():
-            matches_approval = False
-            for eapproval in event.approvals:
-                if (normalizeCategory(eapproval['description']) == category and
-                    int(eapproval['value']) == int(value)):
-                    matches_approval = True
-            if not matches_approval:
-                return False
-
-        # required approvals are ANDed (reject approvals are ORed)
-        if not self.matchesApprovals(change):
-            return False
-
-        # timespecs are ORed
-        matches_timespec = False
-        for timespec in self.timespecs:
-            if (event.timespec == timespec):
-                matches_timespec = True
-        if self.timespecs and not matches_timespec:
-            return False
-
-        # actions are ORed
-        matches_action = False
-        for action in self.actions:
-            if (event.action == action):
-                matches_action = True
-        if self.actions and not matches_action:
-            return False
-
-        # labels are ORed
-        if self.labels and event.label not in self.labels:
-            return False
-
-        # unlabels are ORed
-        if self.unlabels and event.unlabel not in self.unlabels:
-            return False
-
+    def matches(self, event, ref):
+        # TODO(jeblair): consider removing ref argument
         return True
 
 
-class ChangeishFilter(BaseFilter):
+class RefFilter(BaseFilter):
     """Allows a Manager to only enqueue Changes that meet certain criteria."""
-    def __init__(self, open=None, current_patchset=None,
-                 statuses=[], required_approvals=[],
-                 reject_approvals=[]):
-        super(ChangeishFilter, self).__init__(
-            required_approvals=required_approvals,
-            reject_approvals=reject_approvals)
-        self.open = open
-        self.current_patchset = current_patchset
-        self.statuses = statuses
-
-    def __repr__(self):
-        ret = '<ChangeishFilter'
-
-        if self.open is not None:
-            ret += ' open: %s' % self.open
-        if self.current_patchset is not None:
-            ret += ' current-patchset: %s' % self.current_patchset
-        if self.statuses:
-            ret += ' statuses: %s' % ', '.join(self.statuses)
-        if self.required_approvals:
-            ret += (' required_approvals: %s' %
-                    str(self.required_approvals))
-        if self.reject_approvals:
-            ret += (' reject_approvals: %s' %
-                    str(self.reject_approvals))
-        ret += '>'
-
-        return ret
+    def __init__(self):
+        super(RefFilter, self).__init__()
 
     def matches(self, change):
-        if self.open is not None:
-            if self.open != change.open:
-                return False
-
-        if self.current_patchset is not None:
-            if self.current_patchset != change.is_current_patchset:
-                return False
-
-        if self.statuses:
-            if change.status not in self.statuses:
-                return False
-
-        # required approvals are ANDed (reject approvals are ORed)
-        if not self.matchesApprovals(change):
-            return False
-
         return True
 
 
@@ -2282,6 +1944,7 @@
     def __init__(self, name):
         self.name = name
         self.merge_mode = None
+        self.default_branch = None
         self.pipelines = {}
         self.private_key_file = None
 
@@ -2313,7 +1976,7 @@
                 raise Exception("Configuration item dictionaries must have "
                                 "a single key (when parsing %s)" %
                                 (conf,))
-            key, value = item.items()[0]
+            key, value = list(item.items())[0]
             if key == 'tenant':
                 self.tenants.append(value)
             else:
@@ -2371,7 +2034,7 @@
                 raise Exception("Configuration item dictionaries must have "
                                 "a single key (when parsing %s)" %
                                 (conf,))
-            key, value = item.items()[0]
+            key, value = list(item.items())[0]
             if key == 'project':
                 name = value['name']
                 self.projects.setdefault(name, []).append(value)
@@ -2678,7 +2341,7 @@
             if hostname:
                 project = hostname_dict.get(hostname)
             else:
-                values = hostname_dict.values()
+                values = list(hostname_dict.values())
                 if len(values) == 1:
                     project = values[0]
                 else:
@@ -2722,7 +2385,7 @@
     def load(self):
         if not os.path.exists(self.path):
             return
-        with open(self.path) as f:
+        with open(self.path, 'rb') as f:
             data = struct.unpack(self.format, f.read())
         version = data[0]
         if version != self.version:
@@ -2738,7 +2401,7 @@
         data.extend(self.failure_times)
         data.extend(self.results)
         data = struct.pack(self.format, *data)
-        with open(tmpfile, 'w') as f:
+        with open(tmpfile, 'wb') as f:
             f.write(data)
         os.rename(tmpfile, self.path)
 
diff --git a/zuul/nodepool.py b/zuul/nodepool.py
index e94b950..8f6489c 100644
--- a/zuul/nodepool.py
+++ b/zuul/nodepool.py
@@ -38,11 +38,11 @@
     def cancelRequest(self, request):
         self.log.info("Canceling node request %s" % (request,))
         if request.uid in self.requests:
+            request.canceled = True
             try:
                 self.sched.zk.deleteNodeRequest(request)
             except Exception:
                 self.log.exception("Error deleting node request:")
-            del self.requests[request.uid]
 
     def useNodeSet(self, nodeset):
         self.log.info("Setting nodeset %s in use" % (nodeset,))
@@ -98,6 +98,10 @@
         if request.uid not in self.requests:
             return False
 
+        if request.canceled:
+            del self.requests[request.uid]
+            return False
+
         if request.state in (model.STATE_FULFILLED, model.STATE_FAILED):
             self.log.info("Node request %s %s" % (request, request.state))
 
@@ -119,6 +123,11 @@
 
         self.log.info("Accepting node request %s" % (request,))
 
+        if request.canceled:
+            self.log.info("Ignoring canceled node request %s" % (request,))
+            # The request was already deleted when it was canceled
+            return
+
         locked = False
         if request.fulfilled:
             # If the request suceeded, try to lock the nodes.
diff --git a/zuul/reporter/__init__.py b/zuul/reporter/__init__.py
index 5e25e7c..9c8e953 100644
--- a/zuul/reporter/__init__.py
+++ b/zuul/reporter/__init__.py
@@ -37,7 +37,7 @@
         self._action = action
 
     @abc.abstractmethod
-    def report(self, source, pipeline, item):
+    def report(self, pipeline, item):
         """Send the compiled report message."""
 
     def getSubmitAllowNeeds(self):
@@ -74,7 +74,12 @@
         return ret
 
     def _formatItemReportStart(self, pipeline, item, with_jobs=True):
-        return pipeline.start_message.format(pipeline=pipeline)
+        status_url = ''
+        if self.connection.sched.config.has_option('zuul', 'status_url'):
+            status_url = self.connection.sched.config.get('zuul',
+                                                          'status_url')
+        return pipeline.start_message.format(pipeline=pipeline,
+                                             status_url=status_url)
 
     def _formatItemReportSuccess(self, pipeline, item, with_jobs=True):
         msg = pipeline.success_message
diff --git a/zuul/rpcclient.py b/zuul/rpcclient.py
index 9d81520..d980992 100644
--- a/zuul/rpcclient.py
+++ b/zuul/rpcclient.py
@@ -35,9 +35,9 @@
 
     def submitJob(self, name, data):
         self.log.debug("Submitting job %s with data %s" % (name, data))
-        job = gear.Job(name,
-                       json.dumps(data),
-                       unique=str(time.time()))
+        job = gear.TextJob(name,
+                           json.dumps(data),
+                           unique=str(time.time()))
         self.gearman.submitJob(job, timeout=300)
 
         self.log.debug("Waiting for job completion")
diff --git a/zuul/rpclistener.py b/zuul/rpclistener.py
index 105c34b..6508e84 100644
--- a/zuul/rpclistener.py
+++ b/zuul/rpclistener.py
@@ -38,7 +38,7 @@
             port = self.config.get('gearman', 'port')
         else:
             port = 4730
-        self.worker = gear.Worker('Zuul RPC Listener')
+        self.worker = gear.TextWorker('Zuul RPC Listener')
         self.worker.addServer(server, port)
         self.worker.waitForServer()
         self.register()
diff --git a/zuul/scheduler.py b/zuul/scheduler.py
index 2e9bef2..40d5eb7 100644
--- a/zuul/scheduler.py
+++ b/zuul/scheduler.py
@@ -138,16 +138,18 @@
     :arg bool merged: Whether the merge succeeded (changes with refs).
     :arg bool updated: Whether the repo was updated (changes without refs).
     :arg str commit: The SHA of the merged commit (changes with refs).
+    :arg dict repo_state: The starting repo state before the merge.
     """
 
     def __init__(self, build_set, zuul_url, merged, updated, commit,
-                 files):
+                 files, repo_state):
         self.build_set = build_set
         self.zuul_url = zuul_url
         self.merged = merged
         self.updated = updated
         self.commit = commit
         self.files = files
+        self.repo_state = repo_state
 
 
 class NodesProvisionedEvent(ResultEvent):
@@ -316,11 +318,11 @@
         self.log.debug("Done adding complete event for build: %s" % build)
 
     def onMergeCompleted(self, build_set, zuul_url, merged, updated,
-                         commit, files):
+                         commit, files, repo_state):
         self.log.debug("Adding merge complete event for build set: %s" %
                        build_set)
         event = MergeCompletedEvent(build_set, zuul_url, merged,
-                                    updated, commit, files)
+                                    updated, commit, files, repo_state)
         self.result_event_queue.put(event)
         self.wake_event.set()
 
@@ -871,6 +873,8 @@
         build_set = request.build_set
 
         self.nodepool.acceptNodes(request)
+        if request.canceled:
+            return
 
         if build_set is not build_set.item.current_build_set:
             self.log.warning("Build set %s is not current" % (build_set,))
diff --git a/zuul/source/__init__.py b/zuul/source/__init__.py
index f0eeba6..68baf0e 100644
--- a/zuul/source/__init__.py
+++ b/zuul/source/__init__.py
@@ -69,3 +69,13 @@
     @abc.abstractmethod
     def getProjectBranches(self, project):
         """Get branches for a project"""
+
+    @abc.abstractmethod
+    def getRequireFilters(self, config):
+        """Return a list of ChangeFilters for the scheduler to match against.
+        """
+
+    @abc.abstractmethod
+    def getRejectFilters(self, config):
+        """Return a list of ChangeFilters for the scheduler to match against.
+        """
diff --git a/zuul/webapp.py b/zuul/webapp.py
index 37d6ddd..e4feaa0 100644
--- a/zuul/webapp.py
+++ b/zuul/webapp.py
@@ -128,7 +128,7 @@
     def app(self, request):
         # Try registered paths without a tenant_name first
         path = request.path
-        for path_re, handler in self.routes.itervalues():
+        for path_re, handler in self.routes.values():
             if path_re.match(path):
                 return handler(path, '', request)
 
@@ -138,7 +138,7 @@
         # Handle keys
         if path.startswith('/keys'):
             return self._handle_keys(request, path)
-        for path_re, handler in self.routes.itervalues():
+        for path_re, handler in self.routes.values():
             if path_re.match(path):
                 return handler(path, tenant_name, request)
         else:
@@ -147,7 +147,8 @@
     def status(self, path, tenant_name, request):
         def func():
             return webob.Response(body=self.cache[tenant_name],
-                                  content_type='application/json')
+                                  content_type='application/json',
+                                  charset='utf8')
         return self._response_with_status_cache(func, tenant_name)
 
     def change(self, path, tenant_name, request):
@@ -157,7 +158,8 @@
             status = self._status_for_change(change_id, tenant_name)
             if status:
                 return webob.Response(body=status,
-                                      content_type='application/json')
+                                      content_type='application/json',
+                                      charset='utf8')
             else:
                 raise webob.exc.HTTPNotFound()
         return self._response_with_status_cache(func, tenant_name)
diff --git a/zuul/zk.py b/zuul/zk.py
index 5cd7bee..31b85ea 100644
--- a/zuul/zk.py
+++ b/zuul/zk.py
@@ -59,10 +59,10 @@
         self._became_lost = False
 
     def _dictToStr(self, data):
-        return json.dumps(data)
+        return json.dumps(data).encode('utf8')
 
     def _strToDict(self, data):
-        return json.loads(data)
+        return json.loads(data.decode('utf8'))
 
     def _connection_listener(self, state):
         '''
@@ -168,7 +168,7 @@
             if data:
                 data = self._strToDict(data)
                 node_request.updateFromDict(data)
-                request_nodes = node_request.nodeset.getNodes()
+                request_nodes = list(node_request.nodeset.getNodes())
                 for i, nodeid in enumerate(data.get('nodes', [])):
                     node_path = '%s/%s' % (self.NODE_ROOT, nodeid)
                     node_data, node_stat = self.client.get(node_path)