Browse Source

Initial commit.

tags/1.1.0
James E. Blair 7 years ago
commit
ee743613ce
16 changed files with 1537 additions and 0 deletions
  1. 6
    0
      .gitignore
  2. 4
    0
      .gitreview
  3. 1
    0
      AUTHORS
  4. 202
    0
      LICENSE
  5. 1
    0
      README
  6. 31
    0
      setup.py
  7. 53
    0
      zuul-server
  8. 0
    0
      zuul/__init__.py
  9. 0
    0
      zuul/launcher/__init__.py
  10. 217
    0
      zuul/launcher/jenkins.py
  11. 0
    0
      zuul/lib/__init__.py
  12. 171
    0
      zuul/lib/gerrit.py
  13. 323
    0
      zuul/model.py
  14. 436
    0
      zuul/scheduler.py
  15. 0
    0
      zuul/trigger/__init__.py
  16. 92
    0
      zuul/trigger/gerrit.py

+ 6
- 0
.gitignore View File

@@ -0,0 +1,6 @@
1
+build
2
+dist
3
+zuul.egg-info
4
+MANIFEST
5
+.tox
6
+

+ 4
- 0
.gitreview View File

@@ -0,0 +1,4 @@
1
+[gerrit]
2
+host=review.openstack.org
3
+port=29418
4
+project=openstack-ci/zuul.git

+ 1
- 0
AUTHORS View File

@@ -0,0 +1 @@
1
+James E. Blair <jeblair@hp.com>

+ 202
- 0
LICENSE View File

