Stop jobs when executor stops

If the executor stops while jobs are running, those jobs are not
explicitly aborted.  In production, the process exit would cause
all of the jobs to terminate and the gearman disconnection would
report a failure, however, in tests the python process may continue
and the ansible threads would essentially leak into a subsequent
test.  This is especially likely to happen if a test holds jobs in
build, and then fails while those jobs are still held.  Those threads
will continue to wait to be released while further tests continue
to run.  Because all tests assert that git.Repo objects are not
leaked, the outstanding reference that the leaked threads have
to a git.Repo object trips that assertion and all subsequent tests
in the same test runner fail.

This adds code to the executor shutdown to stop all jobs at the start
of the shutdown process.  It also adds a test which shuts down the
executor while jobs are held and asserts that after shutdown, those
threads are stopped, and no git repo objects are leaked.

Change-Id: I9d73775a13c289ef922c27b29162efcfca3950a9
diff --git a/tests/unit/test_scheduler.py b/tests/unit/test_scheduler.py
index d3e6094..4a295c1 100755
--- a/tests/unit/test_scheduler.py
+++ b/tests/unit/test_scheduler.py
@@ -14,6 +14,7 @@
 # License for the specific language governing permissions and limitations
 # under the License.
 
+import gc
 import json
 import textwrap
 
@@ -4638,6 +4639,39 @@
         self.assertIn('project-test2 : SKIPPED', A.messages[1])
 
 
+class TestExecutor(ZuulTestCase):
+    tenant_config_file = 'config/single-tenant/main.yaml'
+
+    def assertFinalState(self):
+        # In this test, we expect to shut down in a non-final state,
+        # so skip these checks.
+        pass
+
+    def assertCleanShutdown(self):
+        self.log.debug("Assert clean shutdown")
+
+        # After shutdown, make sure no jobs are running
+        self.assertEqual({}, self.executor_server.job_workers)
+
+        # Make sure that git.Repo objects have been garbage collected.
+        repos = []
+        gc.collect()
+        for obj in gc.get_objects():
+            if isinstance(obj, git.Repo):
+                self.log.debug("Leaked git repo object: %s" % repr(obj))
+                repos.append(obj)
+        self.assertEqual(len(repos), 0)
+
+    def test_executor_shutdown(self):
+        "Test that the executor can shut down with jobs running"
+
+        self.executor_server.hold_jobs_in_build = True
+        A = self.fake_gerrit.addFakeChange('org/project', 'master', 'A')
+        A.addApproval('code-review', 2)
+        self.fake_gerrit.addEvent(A.addApproval('approved', 1))
+        self.waitUntilSettled()
+
+
 class TestDependencyGraph(ZuulTestCase):
     tenant_config_file = 'config/dependency-graph/main.yaml'