@@ -0,0 +1,202 @@
1
+
2
+                                 Apache License
3
+                           Version 2.0, January 2004
4
+                        http://www.apache.org/licenses/
5
+
6
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+   1. Definitions.
9
+
10
+      "License" shall mean the terms and conditions for use, reproduction,
11
+      and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+      "Licensor" shall mean the copyright owner or entity authorized by
14
+      the copyright owner that is granting the License.
15
+
16
+      "Legal Entity" shall mean the union of the acting entity and all
17
+      other entities that control, are controlled by, or are under common
18
+      control with that entity. For the purposes of this definition,
19
+      "control" means (i) the power, direct or indirect, to cause the
20
+      direction or management of such entity, whether by contract or
21
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+      outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+      "You" (or "Your") shall mean an individual or Legal Entity
25
+      exercising permissions granted by this License.
26
+
27
+      "Source" form shall mean the preferred form for making modifications,
28
+      including but not limited to software source code, documentation
29
+      source, and configuration files.
30
+
31
+      "Object" form shall mean any form resulting from mechanical
32
+      transformation or translation of a Source form, including but
33
+      not limited to compiled object code, generated documentation,
34
+      and conversions to other media types.
35
+
36
+      "Work" shall mean the work of authorship, whether in Source or
37
+      Object form, made available under the License, as indicated by a
38
+      copyright notice that is included in or attached to the work
39
+      (an example is provided in the Appendix below).
40
+
41
+      "Derivative Works" shall mean any work, whether in Source or Object
42
+      form, that is based on (or derived from) the Work and for which the
43
+      editorial revisions, annotations, elaborations, or other modifications
44
+      represent, as a whole, an original work of authorship. For the purposes
45
+      of this License, Derivative Works shall not include works that remain
46
+      separable from, or merely link (or bind by name) to the interfaces of,
47
+      the Work and Derivative Works thereof.
48
+
49
+      "Contribution" shall mean any work of authorship, including
50
+      the original version of the Work and any modifications or additions
51
+      to that Work or Derivative Works thereof, that is intentionally
52
+      submitted to Licensor for inclusion in the Work by the copyright owner
53
+      or by an individual or Legal Entity authorized to submit on behalf of
54
+      the copyright owner. For the purposes of this definition, "submitted"
55
+      means any form of electronic, verbal, or written communication sent
56
+      to the Licensor or its representatives, including but not limited to
57
+      communication on electronic mailing lists, source code control systems,
58
+      and issue tracking systems that are managed by, or on behalf of, the
59
+      Licensor for the purpose of discussing and improving the Work, but
60
+      excluding communication that is conspicuously marked or otherwise
61
+      designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+      "Contributor" shall mean Licensor and any individual or Legal Entity
64
+      on behalf of whom a Contribution has been received by Licensor and
65
+      subsequently incorporated within the Work.
66
+
67
+   2. Grant of Copyright License. Subject to the terms and conditions of
68
+      this License, each Contributor hereby grants to You a perpetual,
69
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+      copyright license to reproduce, prepare Derivative Works of,
71
+      publicly display, publicly perform, sublicense, and distribute the
72
+      Work and such Derivative Works in Source or Object form.
73
+
74
+   3. Grant of Patent License. Subject to the terms and conditions of
75
+      this License, each Contributor hereby grants to You a perpetual,
76
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+      (except as stated in this section) patent license to make, have made,
78
+      use, offer to sell, sell, import, and otherwise transfer the Work,
79
+      where such license applies only to those patent claims licensable
80
+      by such Contributor that are necessarily infringed by their
81
+      Contribution(s) alone or by combination of their Contribution(s)
82
+      with the Work to which such Contribution(s) was submitted. If You
83
+      institute patent litigation against any entity (including a
84
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+      or a Contribution incorporated within the Work constitutes direct
86
+      or contributory patent infringement, then any patent licenses
87
+      granted to You under this License for that Work shall terminate
88
+      as of the date such litigation is filed.
89
+
90
+   4. Redistribution. You may reproduce and distribute copies of the
91
+      Work or Derivative Works thereof in any medium, with or without
92
+      modifications, and in Source or Object form, provided that You
93
+      meet the following conditions:
94
+
95
+      (a) You must give any other recipients of the Work or
96
+          Derivative Works a copy of this License; and
97
+
98
+      (b) You must cause any modified files to carry prominent notices
99
+          stating that You changed the files; and
100
+
101
+      (c) You must retain, in the Source form of any Derivative Works
102
+          that You distribute, all copyright, patent, trademark, and
103
+          attribution notices from the Source form of the Work,
104
+          excluding those notices that do not pertain to any part of
105
+          the Derivative Works; and
106
+
107
+      (d) If the Work includes a "NOTICE" text file as part of its
108
+          distribution, then any Derivative Works that You distribute must
109
+          include a readable copy of the attribution notices contained
110
+          within such NOTICE file, excluding those notices that do not
111
+          pertain to any part of the Derivative Works, in at least one
112
+          of the following places: within a NOTICE text file distributed
113
+          as part of the Derivative Works; within the Source form or
114
+          documentation, if provided along with the Derivative Works; or,
115
+          within a display generated by the Derivative Works, if and
116
+          wherever such third-party notices normally appear. The contents
117
+          of the NOTICE file are for informational purposes only and
118
+          do not modify the License. You may add Your own attribution
119
+          notices within Derivative Works that You distribute, alongside
120
+          or as an addendum to the NOTICE text from the Work, provided
121
+          that such additional attribution notices cannot be construed
122
+          as modifying the License.
123
+
124
+      You may add Your own copyright statement to Your modifications and
125
+      may provide additional or different license terms and conditions
126
+      for use, reproduction, or distribution of Your modifications, or
127
+      for any such Derivative Works as a whole, provided Your use,
128
+      reproduction, and distribution of the Work otherwise complies with
129
+      the conditions stated in this License.
130
+
131
+   5. Submission of Contributions. Unless You explicitly state otherwise,
132
+      any Contribution intentionally submitted for inclusion in the Work
133
+      by You to the Licensor shall be under the terms and conditions of
134
+      this License, without any additional terms or conditions.
135
+      Notwithstanding the above, nothing herein shall supersede or modify
136
+      the terms of any separate license agreement you may have executed
137
+      with Licensor regarding such Contributions.
138
+
139
+   6. Trademarks. This License does not grant permission to use the trade
140
+      names, trademarks, service marks, or product names of the Licensor,
141
+      except as required for reasonable and customary use in describing the
142
+      origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+   7. Disclaimer of Warranty. Unless required by applicable law or
145
+      agreed to in writing, Licensor provides the Work (and each
146
+      Contributor provides its Contributions) on an "AS IS" BASIS,
147
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+      implied, including, without limitation, any warranties or conditions
149
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+      PARTICULAR PURPOSE. You are solely responsible for determining the
151
+      appropriateness of using or redistributing the Work and assume any
152
+      risks associated with Your exercise of permissions under this License.
153
+
154
+   8. Limitation of Liability. In no event and under no legal theory,
155
+      whether in tort (including negligence), contract, or otherwise,
156
+      unless required by applicable law (such as deliberate and grossly
157
+      negligent acts) or agreed to in writing, shall any Contributor be
158
+      liable to You for damages, including any direct, indirect, special,
159
+      incidental, or consequential damages of any character arising as a
160
+      result of this License or out of the use or inability to use the
161
+      Work (including but not limited to damages for loss of goodwill,
162
+      work stoppage, computer failure or malfunction, or any and all
163
+      other commercial damages or losses), even if such Contributor
164
+      has been advised of the possibility of such damages.
165
+
166
+   9. Accepting Warranty or Additional Liability. While redistributing
167
+      the Work or Derivative Works thereof, You may choose to offer,
168
+      and charge a fee for, acceptance of support, warranty, indemnity,
169
+      or other liability obligations and/or rights consistent with this
170
+      License. However, in accepting such obligations, You may act only
171
+      on Your own behalf and on Your sole responsibility, not on behalf
172
+      of any other Contributor, and only if You agree to indemnify,
173
+      defend, and hold each Contributor harmless for any liability
174
+      incurred by, or claims asserted against, such Contributor by reason
175
+      of your accepting any such warranty or additional liability.
176
+
177
+   END OF TERMS AND CONDITIONS
178
+
179
+   APPENDIX: How to apply the Apache License to your work.
180
+
181
+      To apply the Apache License to your work, attach the following
182
+      boilerplate notice, with the fields enclosed by brackets "[]"
183
+      replaced with your own identifying information. (Don't include
184
+      the brackets!)  The text should be enclosed in the appropriate
185
+      comment syntax for the file format. We also recommend that a
186
+      file or class name and description of purpose be included on the
187
+      same "printed page" as the copyright notice for easier
188
+      identification within third-party archives.
189
+
190
+   Copyright [yyyy] [name of copyright owner]
191
+
192
+   Licensed under the Apache License, Version 2.0 (the "License");
193
+   you may not use this file except in compliance with the License.
194
+   You may obtain a copy of the License at
195
+
196
+       http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+   Unless required by applicable law or agreed to in writing, software
199
+   distributed under the License is distributed on an "AS IS" BASIS,
200
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+   See the License for the specific language governing permissions and
202
+   limitations under the License.

+ 1
- 0
README View File

@@ -0,0 +1 @@
1
+This is a trunk gating system developed for the OpenStack Project.

+ 31
- 0
setup.py View File

@@ -0,0 +1,31 @@
1
+#!/usr/bin/env python
2
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
3
+#
4
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
5
+# not use this file except in compliance with the License. You may obtain
6
+# a copy of the License at
7
+#
8
+#      http://www.apache.org/licenses/LICENSE-2.0
9
+#
10
+# Unless required by applicable law or agreed to in writing, software
11
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
+# License for the specific language governing permissions and limitations
14
+# under the License.
15
+
16
+from setuptools import find_packages
17
+from setuptools.command.sdist import sdist
18
+from setuptools import setup
19
+import subprocess
20
+
21
+setup(name='zuul',
22
+      version='1.0',
23
+      description="Trunk gating system",
24
+      license='Apache License (2.0)',
25
+      author='Hewlett-Packard Development Company, L.P.',
26
+      author_email='openstack@lists.launchpad.net',
27
+      url='http://launchpad.net/zuul',
28
+      scripts=['zuul-server'],
29
+      include_package_data=True,
30
+      zip_safe=False,
31
+      )

+ 53
- 0
zuul-server View File

@@ -0,0 +1,53 @@
1
+import argparse
2
+import ConfigParser
3
+import os
4
+
5
+import zuul.scheduler
6
+import zuul.launcher.jenkins
7
+import zuul.trigger.gerrit
8
+
9
+import logging.config
10
+
11
+def parse_arguments():
12
+    parser = argparse.ArgumentParser(description='Project gating system.')
13
+    parser.add_argument('-c', dest='config',
14
+                        help='specify the config file')
15
+    return parser.parse_args()
16
+
17
+def read_config(args):
18
+    config=ConfigParser.ConfigParser()
19
+    if args.config:
20
+        locations = [args.config]
21
+    else:
22
+        locations = ['/etc/zuul/zuul.conf',
23
+                     '~/zuul.conf']
24
+    for fp in locations:
25
+        if os.path.exists(os.path.expanduser(fp)):
26
+            config.read(fp)
27
+            return config
28
+    raise Exception("Unable to locate config file in %s" % locations)
29
+
30
+def setup_logging(config):
31
+    if config.has_option('zuul', 'log_config'):
32
+        fp = os.path.expanduser(config.get('zuul', 'log_config'))
33
+        if not os.path.exists(fp):
34
+            raise Exception("Unable to read logging config file at %s" % fp)
35
+        logging.config.fileConfig(fp)
36
+    else:
37
+        logging.basicConfig(level=logging.DEBUG)
38
+
39
+def main(config):
40
+    sched = zuul.scheduler.Scheduler(config)
41
+
42
+    jenkins = zuul.launcher.jenkins.Jenkins(config, sched)
43
+    gerrit = zuul.trigger.gerrit.Gerrit(config, sched)
44
+
45
+    sched.setLauncher(jenkins)
46
+    sched.setTrigger(gerrit)
47
+    sched.run()
48
+
49
+if __name__ == '__main__':
50
+    args = parse_arguments()
51
+    config = read_config(args)
52
+    setup_logging(config)
53
+    main(config)

+ 0
- 0
zuul/__init__.py View File


+ 0
- 0
zuul/launcher/__init__.py View File


+ 217
- 0
zuul/launcher/jenkins.py View File

@@ -0,0 +1,217 @@
1
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+# So we can name this module "jenkins" and still load the "jenkins"
16
+# system module
17
+from __future__ import absolute_import
18
+
19
+import threading
20
+from webob import Request
21
+from paste import httpserver
22
+from uuid import uuid1
23
+import jenkins
24
+import json
25
+import urllib2  # for extending jenkins lib
26
+import logging
27
+import pprint
28
+
29
+from zuul.model import Build
30
+
31
+class JenkinsCallback(threading.Thread):
32
+    log = logging.getLogger("zuul.JenkinsCallback")
33
+
34
+    def __init__(self, jenkins):
35
+        threading.Thread.__init__(self)
36
+        self.jenkins = jenkins
37
+
38
+    def run(self):
39
+        httpserver.serve(self.app, host='0.0.0.0', port='8080')
40
+
41
+    def app(self, environ, start_response):
42
+        request = Request(environ)
43
+        if request.path == '/jenkins_endpoint':
44
+            self.jenkins_endpoint(request)
45
+        start_response('200 OK', [('content-type', 'text/html')])
46
+        return ['Zuul good.']
47
+
48
+    def jenkins_endpoint(self, request):
49
+        data = json.loads(request.body)
50
+        if data:
51
+            self.log.debug("Received data from Jenkins: \n%s" % (
52
+                    pprint.pformat(data)))
53
+            build = data.get('build')
54
+            if build:
55
+                phase = build.get('phase')
56
+                status = build.get('status')
57
+                url = build.get('full_url')
58
+                number = build.get('number')
59
+                params = build.get('parameters')
60
+                if params:
61
+                    uuid = params.get('UUID')
62
+                    if (status and url and uuid and phase
63
+                        and phase == 'COMPLETED'):
64
+                        self.jenkins.onBuildCompleted(uuid, status, url, number)
65
+                    if (phase and phase == 'STARTED'):
66
+                        self.jenkins.onBuildStarted(uuid, url, number)
67
+
68
+
69
+STOP_BUILD = 'job/%(name)s/%(number)s/stop'
70
+CANCEL_QUEUE = 'queue/item/%(number)s/cancelQueue'
71
+BUILD_INFO = 'job/%(name)s/%(number)s/api/json?depth=0'
72
+
73
+class ExtendedJenkins(jenkins.Jenkins):
74
+    def jenkins_open(self, req):
75
+        '''
76
+        Utility routine for opening an HTTP request to a Jenkins server. 
77
+        '''
78
+        try:
79
+            if self.auth:
80
+                req.add_header('Authorization', self.auth)
81
+            return urllib2.urlopen(req).read()
82
+        except urllib2.HTTPError, e:
83
+            print e.msg
84
+            print e.fp.read()
85
+            raise
86
+
87
+    def stop_build(self, name, number):
88
+        '''
89
+        Stop a running Jenkins build.
90
+
91
+        @param name: Name of Jenkins job
92
+        @type  name: str
93
+        @param number: Jenkins build number for the job
94
+        @type  number: int
95
+        '''
96
+        self.jenkins_open(urllib2.Request(self.server + STOP_BUILD%locals()))
97
+
98
+    def cancel_queue(self, number):
99
+        '''
100
+        Cancel a queued build.
101
+
102
+        @param number: Jenkins queue number for the build
103
+        @type  number: int
104
+        '''
105
+        # Jenkins returns a 302 from this URL, unless Referer is not set,
106
+        # then you get a 404.
107
+        self.jenkins_open(urllib2.Request(self.server + CANCEL_QUEUE%locals(),
108
+                                          headers={'Referer': self.server}))
109
+
110
+
111
+    def get_build_info(self, name, number):
112
+        '''
113
+        Get information for a build.
114
+
115
+        @param name: Name of Jenkins job
116
+        @type  name: str
117
+        @param number: Jenkins build number for the job
118
+        @type  number: int
119
+        @return: dictionary
120
+        '''
121
+        return json.loads(self.jenkins_open(urllib2.Request(self.server + BUILD_INFO%locals())))
122
+
123
+class Jenkins(object):
124
+    log = logging.getLogger("zuul.Jenkins")
125
+
126
+    def __init__(self, config, sched):
127
+        self.sched = sched
128
+        self.builds = {}
129
+        server = config.get('jenkins', 'server')
130
+        user = config.get('jenkins', 'user')
131
+        apikey = config.get('jenkins', 'apikey')
132
+        self.jenkins = ExtendedJenkins(server, user, apikey)
133
+        self.callback_thread = JenkinsCallback(self)
134
+        self.callback_thread.start()
135
+    
136
+    def launch(self, job, change, dependent_changes = []):
137
+        self.log.info("Launch job %s for change %s with dependent changes %s" % (
138
+                job, change, dependent_changes))
139
+        uuid = str(uuid1())
140
+        params = dict(UUID=uuid)
141
+        build = Build(job, uuid)
142
+        self.builds[uuid] = build
143
+        # We can get the started notification on another thread before this is done
144
+        # so we add the build even before we trigger the job on Jenkins.  We should
145
+        # be careful to clean it up if it doesn't actually kick off.
146
+        try:
147
+            self.jenkins.build_job(job.name, parameters=params)
148
+        except:
149
+            self.log.exception("Exception launching build %s for job %s for change %s:" % (
150
+                    build, job, change))
151
+            # Whoops.  Remove that build we added.
152
+            del self.builds[uuid]
153
+            raise
154
+        return build
155
+
156
+    def cancel(self, build):
157
+        self.log.info("Cancel build %s for job %s" % (build, build.job))
158
+        if build.number:
159
+            self.log.debug("Build %s has already started" % build)
160
+            self.jenkins.stop_build(build.job.name, build.number)
161
+            self.log.debug("Canceled running build %s" % build)
162
+            return
163
+        else:
164
+            self.log.debug("Build %s has not started yet" % build)
165
+
166
+        self.log.debug("Looking for build %s in queue" % build)
167
+        for item in self.jenkins.get_queue_info():
168
+            if not item.has_key('actions'):
169
+                continue
170
+            for action in item['actions']:
171
+                if not action.has_key('parameters'):
172
+                    continue
173
+                parameters = action['parameters']
174
+                for param in parameters:
175
+                    if (param['name'] == 'UUID' and build.uuid == param['value']):
176
+                        self.log.debug("Found queue item %s for build %s" % (
177
+                                item['id'], build))
178
+                        try:
179
+                            self.jenkins.cancel_queue(item['id'])
180
+                            self.log.debug("Canceled queue item %s for build %s" % (
181
+                                    item['id'], build))
182
+                            return
183
+                        except:
184
+                            self.log.exception("Exception canceling queue item %s for build %s" % (
185
+                                    item['id'], build))
186
+
187
+        self.log.debug("Still unable to find build %s to cancel" % build)
188
+        if build.number:
189
+            self.log.debug("Build %s has just started" % build)
190
+            self.jenkins.stop_build(build.job.name, build.number)
191
+            self.log.debug("Canceled just running build %s" % build)
192
+        else:
193
+            self.log.error("Build %s has not started but was not found in queue" % build)
194
+    
195
+    def onBuildCompleted(self, uuid, status, url, number):
196
+        self.log.info("Build %s #%s complete, status %s" % (
197
+                uuid, number, status))
198
+        build = self.builds.get(uuid)
199
+        if build:
200
+            self.log.debug("Found build %s" % build)
201
+            del self.builds[uuid]
202
+            build.result = status
203
+            build.url = url
204
+            build.number = number
205
+            self.sched.onBuildCompleted(build)
206
+        else:
207
+            self.log.error("Unable to find build %s" % uuid)
208
+
209
+    def onBuildStarted(self, uuid, url, number):
210
+        self.log.info("Build %s #%s started, url: %s" % (uuid, number, url))
211
+        build = self.builds.get(uuid)
212
+        if build:
213
+            self.log.debug("Found build %s" % build)
214
+            build.url = url
215
+            build.number = number
216
+        else:
217
+            self.log.error("Unable to find build %s" % uuid)

+ 0
- 0
zuul/lib/__init__.py View File


+ 171
- 0
zuul/lib/gerrit.py View File

@@ -0,0 +1,171 @@
1
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+import threading
16
+import select
17
+import json
18
+import time
19
+import subprocess
20
+import Queue
21
+import paramiko
22
+import logging
23
+import pprint
24
+
25
+# TODO: switch this to paramiko?
26
+
27
+class GerritWatcher(threading.Thread):
28
+    log = logging.getLogger("gerrit.GerritWatcher")
29
+
30
+    def __init__(self, gerrit, username, server, port=29418, keyfile=None):
31
+        threading.Thread.__init__(self)
32
+        self.username = username
33
+        self.keyfile = keyfile
34
+        self.server = server
35
+        self.port = port
36
+        self.proc = None
37
+        self.poll = select.poll()
38
+        self.gerrit = gerrit
39
+
40
+    def _open(self):
41
+        self.log.debug("Opening ssh connection to %s" % self.server)
42
+        cmd = ['/usr/bin/ssh', '-p', str(self.port)]
43
+        if self.keyfile:
44
+            cmd += ['-i', self.keyfile]
45
+        cmd += ['-l', self.username, self.server,
46
+                'gerrit', 'stream-events']
47
+        self.proc = subprocess.Popen(cmd,
48
+                                     bufsize=1, 
49
+                                     stdin=None,
50
+                                     stdout=subprocess.PIPE,
51
+                                     stderr=None,
52
+                                     )
53
+        self.poll.register(self.proc.stdout)
54
+
55
+    def _close(self):
56
+        self.log.debug("Closing ssh connection")
57
+        try:
58
+            self.poll.unregister(self.proc.stdout)
59
+        except:
60
+            pass
61
+        try:
62
+            self.proc.kill()
63
+        except:
64
+            pass
65
+        self.proc = None
66
+
67
+    def _read(self):
68
+        l = self.proc.stdout.readline()
69
+        data = json.loads(l)
70
+        self.log.debug("Received data from Gerrit event stream: \n%s" % pprint.pformat(data))
71
+        self.gerrit.addEvent(data)
72
+
73
+    def _listen(self):
74
+        while True:
75
+            ret = self.poll.poll()
76
+            for (fd, event) in ret:
77
+                if fd == self.proc.stdout.fileno():
78
+                    if event == select.POLLIN:
79
+                        self._read()
80
+                    else:
81
+                        raise Exception("event on ssh connection")
82
+        
83
+    def _run(self):
84
+        try:
85
+            if not self.proc:
86
+                self._open()
87
+            self._listen()
88
+        except:
89
+            self.log.exception("Exception on ssh event stream:")
90
+            self._close()
91
+            time.sleep(5)
92
+
93
+    def run(self):
94
+        while True:
95
+            self._run()
96
+
97
+class Gerrit(object):
98
+    log = logging.getLogger("gerrit.Gerrit")
99
+
100
+    def __init__(self, hostname, username, keyfile=None):
101
+        self.username = username
102
+        self.hostname = hostname
103
+        self.keyfile = keyfile
104
+        self.watcher_thread = None
105
+        self.event_queue = None
106
+
107
+    def startWatching(self):
108
+        self.event_queue = Queue.Queue()
109
+        self.watcher_thread = GerritWatcher(
110
+            self,
111
+            self.username,
112
+            self.hostname,
113
+            keyfile=self.keyfile)
114
+        self.watcher_thread.start()
115
+
116
+    def addEvent(self, data):
117
+        return self.event_queue.put(data)
118
+
119
+    def getEvent(self):
120
+        return self.event_queue.get()
121
+
122
+    def review(self, project, change, message, action={}):
123
+        cmd = 'gerrit review --project %s --message "%s"' % (
124
+            project, message)
125
+        for k,v in action.items():
126
+            if v == True:
127
+                cmd += ' --%s' % k
128
+            else:
129
+                cmd += ' --%s %s' % (k, v)
130
+        cmd += ' %s' % change
131
+        out, err = self._ssh(cmd)
132
+        return err
133
+
134
+    def query(self, change):
135
+        cmd = 'gerrit query --format json %s"' % (
136
+            change)
137
+        out, err = self._ssh(cmd)
138
+        if not out:
139
+            return False
140
+        lines = out.split('\n')
141
+        if not lines:
142
+            return False
143
+        data = json.loads(lines[0])
144
+        if not data:
145
+            return False
146
+        self.log.debug("Received data from Gerrit query: \n%s" % (
147
+                pprint.pformat(data)))
148
+        return data
149
+
150
+    def _ssh(self, command):
151
+        client = paramiko.SSHClient()
152
+        client.load_system_host_keys()
153
+        client.set_missing_host_key_policy(paramiko.WarningPolicy())
154
+        client.connect(self.hostname, 
155
+                       username=self.username,
156
+                       port=29418)
157
+
158
+        self.log.debug("SSH command:\n%s" % command)
159
+        stdin, stdout, stderr = client.exec_command(command)
160
+
161
+        out = stdout.read()
162
+        self.log.debug("SSH received stdout:\n%s" % out)
163
+
164
+        ret = stdout.channel.recv_exit_status()
165
+        self.log.debug("SSH exit status: %s" % ret)
166
+
167
+        err = stderr.read()
168
+        self.log.debug("SSH received stderr:\n%s" % err)
169
+        if ret:
170
+            raise Exception("Gerrit error executing %s" % command)
171
+        return (out, err)

+ 323
- 0
zuul/model.py View File

@@ -0,0 +1,323 @@
1
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+import re
16
+
17
+class ChangeQueue(object):
18
+    def __init__(self, queue_name):
19
+        self.name = ''
20
+        self.queue_name = queue_name
21
+        self.projects = []
22
+        self._jobs = set()
23
+        self.queue = []
24
+
25
+    def __str__(self):
26
+        return '<ChangeQueue %s: %s>' % (self.queue_name, self.name)
27
+
28
+    def getJobs(self):
29
+        return self._jobs
30
+
31
+    def addProject(self, project):
32
+        if project not in self.projects:
33
+            self.projects.append(project)
34
+            names = [x.name for x in self.projects]
35
+            names.sort()
36
+            self.name = ', '.join(names)
37
+            self._jobs |= set(project.getJobs(self.queue_name))
38
+
39
+    def enqueueChange(self, change):
40
+        if self.queue:
41
+            self.queue[-1].change_behind = change
42
+            change.change_ahead = self.queue[-1]
43
+        self.queue.append(change)
44
+        change.queue = self
45
+
46
+    def dequeueChange(self, change):
47
+        if change in self.queue:
48
+            self.queue.remove(change)
49
+
50
+    def mergeChangeQueue(self, other):
51
+        for project in other.projects:
52
+            self.addProject(project)
53
+
54
+class Job(object):
55
+    def __init__(self, name):
56
+        self.name = name
57
+        self.failure_message = None
58
+        self.success_message = None
59
+        self.event_filters = []
60
+
61
+    def __str__(self):
62
+        return self.name
63
+
64
+    def __repr__(self):
65
+        return '<Job %s>' % (self.name)
66
+
67
+class Build(object):
68
+    def __init__(self, job, uuid):
69
+        self.job = job
70
+        self.uuid = uuid
71
+        self.status = None
72
+        self.url = None
73
+        self.number = None
74
+
75
+    def __repr__(self):
76
+        return '<Build %s of %s>' % (self.uuid, self.job.name)
77
+
78
+class JobTree(object):
79
+    """ A JobTree represents an instance of one Job, and holds JobTrees
80
+    whose jobs should be run if that Job succeeds.  A root node of a
81
+    JobTree will have no associated Job. """
82
+
83
+    def __init__(self, job):
84
+        self.job = job
85
+        self.job_trees = []
86
+
87
+    def addJob(self, job):
88
+        if job not in [x.job for x in self.job_trees]:
89
+            t = JobTree(job)
90
+            self.job_trees.append(t)
91
+            return t
92
+
93
+    def getJobs(self):
94
+        jobs = []
95
+        for x in self.job_trees:
96
+            jobs.append(x.job)
97
+            jobs.extend(x.getJobs())
98
+        return jobs
99
+
100
+    def getJobTreeForJob(self, job):
101
+        if self.job == job:
102
+            return self
103
+        for tree in self.job_trees:
104
+            ret = tree.getJobTreeForJob(job)
105
+            if ret:
106
+                return ret
107
+        return None
108
+
109
+class Project(object):
110
+    def __init__(self, name):
111
+        self.name = name
112
+        self.job_trees = {}  # Queue -> JobTree
113
+
114
+    def __str__(self):
115
+        return self.name
116
+
117
+    def __repr__(self):
118
+        return '<Project %s>' % (self.name)
119
+
120
+    def addQueue(self, name):
121
+        self.job_trees[name] = JobTree(None)
122
+        return self.job_trees[name]
123
+
124
+    def hasQueue(self, name):
125
+        if self.job_trees.has_key(name):
126
+            return True
127
+        return False
128
+
129
+    def getJobTreeForQueue(self, name):
130
+        return self.job_trees.get(name, None)
131
+
132
+    def getJobs(self, queue_name):
133
+        tree = self.getJobTreeForQueue(queue_name)
134
+        if not tree:
135
+            return []
136
+        return tree.getJobs()
137
+
138
+class Change(object):
139
+    def __init__(self, queue_name, project, number, patchset):
140
+        self.queue_name = queue_name
141
+        self.project = project
142
+        self.number = number
143
+        self.patchset = patchset
144
+        self.jobs = {}
145
+        self.job_urls = {}
146
+        self.change_ahead = None
147
+        self.change_behind = None
148
+        self.running_builds = []
149
+
150
+    def __str__(self):
151
+        return '<Change 0x%x %s,%s>' % (id(self), self.number, self.patchset)
152
+
153
+    def formatStatus(self, indent=0):
154
+        indent_str = ' '*indent
155
+        ret = ''
156
+        ret += '%sProject %s change %s,%s\n' % (indent_str,
157
+                                              self.project.name,
158
+                                              self.number, 
159
+                                              self.patchset)
160
+        for job in self.project.getJobs(self.queue_name):
161
+            result = self.jobs.get(job.name)
162
+            ret += '%s  %s: %s\n' % (indent_str, job.name, result)
163
+        if self.change_ahead:
164
+            ret += '%sWaiting on:\n' % (indent_str)
165
+            ret += self.change_ahead.formatStatus(indent+2)
166
+        return ret
167
+
168
+    def formatReport(self):
169
+        ret = ''
170
+        if self.didAllJobsSucceed():
171
+            ret += 'Build successful\n\n'
172
+        else:
173
+            ret += 'Build failed\n\n'
174
+        
175
+        for job in self.project.getJobs(self.queue_name):
176
+            result = self.jobs.get(job.name)
177
+            url = self.job_urls.get(job.name, job.name)
178
+            ret += '- %s : %s\n' % (url, result)
179
+        return ret
180
+
181
+    def resetAllBuilds(self):
182
+        self.jobs = {}
183
+        self.job_urls = {}
184
+        self.running_builds = []
185
+
186
+    def addBuild(self, build):
187
+        self.running_builds.append(build)
188
+
189
+    def setResult(self, build):
190
+        self.running_builds.remove(build)
191
+        self.jobs[build.job.name] = build.result
192
+        self.job_urls[build.job.name] = build.url
193
+        if build.result != 'SUCCESS':
194
+            # Get a JobTree from a Job so we can find only its dependent jobs
195
+            root = self.project.getJobTreeForQueue(self.queue_name)
196
+            tree = root.getJobTreeForJob(build.job)
197
+            for job in tree.getJobs():
198
+                self.jobs[job.name] = 'SKIPPED'
199
+
200
+    def _findJobsToRun(self, job_trees):
201
+        torun = []
202
+        for tree in job_trees:
203
+            job = tree.job
204
+            if job:
205
+                result = self.jobs.get(job.name, None)
206
+            else:
207
+                # This is a null job tree, run all of its jobs
208
+                result = 'SUCCESS'
209
+            if not result:
210
+                if job not in [b.job for b in self.running_builds]:
211
+                    torun.append(job)
212
+            elif result == 'SUCCESS':
213
+                torun.extend(self._findJobsToRun(tree.job_trees))
214
+        return torun
215
+
216
+    def findJobsToRun(self):
217
+        tree = self.project.getJobTreeForQueue(self.queue_name)
218
+        return self._findJobsToRun(tree.job_trees)
219
+
220
+    def areAllJobsComplete(self):
221
+        tree = self.project.getJobTreeForQueue(self.queue_name)
222
+        for job in tree.getJobs():
223
+            if not self.jobs.has_key(job.name):
224
+                return False
225
+        return True
226
+
227
+    def didAllJobsSucceed(self):
228
+        for result in self.jobs.values():
229
+            if result != 'SUCCESS':
230
+                return False
231
+        return True
232
+
233
+    def delete(self):
234
+        if self.change_behind:
235
+            self.change_behind.change_ahead = None
236
+
237
+class TriggerEvent(object):
238
+    def __init__(self):
239
+        self.data = None
240
+        self.type = None
241
+        self.project_name = None
242
+        self.change_number = None
243
+        self.patch_number = None
244
+        self.approvals = []
245
+        self.branch = None
246
+        self.ref = None
247
+
248
+    def __str__(self):
249
+        ret = '<TriggerEvent %s %s' % (self.type, self.project_name)
250
+        
251
+        if self.branch:
252
+            ret += " %s" % self.branch
253
+        if self.change_number:
254
+            ret += " %s,%s" % (self.change_number, self.patch_number)
255
+        if self.approvals:
256
+            ret += ' '+', '.join(['%s:%s' % (a['type'], a['value']) for a in self.approvals])
257
+        ret += '>'
258
+
259
+        return ret
260
+
261
+class EventFilter(object):
262
+    def __init__(self, types=[], branches=[], refs=[], approvals=[]):
263
+        self._types = types
264
+        self._branches = branches
265
+        self._refs = refs
266
+        self.types = [re.compile(x) for x in types]
267
+        self.branches = [re.compile(x) for x in branches]
268
+        self.refs = [re.compile(x) for x in refs]
269
+        self.approvals = approvals
270
+
271
+    def __str__(self):
272
+        ret = '<EventFilter'
273
+        
274
+        if self._types:
275
+            ret += ' types: %s' % ', '.join(self._types)
276
+        if self._branches:
277
+            ret += ' branches: %s' % ', '.join(self._branches)
278
+        if self._refs:
279
+            ret += ' refs: %s' % ', '.join(self._refs)
280
+        if self.approvals:
281
+            ret += ' approvals: %s' % ', '.join(['%s:%s' % a for a in self.approvals.items()])
282
+        ret += '>'
283
+
284
+        return ret
285
+
286
+    def matches(self, event):
287
+        def normalizeCategory(name):
288
+            name = name.lower()
289
+            return re.sub(' ', '-', name)
290
+
291
+        # event types are ORed
292
+        matches_type = False
293
+        for etype in self.types:
294
+            if etype.match(event.type):
295
+                matches_type = True
296
+        if self.types and not matches_type:
297
+            return False
298
+
299
+        # branches are ORed
300
+        matches_branch = False
301
+        for branch in self.branches:
302
+            if branch.match(event.branch):
303
+                matches_branch = True
304
+        if self.branches and not matches_branch:
305
+            return False
306
+
307
+        # refs are ORed
308
+        matches_ref = False
309
+        for ref in self.refs:
310
+            if ref.match(event.ref):
311
+                matches_ref = True
312
+        if self.refs and not matches_ref:
313
+            return False
314
+
315
+        # approvals are ANDed
316
+        for category, value in self.approvals.items():
317
+            matches_approval = False
318
+            for eapproval in event.approvals:
319
+                if (normalizeCategory(eapproval['description']) == category and
320
+                    int(eapproval['value']) == int(value)):
321
+                    matches_approval = True
322
+            if not matches_approval: return False
323
+        return True

+ 436
- 0
zuul/scheduler.py View File

@@ -0,0 +1,436 @@
1
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+import os
16
+import Queue
17
+import threading
18
+import logging
19
+import yaml
20
+
21
+
22
+from model import Job, Change, Project, ChangeQueue, EventFilter
23
+
24
+class Scheduler(object):
25
+    log = logging.getLogger("zuul.Scheduler")
26
+
27
+    def __init__(self, config):
28
+        self.wake_event = threading.Event()
29
+        self.queue_managers = {}
30
+        self.jobs = {}
31
+        self.projects = {}
32
+        self.launcher = None
33
+        self.trigger = None
34
+
35
+        self.trigger_event_queue = Queue.Queue()
36
+        self.result_event_queue = Queue.Queue()
37
+
38
+        self._parseConfig(config.get('zuul', 'layout_config'))
39
+
40
+    def _parseConfig(self, fp):
41
+        def toList(item):
42
+            if not item: return []
43
+            if type(item) == type([]):
44
+                return item
45
+            return [item]
46
+
47
+        if fp:
48
+            fp = os.path.expanduser(fp)
49
+            if not os.path.exists(fp):
50
+                raise Exception("Unable to read layout config file at %s" % fp)
51
+        fp = open(fp)
52
+        data = yaml.load(fp)
53
+        import pprint
54
+        pprint.pprint(data)
55
+        
56
+        for config_queue in data['queue']:
57
+            manager = globals()[config_queue['manager']](self, config_queue['name'])
58
+            self.queue_managers[config_queue['name']] = manager
59
+            manager.success_action = config_queue.get('success')
60
+            manager.failure_action = config_queue.get('failure')
61
+            for trigger in toList(config_queue['trigger']):
62
+                approvals = {}
63
+                for approval_dict in toList(trigger.get('approval')):
64
+                    for k, v in approval_dict.items():
65
+                        approvals[k]=v
66
+                f = EventFilter(types=toList(trigger['event']),
67
+                                branches=toList(trigger.get('branch')),
68
+                                refs=toList(trigger.get('ref')),
69
+                                approvals=approvals)
70
+                manager.event_filters.append(f)
71
+
72
+        for config_job in data['jobs']:
73
+            job = self.getJob(config_job['name'])
74
+            job.failure_message = config_job.get('failure-message', None)
75
+            job.success_message = config_job.get('success-message', None)
76
+            silent = config_job.get('silent', None)
77
+            if silent:
78
+                job.silent = True
79
+            branches = toList(config_job.get('branch'))
80
+            if branches:
81
+                f = EventFilter(branches=branches)
82
+                job.event_filters.append(f)
83
+
84
+        def add_jobs(job_tree, config_jobs):
85
+            for job in config_jobs:
86
+                if isinstance(job, list):
87
+                    for x in job:
88
+                        add_jobs(job_tree, x)
89
+                if isinstance(job, dict):
90
+                    for parent, children in job.items():
91
+                        parent_tree = job_tree.addJob(self.getJob(parent))
92
+                        add_jobs(parent_tree, children)
93
+                if isinstance(job, str):
94
+                    job_tree.addJob(self.getJob(job))
95
+
96
+        for config_project in data['projects']:
97
+            project = Project(config_project['name'])
98
+            self.projects[config_project['name']] = project
99
+            for qname in self.queue_managers.keys():
100
+                if config_project.has_key(qname):
101
+                    print project, qname
102
+                    job_tree = project.addQueue(qname)
103
+                    config_jobs = config_project[qname]
104
+                    add_jobs(job_tree, config_jobs)
105
+            
106
+
107
+        # TODO(jeblair): check that we don't end up with jobs like
108
+        # "foo - bar" because a ':' is missing in the yaml for a dependent job
109
+        for manager in self.queue_managers.values():
110
+            manager._postConfig()
111
+
112
+    def getJob(self, name):
113
+        if self.jobs.has_key(name):
114
+            return self.jobs[name]
115
+        job = Job(name)
116
+        self.jobs[name] = job
117
+        return job
118
+
119
+    def setLauncher(self, launcher):
120
+        self.launcher = launcher
121
+
122
+    def setTrigger(self, trigger):
123
+        self.trigger = trigger
124
+
125
+    def addEvent(self, event):
126
+        self.log.debug("Adding trigger event: %s" % event)
127
+        self.trigger_event_queue.put(event)
128
+        self.wake_event.set()
129
+
130
+    def onBuildCompleted(self, build):
131
+        self.log.debug("Adding result event for build: %s" % build)
132
+        self.result_event_queue.put(build)
133
+        self.wake_event.set()
134
+
135
+    def run(self):
136
+        while True:
137
+            self.log.debug("Run handler sleeping")
138
+            self.wake_event.wait()
139
+            self.wake_event.clear()
140
+            self.log.debug("Run handler awake")
141
+            try:
142
+                if not self.trigger_event_queue.empty():
143
+                    self.process_event_queue()
144
+                if not self.result_event_queue.empty():
145
+                    self.process_result_queue()
146
+            except:
147
+                self.log.exception("Exception in run handler:")
148
+
149
+    def process_event_queue(self):
150
+        self.log.debug("Fetching trigger event")
151
+        event = self.trigger_event_queue.get()
152
+        self.log.debug("Processing trigger event %s" % event)
153
+        project = self.projects.get(event.project_name)
154
+        if not project:
155
+            self.log.warning("Project %s not found" % event.project_name)
156
+            return
157
+
158
+        for manager in self.queue_managers.values():
159
+            if not manager.eventMatches(event):
160
+                self.log.debug("Event %s ignored by %s" % (event, manager))
161
+                continue
162
+            if event.change_number:
163
+                change = Change(manager.name, project,
164
+                                event.change_number, event.patch_number)
165
+                self.log.info("Adding %s, %s to to %s" % (
166
+                        project, change, manager))
167
+                manager.addChange(change)
168
+            
169
+    def process_result_queue(self):
170
+        self.log.debug("Fetching result event")
171
+        build = self.result_event_queue.get()
172
+        self.log.debug("Processing result event %s" % build)
173
+        for manager in self.queue_managers.values():
174
+            if manager.onBuildCompleted(build):
175
+                return
176
+
177
+class BaseQueueManager(object):
178
+    log = logging.getLogger("zuul.BaseQueueManager")
179
+
180
+    def __init__(self, sched, name):
181
+        self.sched = sched
182
+        self.name = name
183
+        self.building_jobs = {}
184
+        self.event_filters = []
185
+        self.success_action = {}
186
+        self.failure_action = {}
187
+
188
+    def __str__(self):
189
+        return "<%s %s>" % (self.__class__.__name__, self.name)
190
+
191
+    def _postConfig(self):
192
+        self.log.info("Configured Queue Manager %s" % self.name)
193
+        self.log.info("  Events:")
194
+        for e in self.event_filters:
195
+            self.log.info("    %s" % e)
196
+        self.log.info("  Projects:")
197
+        def log_jobs(tree, indent=0):
198
+            istr = '    '+' '*indent
199
+            if tree.job:
200
+                efilters = ''
201
+                for e in tree.job.event_filters:
202
+                    efilters += str(e)
203
+                if efilters:
204
+                    efilters = ' '+efilters
205
+                self.log.info("%s%s%s" % (istr, repr(tree.job), efilters))
206
+            for x in tree.job_trees:
207
+                log_jobs(x, indent+2)
208
+        for p in self.sched.projects.values():
209
+            if p.hasQueue(self.name):
210
+                self.log.info("    %s" % p)
211
+                log_jobs(p.getJobTreeForQueue(self.name))
212
+        if self.success_action:
213
+            self.log.info("  On success:")
214
+            self.log.info("    %s" % self.success_action)
215
+        if self.failure_action:
216
+            self.log.info("  On failure:")
217
+            self.log.info("    %s" % self.failure_action)
218
+
219
+
220
+    def eventMatches(self, event):
221
+        for ef in self.event_filters:
222
+            print ef
223
+            if ef.matches(event):
224
+                return True
225
+        return False
226
+
227
+
228
+    def addChange(self, change):
229
+        self.log.debug("Adding change %s" % change)
230
+        self.launchJobs(change)
231
+
232
+    def launchJobs(self, change):
233
+        self.log.debug("Launching jobs for change %s" % change)
234
+        for job in change.findJobsToRun():
235
+            self.log.debug("Found job %s for change %s" % (job, change))
236
+            try:
237
+                build = self.sched.launcher.launch(job, change)
238
+                self.building_jobs[build] = change
239
+                self.log.debug("Adding build %s of job %s to change %s" % (
240
+                        build, job, change))
241
+                change.addBuild(build)
242
+            except:
243
+                self.log.exception("Exception while launching job %s for change %s:" % (
244
+                        job, change))
245
+
246
+    def onBuildCompleted(self, build):
247
+        self.log.debug("Build %s completed" % build)
248
+        if not self.building_jobs.has_key(build):
249
+            self.log.warning("Build %s not found (may have been canceled)" % (
250
+                    build))
251
+            # Or triggered externally, or triggered before zuul started,
252
+            # or restarted
253
+            return False
254
+        change = self.building_jobs[build]
255
+        self.log.debug("Found change %s which triggered completed build %s" % (
256
+                change, build))
257
+
258
+        del self.building_jobs[build]
259
+
260
+        change.setResult(build)
261
+        self.log.info("Change %s status is now:\n %s" % (
262
+                change, change.formatStatus()))
263
+
264
+        if change.areAllJobsComplete():
265
+            self.log.debug("All jobs for change %s are complete" % change)
266
+            self.possiblyReportChange(change)
267
+        else:
268
+            # There may be jobs that depended on jobs that are now complete
269
+            self.log.debug("All jobs for change %s are not yet complete" % (
270
+                    change))
271
+            self.launchJobs(change)
272
+        return True
273
+
274
+    def possiblyReportChange(self, change):
275
+        self.log.debug("Possibly reporting change %s" % change)
276
+        self.reportChange(change)
277
+
278
+    def reportChange(self, change):
279
+        self.log.debug("Reporting change %s" % change)
280
+        ret = None
281
+        if change.didAllJobsSucceed():
282
+            action = self.success_action
283
+        else:
284
+            action = self.failure_action
285
+        try:
286
+            self.log.info("Reporting change %s, action: %s" % (
287
+                    change, action))
288
+            ret = self.sched.trigger.report(change, change.formatReport(),
289
+                                            action)
290
+            if ret:
291
+                self.log.error("Reporting change %s received: %s" % (
292
+                        change, ret))
293
+                print ret
294
+        except:
295
+            self.log.exception("Exception while reporting:")
296
+        return ret
297
+
298
+class IndependentQueueManager(BaseQueueManager):
299
+    log = logging.getLogger("zuul.IndependentQueueManager")
300
+    pass
301
+
302
+class DependentQueueManager(BaseQueueManager):
303
+    log = logging.getLogger("zuul.DependentQueueManager")
304
+
305
+    def __init__(self, *args, **kwargs):
306
+        super(DependentQueueManager, self).__init__(*args, **kwargs)
307
+        self.change_queues = []
308
+
309
+    def _postConfig(self):
310
+        super(DependentQueueManager, self)._postConfig()
311
+        self.buildChangeQueues()
312
+
313
+    def buildChangeQueues(self):
314
+        self.log.debug("Building shared change queues")
315
+        change_queues = []
316
+
317
+        for project in self.sched.projects.values():
318
+            if project.hasQueue(self.name):
319
+                change_queue = ChangeQueue(self.name)
320
+                change_queue.addProject(project)
321
+                change_queues.append(change_queue)
322
+                self.log.debug("Created queue: %s" % change_queue)
323
+
324
+        self.log.debug("Combining shared queues")
325
+        new_change_queues = []
326
+        for a in change_queues:
327
+            merged_a = False
328
+            for b in new_change_queues:
329
+                if not a.getJobs().isdisjoint(b.getJobs()):
330
+                    self.log.debug("Merging queue %s into %s" % (a, b))
331
+                    b.mergeChangeQueue(a)
332
+                    merged_a = True
333
+                    break  # this breaks out of 'for b' and continues 'for a'
334
+            if not merged_a:
335
+                self.log.debug("Keeping queue %s" % (a))
336
+                new_change_queues.append(a)
337
+        
338
+        self.change_queues = new_change_queues
339
+        self.log.info("  Shared change queues:")
340
+        for x in self.change_queues:
341
+            self.log.info("    %s" % x)
342
+
343
+    def getQueue(self, project):
344
+        for queue in self.change_queues:
345
+            if project in queue.projects:
346
+                return queue
347
+        self.log.error("Unable to find change queue for project %s" % project)
348
+            
349
+    def addChange(self, change):
350
+        self.log.debug("Adding change %s" % change)
351
+        change_queue = self.getQueue(change.project)
352
+        self.log.debug("Adding change %s to queue %s" % (change, change_queue))
353
+        change_queue.enqueueChange(change)
354
+        super(DependentQueueManager, self).addChange(change)
355
+
356
+    def _getDependentChanges(self, change):
357
+        changes = []
358
+        while change.change_ahead:
359
+            changes.append(change.change_ahead)
360
+            change = change.change_ahead
361
+        self.log.info("Change %s depends on changes %s" % (change, changes))
362
+        return changes
363
+
364
+    def launchJobs(self, change):
365
+        self.log.debug("Launching jobs for change %s" % change)
366
+        dependent_changes = self._getDependentChanges(change)
367
+        for job in change.findJobsToRun():
368
+            self.log.debug("Found job %s for change %s" % (job, change))
369
+            try:
370
+                build = self.sched.launcher.launch(job, change, 
371
+                                                   dependent_changes)
372
+                self.building_jobs[build] = change
373
+                self.log.debug("Adding build %s of job %s to change %s" % (
374
+                        build, job, change))
375
+                change.addBuild(build)
376
+            except:
377
+                self.log.exception("Exception while launching job %s for change %s:" % (
378
+                        job, change))
379
+        if change.change_behind:
380
+            self.log.debug("Launching jobs for change %s, behind change %s" % (
381
+                    change.change_behind, change))
382
+            self.launchJobs(change.change_behind)
383
+
384
+    def cancelJobs(self, change):
385
+        self.log.debug("Cancel jobs for change %s" % change)
386
+        to_remove = []
387
+        change.resetAllBuilds()
388
+        for build, build_change in self.building_jobs.items():
389
+            if build_change == change:
390
+                self.log.debug("Found build %s for change %s to cancel" % (
391
+                        build, change))
392
+                try:
393
+                    self.sched.launcher.cancel(build)
394
+                except:
395
+                    self.log.exception("Exception while canceling build %s for change %s" % (
396
+                            build, change))
397
+                to_remove.append(build)
398
+        for build in to_remove:
399
+            self.log.debug("Removing build %s from running builds" % build)
400
+            del self.building_jobs[build]
401
+        if change.change_behind:
402
+            self.log.debug("Canceling jobs for change %s, behind change %s" % (
403
+                    change.change_behind, change))
404
+            self.cancelJobs(change.change_behind)
405
+
406
+    def possiblyReportChange(self, change):
407
+        self.log.debug("Possibly reporting change %s" % change)
408
+        if not change.change_ahead:
409
+            self.log.debug("Change %s is at the front of the queue, reporting" % (
410
+                    change))
411
+            ret = self.reportChange(change)
412
+            self.log.debug("Removing reported change %s from queue" % change)
413
+            change.delete()
414
+            change.queue.dequeueChange(change)
415
+            merged = (not ret)
416
+            if merged:
417
+                merged = self.sched.trigger.isMerged(change)
418
+            succeeded = change.didAllJobsSucceed()
419
+            self.log.info("Reported change %s status: all-succeeded: %s, merged: %s" % (
420
+                    change, succeeded, merged))
421
+                    
422
+            if not (succeeded and merged):
423
+                self.log.debug("Reported change %s failed tests or failed to merge" % (
424
+                        change))
425
+                # The merge or test failed, re-run all jobs behind this one
426
+                if change.change_behind:
427
+                    self.log.info("Canceling/relaunching jobs for change %s behind failed change %s" % (
428
+                            change.change_behind, change))
429
+                    self.cancelJobs(change.change_behind)
430
+                    self.launchJobs(change.change_behind)
431
+        # If the change behind this is ready, notify
432
+        if (change.change_behind and 
433
+            change.change_behind.areAllJobsComplete()):
434
+            self.log.info("Change %s behind change %s is ready, possibly reporting" % (
435
+                    change.change_behind, change))
436
+            self.possiblyReportChange(change.change_behind)

+ 0
- 0
zuul/trigger/__init__.py View File


+ 92
- 0
zuul/trigger/gerrit.py View File

@@ -0,0 +1,92 @@
1
+# Copyright 2012 Hewlett-Packard Development Company, L.P.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+# not use this file except in compliance with the License. You may obtain
5
+# a copy of the License at
6
+#
7
+#      http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+# License for the specific language governing permissions and limitations
13
+# under the License.
14
+
15
+import threading
16
+import logging
17
+from zuul.lib import gerrit
18
+from zuul.model import TriggerEvent
19
+
20
+class GerritEventConnector(threading.Thread):
21
+    """Move events from Gerrit to the scheduler."""
22
+
23
+    log = logging.getLogger("zuul.GerritEventConnector")
24
+
25
+    def __init__(self, gerrit, sched):
26
+        super(GerritEventConnector, self).__init__()
27
+        self.gerrit = gerrit
28
+        self.sched = sched
29
+
30
+
31
+    def _handleEvent(self):
32
+        data = self.gerrit.getEvent()
33
+        event = TriggerEvent()
34
+        event.type = data.get('type')
35
+        change = data.get('change')
36
+        if change:
37
+            event.project_name = change.get('project')
38
+            event.branch = change.get('branch')
39
+            event.change_number = change.get('number')
40
+            patchset = data.get('patchSet')
41
+            if patchset:
42
+                event.patch_number = patchset.get('number')
43
+            event.approvals = data.get('approvals')
44
+        self.sched.addEvent(event)
45
+
46
+
47
+    def run(self):
48
+        while True:
49
+            try:
50
+                self._handleEvent()
51
+            except:
52
+                self.log.exception("Exception moving Gerrit event:")
53
+
54
+
55
+class Gerrit(object):
56
+    log = logging.getLogger("zuul.Gerrit")
57
+
58
+    def __init__(self, config, sched):
59
+        self.sched = sched
60
+        server = config.get('gerrit', 'server')
61
+        user = config.get('gerrit', 'user')
62
+        if config.has_option('gerrit', 'sshkey'):
63
+            sshkey = config.get('gerrit', 'sshkey')
64
+        else:
65
+            sshkey = None
66
+        self.gerrit = gerrit.Gerrit(server, user, sshkey)
67
+        self.gerrit.startWatching()
68
+        self.gerrit_connector = GerritEventConnector(
69
+            self.gerrit, sched)
70
+        self.gerrit_connector.start()
71
+
72
+        
73
+    def report(self, change, message, action):
74
+        self.log.debug("Report change %s, action %s, message: %s" %
75
+                       (change, action, message))
76
+        changeid = '%s,%s' % (change.number, change.patchset)
77
+        return self.gerrit.review(change.project.name, changeid,
78
+                                  message, action)
79
+
80
+
81
+    def isMerged(self, change):
82
+        self.log.debug("Checking if change %s is merged", change)
83
+        data = self.gerrit.query(change.number)
84
+        if not data:
85
+            return False
86
+        status = data.get('status')
87
+        if not status:
88
+            return False
89
+        self.log.debug("Change %s status: %s" % (change, status))
90
+        if status == 'MERGED' or status == 'SUBMITTED':
91
+            return True
92
+

Loading…
Cancel
Save