blob: 5e1befe37dd4f916b64a77a5e0ff63e3da18867b [file] [log] [blame]
Clark Boylanb640e052014-04-03 16:41:46 -07001#!/usr/bin/env python
2
3# Copyright 2012 Hewlett-Packard Development Company, L.P.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
Christian Berendtffba5df2014-06-07 21:30:22 +020017from six.moves import configparser as ConfigParser
Clark Boylanb640e052014-04-03 16:41:46 -070018import gc
19import hashlib
20import json
21import logging
22import os
23import pprint
Christian Berendt12d4d722014-06-07 21:03:45 +020024from six.moves import queue as Queue
Clark Boylanb640e052014-04-03 16:41:46 -070025import random
26import re
27import select
28import shutil
29import socket
30import string
31import subprocess
32import swiftclient
James E. Blairf84026c2015-12-08 16:11:46 -080033import tempfile
Clark Boylanb640e052014-04-03 16:41:46 -070034import threading
35import time
36import urllib2
37
38import git
39import gear
40import fixtures
41import six.moves.urllib.parse as urlparse
42import statsd
43import testtools
Mike Heald8225f522014-11-21 09:52:33 +000044from git import GitCommandError
Clark Boylanb640e052014-04-03 16:41:46 -070045
Joshua Hesketh352264b2015-08-11 23:42:08 +100046import zuul.connection.gerrit
47import zuul.connection.smtp
Clark Boylanb640e052014-04-03 16:41:46 -070048import zuul.scheduler
49import zuul.webapp
50import zuul.rpclistener
51import zuul.launcher.gearman
52import zuul.lib.swift
Clark Boylanb640e052014-04-03 16:41:46 -070053import zuul.merger.client
James E. Blair879dafb2015-07-17 14:04:49 -070054import zuul.merger.merger
55import zuul.merger.server
Clark Boylanb640e052014-04-03 16:41:46 -070056import zuul.reporter.gerrit
57import zuul.reporter.smtp
Joshua Hesketh850ccb62014-11-27 11:31:02 +110058import zuul.source.gerrit
Clark Boylanb640e052014-04-03 16:41:46 -070059import zuul.trigger.gerrit
60import zuul.trigger.timer
James E. Blairc494d542014-08-06 09:23:52 -070061import zuul.trigger.zuultrigger
Clark Boylanb640e052014-04-03 16:41:46 -070062
63FIXTURE_DIR = os.path.join(os.path.dirname(__file__),
64 'fixtures')
James E. Blair97d902e2014-08-21 13:25:56 -070065USE_TEMPDIR = True
Clark Boylanb640e052014-04-03 16:41:46 -070066
67logging.basicConfig(level=logging.DEBUG,
68 format='%(asctime)s %(name)-32s '
69 '%(levelname)-8s %(message)s')
70
71
72def repack_repo(path):
73 cmd = ['git', '--git-dir=%s/.git' % path, 'repack', '-afd']
74 output = subprocess.Popen(cmd, close_fds=True,
75 stdout=subprocess.PIPE,
76 stderr=subprocess.PIPE)
77 out = output.communicate()
78 if output.returncode:
79 raise Exception("git repack returned %d" % output.returncode)
80 return out
81
82
83def random_sha1():
84 return hashlib.sha1(str(random.random())).hexdigest()
85
86
James E. Blaira190f3b2015-01-05 14:56:54 -080087def iterate_timeout(max_seconds, purpose):
88 start = time.time()
89 count = 0
90 while (time.time() < start + max_seconds):
91 count += 1
92 yield count
93 time.sleep(0)
94 raise Exception("Timeout waiting for %s" % purpose)
95
96
Clark Boylanb640e052014-04-03 16:41:46 -070097class ChangeReference(git.Reference):
98 _common_path_default = "refs/changes"
99 _points_to_commits_only = True
100
101
102class FakeChange(object):
103 categories = {'APRV': ('Approved', -1, 1),
104 'CRVW': ('Code-Review', -2, 2),
105 'VRFY': ('Verified', -2, 2)}
106
107 def __init__(self, gerrit, number, project, branch, subject,
108 status='NEW', upstream_root=None):
109 self.gerrit = gerrit
110 self.reported = 0
111 self.queried = 0
112 self.patchsets = []
113 self.number = number
114 self.project = project
115 self.branch = branch
116 self.subject = subject
117 self.latest_patchset = 0
118 self.depends_on_change = None
119 self.needed_by_changes = []
120 self.fail_merge = False
121 self.messages = []
122 self.data = {
123 'branch': branch,
124 'comments': [],
125 'commitMessage': subject,
126 'createdOn': time.time(),
127 'id': 'I' + random_sha1(),
128 'lastUpdated': time.time(),
129 'number': str(number),
130 'open': status == 'NEW',
131 'owner': {'email': 'user@example.com',
132 'name': 'User Name',
133 'username': 'username'},
134 'patchSets': self.patchsets,
135 'project': project,
136 'status': status,
137 'subject': subject,
138 'submitRecords': [],
139 'url': 'https://hostname/%s' % number}
140
141 self.upstream_root = upstream_root
142 self.addPatchset()
143 self.data['submitRecords'] = self.getSubmitRecords()
144 self.open = status == 'NEW'
145
146 def add_fake_change_to_repo(self, msg, fn, large):
147 path = os.path.join(self.upstream_root, self.project)
148 repo = git.Repo(path)
149 ref = ChangeReference.create(repo, '1/%s/%s' % (self.number,
150 self.latest_patchset),
151 'refs/tags/init')
152 repo.head.reference = ref
James E. Blair879dafb2015-07-17 14:04:49 -0700153 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -0700154 repo.git.clean('-x', '-f', '-d')
155
156 path = os.path.join(self.upstream_root, self.project)
157 if not large:
158 fn = os.path.join(path, fn)
159 f = open(fn, 'w')
160 f.write("test %s %s %s\n" %
161 (self.branch, self.number, self.latest_patchset))
162 f.close()
163 repo.index.add([fn])
164 else:
165 for fni in range(100):
166 fn = os.path.join(path, str(fni))
167 f = open(fn, 'w')
168 for ci in range(4096):
169 f.write(random.choice(string.printable))
170 f.close()
171 repo.index.add([fn])
172
173 r = repo.index.commit(msg)
174 repo.head.reference = 'master'
James E. Blair879dafb2015-07-17 14:04:49 -0700175 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -0700176 repo.git.clean('-x', '-f', '-d')
177 repo.heads['master'].checkout()
178 return r
179
180 def addPatchset(self, files=[], large=False):
181 self.latest_patchset += 1
182 if files:
183 fn = files[0]
184 else:
James E. Blair97d902e2014-08-21 13:25:56 -0700185 fn = '%s-%s' % (self.branch.replace('/', '_'), self.number)
Clark Boylanb640e052014-04-03 16:41:46 -0700186 msg = self.subject + '-' + str(self.latest_patchset)
187 c = self.add_fake_change_to_repo(msg, fn, large)
188 ps_files = [{'file': '/COMMIT_MSG',
189 'type': 'ADDED'},
190 {'file': 'README',
191 'type': 'MODIFIED'}]
192 for f in files:
193 ps_files.append({'file': f, 'type': 'ADDED'})
194 d = {'approvals': [],
195 'createdOn': time.time(),
196 'files': ps_files,
197 'number': str(self.latest_patchset),
198 'ref': 'refs/changes/1/%s/%s' % (self.number,
199 self.latest_patchset),
200 'revision': c.hexsha,
201 'uploader': {'email': 'user@example.com',
202 'name': 'User name',
203 'username': 'user'}}
204 self.data['currentPatchSet'] = d
205 self.patchsets.append(d)
206 self.data['submitRecords'] = self.getSubmitRecords()
207
208 def getPatchsetCreatedEvent(self, patchset):
209 event = {"type": "patchset-created",
210 "change": {"project": self.project,
211 "branch": self.branch,
212 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
213 "number": str(self.number),
214 "subject": self.subject,
215 "owner": {"name": "User Name"},
216 "url": "https://hostname/3"},
217 "patchSet": self.patchsets[patchset - 1],
218 "uploader": {"name": "User Name"}}
219 return event
220
221 def getChangeRestoredEvent(self):
222 event = {"type": "change-restored",
223 "change": {"project": self.project,
224 "branch": self.branch,
225 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
226 "number": str(self.number),
227 "subject": self.subject,
228 "owner": {"name": "User Name"},
229 "url": "https://hostname/3"},
230 "restorer": {"name": "User Name"},
Antoine Mussobd86a312014-01-08 14:51:33 +0100231 "patchSet": self.patchsets[-1],
232 "reason": ""}
233 return event
234
235 def getChangeAbandonedEvent(self):
236 event = {"type": "change-abandoned",
237 "change": {"project": self.project,
238 "branch": self.branch,
239 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
240 "number": str(self.number),
241 "subject": self.subject,
242 "owner": {"name": "User Name"},
243 "url": "https://hostname/3"},
244 "abandoner": {"name": "User Name"},
245 "patchSet": self.patchsets[-1],
Clark Boylanb640e052014-04-03 16:41:46 -0700246 "reason": ""}
247 return event
248
249 def getChangeCommentEvent(self, patchset):
250 event = {"type": "comment-added",
251 "change": {"project": self.project,
252 "branch": self.branch,
253 "id": "I5459869c07352a31bfb1e7a8cac379cabfcb25af",
254 "number": str(self.number),
255 "subject": self.subject,
256 "owner": {"name": "User Name"},
257 "url": "https://hostname/3"},
258 "patchSet": self.patchsets[patchset - 1],
259 "author": {"name": "User Name"},
260 "approvals": [{"type": "Code-Review",
261 "description": "Code-Review",
262 "value": "0"}],
263 "comment": "This is a comment"}
264 return event
265
Joshua Hesketh642824b2014-07-01 17:54:59 +1000266 def addApproval(self, category, value, username='reviewer_john',
267 granted_on=None, message=''):
Clark Boylanb640e052014-04-03 16:41:46 -0700268 if not granted_on:
269 granted_on = time.time()
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000270 approval = {
271 'description': self.categories[category][0],
272 'type': category,
273 'value': str(value),
274 'by': {
275 'username': username,
276 'email': username + '@example.com',
277 },
278 'grantedOn': int(granted_on)
279 }
Clark Boylanb640e052014-04-03 16:41:46 -0700280 for i, x in enumerate(self.patchsets[-1]['approvals'][:]):
281 if x['by']['username'] == username and x['type'] == category:
282 del self.patchsets[-1]['approvals'][i]
283 self.patchsets[-1]['approvals'].append(approval)
284 event = {'approvals': [approval],
Joshua Hesketh642824b2014-07-01 17:54:59 +1000285 'author': {'email': 'author@example.com',
286 'name': 'Patchset Author',
287 'username': 'author_phil'},
Clark Boylanb640e052014-04-03 16:41:46 -0700288 'change': {'branch': self.branch,
289 'id': 'Iaa69c46accf97d0598111724a38250ae76a22c87',
290 'number': str(self.number),
Joshua Hesketh642824b2014-07-01 17:54:59 +1000291 'owner': {'email': 'owner@example.com',
292 'name': 'Change Owner',
293 'username': 'owner_jane'},
Clark Boylanb640e052014-04-03 16:41:46 -0700294 'project': self.project,
295 'subject': self.subject,
296 'topic': 'master',
297 'url': 'https://hostname/459'},
Joshua Hesketh642824b2014-07-01 17:54:59 +1000298 'comment': message,
Clark Boylanb640e052014-04-03 16:41:46 -0700299 'patchSet': self.patchsets[-1],
300 'type': 'comment-added'}
301 self.data['submitRecords'] = self.getSubmitRecords()
302 return json.loads(json.dumps(event))
303
304 def getSubmitRecords(self):
305 status = {}
306 for cat in self.categories.keys():
307 status[cat] = 0
308
309 for a in self.patchsets[-1]['approvals']:
310 cur = status[a['type']]
311 cat_min, cat_max = self.categories[a['type']][1:]
312 new = int(a['value'])
313 if new == cat_min:
314 cur = new
315 elif abs(new) > abs(cur):
316 cur = new
317 status[a['type']] = cur
318
319 labels = []
320 ok = True
321 for typ, cat in self.categories.items():
322 cur = status[typ]
323 cat_min, cat_max = cat[1:]
324 if cur == cat_min:
325 value = 'REJECT'
326 ok = False
327 elif cur == cat_max:
328 value = 'OK'
329 else:
330 value = 'NEED'
331 ok = False
332 labels.append({'label': cat[0], 'status': value})
333 if ok:
334 return [{'status': 'OK'}]
335 return [{'status': 'NOT_READY',
336 'labels': labels}]
337
338 def setDependsOn(self, other, patchset):
339 self.depends_on_change = other
340 d = {'id': other.data['id'],
341 'number': other.data['number'],
342 'ref': other.patchsets[patchset - 1]['ref']
343 }
344 self.data['dependsOn'] = [d]
345
346 other.needed_by_changes.append(self)
347 needed = other.data.get('neededBy', [])
348 d = {'id': self.data['id'],
349 'number': self.data['number'],
350 'ref': self.patchsets[patchset - 1]['ref'],
351 'revision': self.patchsets[patchset - 1]['revision']
352 }
353 needed.append(d)
354 other.data['neededBy'] = needed
355
356 def query(self):
357 self.queried += 1
358 d = self.data.get('dependsOn')
359 if d:
360 d = d[0]
361 if (self.depends_on_change.patchsets[-1]['ref'] == d['ref']):
362 d['isCurrentPatchSet'] = True
363 else:
364 d['isCurrentPatchSet'] = False
365 return json.loads(json.dumps(self.data))
366
367 def setMerged(self):
368 if (self.depends_on_change and
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000369 self.depends_on_change.data['status'] != 'MERGED'):
Clark Boylanb640e052014-04-03 16:41:46 -0700370 return
371 if self.fail_merge:
372 return
373 self.data['status'] = 'MERGED'
374 self.open = False
375
376 path = os.path.join(self.upstream_root, self.project)
377 repo = git.Repo(path)
378 repo.heads[self.branch].commit = \
379 repo.commit(self.patchsets[-1]['revision'])
380
381 def setReported(self):
382 self.reported += 1
383
384
Joshua Hesketh352264b2015-08-11 23:42:08 +1000385class FakeGerritConnection(zuul.connection.gerrit.GerritConnection):
386 log = logging.getLogger("zuul.test.FakeGerritConnection")
James E. Blair96698e22015-04-02 07:48:21 -0700387
Joshua Hesketh352264b2015-08-11 23:42:08 +1000388 def __init__(self, connection_name, connection_config,
Jan Hruban6b71aff2015-10-22 16:58:08 +0200389 changes_db=None, queues_db=None, upstream_root=None):
Joshua Hesketh352264b2015-08-11 23:42:08 +1000390 super(FakeGerritConnection, self).__init__(connection_name,
391 connection_config)
392
393 self.event_queue = queues_db
Clark Boylanb640e052014-04-03 16:41:46 -0700394 self.fixture_dir = os.path.join(FIXTURE_DIR, 'gerrit')
395 self.change_number = 0
Joshua Hesketh352264b2015-08-11 23:42:08 +1000396 self.changes = changes_db
James E. Blairf8ff9932014-08-15 15:24:24 -0700397 self.queries = []
Jan Hruban6b71aff2015-10-22 16:58:08 +0200398 self.upstream_root = upstream_root
Clark Boylanb640e052014-04-03 16:41:46 -0700399
400 def addFakeChange(self, project, branch, subject, status='NEW'):
401 self.change_number += 1
402 c = FakeChange(self, self.change_number, project, branch, subject,
403 upstream_root=self.upstream_root,
404 status=status)
405 self.changes[self.change_number] = c
406 return c
407
Clark Boylanb640e052014-04-03 16:41:46 -0700408 def review(self, project, changeid, message, action):
409 number, ps = changeid.split(',')
410 change = self.changes[int(number)]
Joshua Hesketh642824b2014-07-01 17:54:59 +1000411
412 # Add the approval back onto the change (ie simulate what gerrit would
413 # do).
414 # Usually when zuul leaves a review it'll create a feedback loop where
415 # zuul's review enters another gerrit event (which is then picked up by
416 # zuul). However, we can't mimic this behaviour (by adding this
417 # approval event into the queue) as it stops jobs from checking what
418 # happens before this event is triggered. If a job needs to see what
419 # happens they can add their own verified event into the queue.
420 # Nevertheless, we can update change with the new review in gerrit.
421
422 for cat in ['CRVW', 'VRFY', 'APRV']:
423 if cat in action:
Joshua Hesketh352264b2015-08-11 23:42:08 +1000424 change.addApproval(cat, action[cat], username=self.user)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000425
426 if 'label' in action:
427 parts = action['label'].split('=')
Joshua Hesketh352264b2015-08-11 23:42:08 +1000428 change.addApproval(parts[0], parts[2], username=self.user)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000429
Clark Boylanb640e052014-04-03 16:41:46 -0700430 change.messages.append(message)
Joshua Hesketh642824b2014-07-01 17:54:59 +1000431
Clark Boylanb640e052014-04-03 16:41:46 -0700432 if 'submit' in action:
433 change.setMerged()
434 if message:
435 change.setReported()
436
437 def query(self, number):
438 change = self.changes.get(int(number))
439 if change:
440 return change.query()
441 return {}
442
James E. Blairc494d542014-08-06 09:23:52 -0700443 def simpleQuery(self, query):
James E. Blair96698e22015-04-02 07:48:21 -0700444 self.log.debug("simpleQuery: %s" % query)
James E. Blairf8ff9932014-08-15 15:24:24 -0700445 self.queries.append(query)
James E. Blair5ee24252014-12-30 10:12:29 -0800446 if query.startswith('change:'):
447 # Query a specific changeid
448 changeid = query[len('change:'):]
449 l = [change.query() for change in self.changes.values()
450 if change.data['id'] == changeid]
James E. Blair96698e22015-04-02 07:48:21 -0700451 elif query.startswith('message:'):
452 # Query the content of a commit message
453 msg = query[len('message:'):].strip()
454 l = [change.query() for change in self.changes.values()
455 if msg in change.data['commitMessage']]
James E. Blair5ee24252014-12-30 10:12:29 -0800456 else:
457 # Query all open changes
458 l = [change.query() for change in self.changes.values()]
James E. Blairf8ff9932014-08-15 15:24:24 -0700459 return l
James E. Blairc494d542014-08-06 09:23:52 -0700460
Joshua Hesketh352264b2015-08-11 23:42:08 +1000461 def _start_watcher_thread(self, *args, **kw):
Clark Boylanb640e052014-04-03 16:41:46 -0700462 pass
463
Joshua Hesketh352264b2015-08-11 23:42:08 +1000464 def getGitUrl(self, project):
465 return os.path.join(self.upstream_root, project.name)
466
Clark Boylanb640e052014-04-03 16:41:46 -0700467
468class BuildHistory(object):
469 def __init__(self, **kw):
470 self.__dict__.update(kw)
471
472 def __repr__(self):
473 return ("<Completed build, result: %s name: %s #%s changes: %s>" %
474 (self.result, self.name, self.number, self.changes))
475
476
477class FakeURLOpener(object):
Jan Hruban6b71aff2015-10-22 16:58:08 +0200478 def __init__(self, upstream_root, url):
Clark Boylanb640e052014-04-03 16:41:46 -0700479 self.upstream_root = upstream_root
Clark Boylanb640e052014-04-03 16:41:46 -0700480 self.url = url
481
482 def read(self):
483 res = urlparse.urlparse(self.url)
484 path = res.path
485 project = '/'.join(path.split('/')[2:-2])
486 ret = '001e# service=git-upload-pack\n'
487 ret += ('000000a31270149696713ba7e06f1beb760f20d359c4abed HEAD\x00'
488 'multi_ack thin-pack side-band side-band-64k ofs-delta '
489 'shallow no-progress include-tag multi_ack_detailed no-done\n')
490 path = os.path.join(self.upstream_root, project)
491 repo = git.Repo(path)
492 for ref in repo.refs:
493 r = ref.object.hexsha + ' ' + ref.path + '\n'
494 ret += '%04x%s' % (len(r) + 4, r)
495 ret += '0000'
496 return ret
497
498
Clark Boylanb640e052014-04-03 16:41:46 -0700499class FakeStatsd(threading.Thread):
500 def __init__(self):
501 threading.Thread.__init__(self)
502 self.daemon = True
503 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
504 self.sock.bind(('', 0))
505 self.port = self.sock.getsockname()[1]
506 self.wake_read, self.wake_write = os.pipe()
507 self.stats = []
508
509 def run(self):
510 while True:
511 poll = select.poll()
512 poll.register(self.sock, select.POLLIN)
513 poll.register(self.wake_read, select.POLLIN)
514 ret = poll.poll()
515 for (fd, event) in ret:
516 if fd == self.sock.fileno():
517 data = self.sock.recvfrom(1024)
518 if not data:
519 return
520 self.stats.append(data[0])
521 if fd == self.wake_read:
522 return
523
524 def stop(self):
525 os.write(self.wake_write, '1\n')
526
527
528class FakeBuild(threading.Thread):
529 log = logging.getLogger("zuul.test")
530
531 def __init__(self, worker, job, number, node):
532 threading.Thread.__init__(self)
533 self.daemon = True
534 self.worker = worker
535 self.job = job
536 self.name = job.name.split(':')[1]
537 self.number = number
538 self.node = node
539 self.parameters = json.loads(job.arguments)
540 self.unique = self.parameters['ZUUL_UUID']
541 self.wait_condition = threading.Condition()
542 self.waiting = False
543 self.aborted = False
544 self.created = time.time()
545 self.description = ''
546 self.run_error = False
547
548 def release(self):
549 self.wait_condition.acquire()
550 self.wait_condition.notify()
551 self.waiting = False
552 self.log.debug("Build %s released" % self.unique)
553 self.wait_condition.release()
554
555 def isWaiting(self):
556 self.wait_condition.acquire()
557 if self.waiting:
558 ret = True
559 else:
560 ret = False
561 self.wait_condition.release()
562 return ret
563
564 def _wait(self):
565 self.wait_condition.acquire()
566 self.waiting = True
567 self.log.debug("Build %s waiting" % self.unique)
568 self.wait_condition.wait()
569 self.wait_condition.release()
570
571 def run(self):
572 data = {
573 'url': 'https://server/job/%s/%s/' % (self.name, self.number),
574 'name': self.name,
575 'number': self.number,
576 'manager': self.worker.worker_id,
577 'worker_name': 'My Worker',
578 'worker_hostname': 'localhost',
579 'worker_ips': ['127.0.0.1', '192.168.1.1'],
580 'worker_fqdn': 'zuul.example.org',
581 'worker_program': 'FakeBuilder',
582 'worker_version': 'v1.1',
583 'worker_extra': {'something': 'else'}
584 }
585
586 self.log.debug('Running build %s' % self.unique)
587
588 self.job.sendWorkData(json.dumps(data))
589 self.log.debug('Sent WorkData packet with %s' % json.dumps(data))
590 self.job.sendWorkStatus(0, 100)
591
592 if self.worker.hold_jobs_in_build:
593 self.log.debug('Holding build %s' % self.unique)
594 self._wait()
595 self.log.debug("Build %s continuing" % self.unique)
596
597 self.worker.lock.acquire()
598
599 result = 'SUCCESS'
600 if (('ZUUL_REF' in self.parameters) and
601 self.worker.shouldFailTest(self.name,
602 self.parameters['ZUUL_REF'])):
603 result = 'FAILURE'
604 if self.aborted:
605 result = 'ABORTED'
606
607 if self.run_error:
608 work_fail = True
609 result = 'RUN_ERROR'
610 else:
611 data['result'] = result
Timothy Chavezb2332082015-08-07 20:08:04 -0500612 data['node_labels'] = ['bare-necessities']
613 data['node_name'] = 'foo'
Clark Boylanb640e052014-04-03 16:41:46 -0700614 work_fail = False
615
616 changes = None
617 if 'ZUUL_CHANGE_IDS' in self.parameters:
618 changes = self.parameters['ZUUL_CHANGE_IDS']
619
620 self.worker.build_history.append(
621 BuildHistory(name=self.name, number=self.number,
622 result=result, changes=changes, node=self.node,
623 uuid=self.unique, description=self.description,
624 pipeline=self.parameters['ZUUL_PIPELINE'])
625 )
626
627 self.job.sendWorkData(json.dumps(data))
628 if work_fail:
629 self.job.sendWorkFail()
630 else:
631 self.job.sendWorkComplete(json.dumps(data))
632 del self.worker.gearman_jobs[self.job.unique]
633 self.worker.running_builds.remove(self)
634 self.worker.lock.release()
635
636
637class FakeWorker(gear.Worker):
638 def __init__(self, worker_id, test):
639 super(FakeWorker, self).__init__(worker_id)
640 self.gearman_jobs = {}
641 self.build_history = []
642 self.running_builds = []
643 self.build_counter = 0
644 self.fail_tests = {}
645 self.test = test
646
647 self.hold_jobs_in_build = False
648 self.lock = threading.Lock()
649 self.__work_thread = threading.Thread(target=self.work)
650 self.__work_thread.daemon = True
651 self.__work_thread.start()
652
653 def handleJob(self, job):
654 parts = job.name.split(":")
655 cmd = parts[0]
656 name = parts[1]
657 if len(parts) > 2:
658 node = parts[2]
659 else:
660 node = None
661 if cmd == 'build':
662 self.handleBuild(job, name, node)
663 elif cmd == 'stop':
664 self.handleStop(job, name)
665 elif cmd == 'set_description':
666 self.handleSetDescription(job, name)
667
668 def handleBuild(self, job, name, node):
669 build = FakeBuild(self, job, self.build_counter, node)
670 job.build = build
671 self.gearman_jobs[job.unique] = job
672 self.build_counter += 1
673
674 self.running_builds.append(build)
675 build.start()
676
677 def handleStop(self, job, name):
678 self.log.debug("handle stop")
679 parameters = json.loads(job.arguments)
680 name = parameters['name']
681 number = parameters['number']
682 for build in self.running_builds:
683 if build.name == name and build.number == number:
684 build.aborted = True
685 build.release()
686 job.sendWorkComplete()
687 return
688 job.sendWorkFail()
689
690 def handleSetDescription(self, job, name):
691 self.log.debug("handle set description")
692 parameters = json.loads(job.arguments)
693 name = parameters['name']
694 number = parameters['number']
695 descr = parameters['html_description']
696 for build in self.running_builds:
697 if build.name == name and build.number == number:
698 build.description = descr
699 job.sendWorkComplete()
700 return
701 for build in self.build_history:
702 if build.name == name and build.number == number:
703 build.description = descr
704 job.sendWorkComplete()
705 return
706 job.sendWorkFail()
707
708 def work(self):
709 while self.running:
710 try:
711 job = self.getJob()
712 except gear.InterruptedError:
713 continue
714 try:
715 self.handleJob(job)
716 except:
717 self.log.exception("Worker exception:")
718
719 def addFailTest(self, name, change):
720 l = self.fail_tests.get(name, [])
721 l.append(change)
722 self.fail_tests[name] = l
723
724 def shouldFailTest(self, name, ref):
725 l = self.fail_tests.get(name, [])
726 for change in l:
727 if self.test.ref_has_change(ref, change):
728 return True
729 return False
730
731 def release(self, regex=None):
732 builds = self.running_builds[:]
733 self.log.debug("releasing build %s (%s)" % (regex,
734 len(self.running_builds)))
735 for build in builds:
736 if not regex or re.match(regex, build.name):
737 self.log.debug("releasing build %s" %
738 (build.parameters['ZUUL_UUID']))
739 build.release()
740 else:
741 self.log.debug("not releasing build %s" %
742 (build.parameters['ZUUL_UUID']))
743 self.log.debug("done releasing builds %s (%s)" %
744 (regex, len(self.running_builds)))
745
746
747class FakeGearmanServer(gear.Server):
748 def __init__(self):
749 self.hold_jobs_in_queue = False
750 super(FakeGearmanServer, self).__init__(0)
751
752 def getJobForConnection(self, connection, peek=False):
753 for queue in [self.high_queue, self.normal_queue, self.low_queue]:
754 for job in queue:
755 if not hasattr(job, 'waiting'):
756 if job.name.startswith('build:'):
757 job.waiting = self.hold_jobs_in_queue
758 else:
759 job.waiting = False
760 if job.waiting:
761 continue
762 if job.name in connection.functions:
763 if not peek:
764 queue.remove(job)
765 connection.related_jobs[job.handle] = job
766 job.worker_connection = connection
767 job.running = True
768 return job
769 return None
770
771 def release(self, regex=None):
772 released = False
773 qlen = (len(self.high_queue) + len(self.normal_queue) +
774 len(self.low_queue))
775 self.log.debug("releasing queued job %s (%s)" % (regex, qlen))
776 for job in self.getQueue():
777 cmd, name = job.name.split(':')
778 if cmd != 'build':
779 continue
780 if not regex or re.match(regex, name):
781 self.log.debug("releasing queued job %s" %
782 job.unique)
783 job.waiting = False
784 released = True
785 else:
786 self.log.debug("not releasing queued job %s" %
787 job.unique)
788 if released:
789 self.wakeConnections()
790 qlen = (len(self.high_queue) + len(self.normal_queue) +
791 len(self.low_queue))
792 self.log.debug("done releasing queued jobs %s (%s)" % (regex, qlen))
793
794
795class FakeSMTP(object):
796 log = logging.getLogger('zuul.FakeSMTP')
797
798 def __init__(self, messages, server, port):
799 self.server = server
800 self.port = port
801 self.messages = messages
802
803 def sendmail(self, from_email, to_email, msg):
804 self.log.info("Sending email from %s, to %s, with msg %s" % (
805 from_email, to_email, msg))
806
807 headers = msg.split('\n\n', 1)[0]
808 body = msg.split('\n\n', 1)[1]
809
810 self.messages.append(dict(
811 from_email=from_email,
812 to_email=to_email,
813 msg=msg,
814 headers=headers,
815 body=body,
816 ))
817
818 return True
819
820 def quit(self):
821 return True
822
823
824class FakeSwiftClientConnection(swiftclient.client.Connection):
825 def post_account(self, headers):
826 # Do nothing
827 pass
828
829 def get_auth(self):
830 # Returns endpoint and (unused) auth token
831 endpoint = os.path.join('https://storage.example.org', 'V1',
832 'AUTH_account')
833 return endpoint, ''
834
835
Maru Newby3fe5f852015-01-13 04:22:14 +0000836class BaseTestCase(testtools.TestCase):
Clark Boylanb640e052014-04-03 16:41:46 -0700837 log = logging.getLogger("zuul.test")
838
839 def setUp(self):
Maru Newby3fe5f852015-01-13 04:22:14 +0000840 super(BaseTestCase, self).setUp()
Clark Boylanb640e052014-04-03 16:41:46 -0700841 test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
842 try:
843 test_timeout = int(test_timeout)
844 except ValueError:
845 # If timeout value is invalid do not set a timeout.
846 test_timeout = 0
847 if test_timeout > 0:
848 self.useFixture(fixtures.Timeout(test_timeout, gentle=False))
849
850 if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
851 os.environ.get('OS_STDOUT_CAPTURE') == '1'):
852 stdout = self.useFixture(fixtures.StringStream('stdout')).stream
853 self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
854 if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
855 os.environ.get('OS_STDERR_CAPTURE') == '1'):
856 stderr = self.useFixture(fixtures.StringStream('stderr')).stream
857 self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
858 if (os.environ.get('OS_LOG_CAPTURE') == 'True' or
859 os.environ.get('OS_LOG_CAPTURE') == '1'):
860 self.useFixture(fixtures.FakeLogger(
861 level=logging.DEBUG,
862 format='%(asctime)s %(name)-32s '
863 '%(levelname)-8s %(message)s'))
Maru Newby3fe5f852015-01-13 04:22:14 +0000864
865
866class ZuulTestCase(BaseTestCase):
867
868 def setUp(self):
869 super(ZuulTestCase, self).setUp()
James E. Blair97d902e2014-08-21 13:25:56 -0700870 if USE_TEMPDIR:
871 tmp_root = self.useFixture(fixtures.TempDir(
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000872 rootdir=os.environ.get("ZUUL_TEST_ROOT"))
873 ).path
James E. Blair97d902e2014-08-21 13:25:56 -0700874 else:
875 tmp_root = os.environ.get("ZUUL_TEST_ROOT")
Clark Boylanb640e052014-04-03 16:41:46 -0700876 self.test_root = os.path.join(tmp_root, "zuul-test")
877 self.upstream_root = os.path.join(self.test_root, "upstream")
878 self.git_root = os.path.join(self.test_root, "git")
879
880 if os.path.exists(self.test_root):
881 shutil.rmtree(self.test_root)
882 os.makedirs(self.test_root)
883 os.makedirs(self.upstream_root)
Clark Boylanb640e052014-04-03 16:41:46 -0700884
885 # Make per test copy of Configuration.
886 self.setup_config()
James E. Blair59fdbac2015-12-07 17:08:06 -0800887 self.config.set('zuul', 'tenant_config',
Joshua Heskethacccffc2015-03-31 23:38:17 +1100888 os.path.join(FIXTURE_DIR,
James E. Blair59fdbac2015-12-07 17:08:06 -0800889 self.config.get('zuul', 'tenant_config')))
Clark Boylanb640e052014-04-03 16:41:46 -0700890 self.config.set('merger', 'git_dir', self.git_root)
891
892 # For each project in config:
893 self.init_repo("org/project")
894 self.init_repo("org/project1")
895 self.init_repo("org/project2")
896 self.init_repo("org/project3")
James E. Blair97d902e2014-08-21 13:25:56 -0700897 self.init_repo("org/project4")
James E. Blairbce35e12014-08-21 14:31:17 -0700898 self.init_repo("org/project5")
899 self.init_repo("org/project6")
Clark Boylanb640e052014-04-03 16:41:46 -0700900 self.init_repo("org/one-job-project")
901 self.init_repo("org/nonvoting-project")
902 self.init_repo("org/templated-project")
903 self.init_repo("org/layered-project")
904 self.init_repo("org/node-project")
905 self.init_repo("org/conflict-project")
906 self.init_repo("org/noop-project")
907 self.init_repo("org/experimental-project")
Evgeny Antyshevd6e546c2015-06-11 15:13:57 +0000908 self.init_repo("org/no-jobs-project")
Clark Boylanb640e052014-04-03 16:41:46 -0700909
910 self.statsd = FakeStatsd()
Ian Wienandff977bf2015-09-30 15:38:47 +1000911 # note, use 127.0.0.1 rather than localhost to avoid getting ipv6
912 # see: https://github.com/jsocol/pystatsd/issues/61
913 os.environ['STATSD_HOST'] = '127.0.0.1'
Clark Boylanb640e052014-04-03 16:41:46 -0700914 os.environ['STATSD_PORT'] = str(self.statsd.port)
915 self.statsd.start()
916 # the statsd client object is configured in the statsd module import
917 reload(statsd)
918 reload(zuul.scheduler)
919
920 self.gearman_server = FakeGearmanServer()
921
922 self.config.set('gearman', 'port', str(self.gearman_server.port))
923
924 self.worker = FakeWorker('fake_worker', self)
925 self.worker.addServer('127.0.0.1', self.gearman_server.port)
926 self.gearman_server.worker = self.worker
927
Joshua Hesketh352264b2015-08-11 23:42:08 +1000928 zuul.source.gerrit.GerritSource.replication_timeout = 1.5
929 zuul.source.gerrit.GerritSource.replication_retry_interval = 0.5
930 zuul.connection.gerrit.GerritEventConnector.delay = 0.0
Clark Boylanb640e052014-04-03 16:41:46 -0700931
Joshua Hesketh352264b2015-08-11 23:42:08 +1000932 self.sched = zuul.scheduler.Scheduler(self.config)
Clark Boylanb640e052014-04-03 16:41:46 -0700933
934 self.useFixture(fixtures.MonkeyPatch('swiftclient.client.Connection',
935 FakeSwiftClientConnection))
936 self.swift = zuul.lib.swift.Swift(self.config)
937
Jan Hruban6b71aff2015-10-22 16:58:08 +0200938 self.event_queues = [
939 self.sched.result_event_queue,
940 self.sched.trigger_event_queue
941 ]
942
Joshua Hesketh352264b2015-08-11 23:42:08 +1000943 self.configure_connections()
944 self.sched.registerConnections(self.connections)
Joshua Hesketh352264b2015-08-11 23:42:08 +1000945
Clark Boylanb640e052014-04-03 16:41:46 -0700946 def URLOpenerFactory(*args, **kw):
947 if isinstance(args[0], urllib2.Request):
948 return old_urlopen(*args, **kw)
Clark Boylanb640e052014-04-03 16:41:46 -0700949 return FakeURLOpener(self.upstream_root, *args, **kw)
950
951 old_urlopen = urllib2.urlopen
952 urllib2.urlopen = URLOpenerFactory
953
Joshua Hesketh352264b2015-08-11 23:42:08 +1000954 self.merge_server = zuul.merger.server.MergeServer(self.config,
955 self.connections)
956 self.merge_server.start()
Clark Boylanb640e052014-04-03 16:41:46 -0700957
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100958 self.launcher = zuul.launcher.gearman.Gearman(self.config, self.sched,
959 self.swift)
960 self.merge_client = zuul.merger.client.MergeClient(
961 self.config, self.sched)
Clark Boylanb640e052014-04-03 16:41:46 -0700962
963 self.sched.setLauncher(self.launcher)
964 self.sched.setMerger(self.merge_client)
Clark Boylanb640e052014-04-03 16:41:46 -0700965
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100966 self.webapp = zuul.webapp.WebApp(self.sched, port=0)
967 self.rpc = zuul.rpclistener.RPCListener(self.config, self.sched)
Clark Boylanb640e052014-04-03 16:41:46 -0700968
969 self.sched.start()
970 self.sched.reconfigure(self.config)
971 self.sched.resume()
972 self.webapp.start()
973 self.rpc.start()
974 self.launcher.gearman.waitForServer()
975 self.registerJobs()
976 self.builds = self.worker.running_builds
977 self.history = self.worker.build_history
978
979 self.addCleanup(self.assertFinalState)
980 self.addCleanup(self.shutdown)
981
Joshua Hesketh352264b2015-08-11 23:42:08 +1000982 def configure_connections(self):
983 # Register connections from the config
984 self.smtp_messages = []
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100985
Joshua Hesketh352264b2015-08-11 23:42:08 +1000986 def FakeSMTPFactory(*args, **kw):
987 args = [self.smtp_messages] + list(args)
988 return FakeSMTP(*args, **kw)
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100989
Joshua Hesketh352264b2015-08-11 23:42:08 +1000990 self.useFixture(fixtures.MonkeyPatch('smtplib.SMTP', FakeSMTPFactory))
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100991
Joshua Hesketh352264b2015-08-11 23:42:08 +1000992 # Set a changes database so multiple FakeGerrit's can report back to
993 # a virtual canonical database given by the configured hostname
994 self.gerrit_changes_dbs = {}
995 self.gerrit_queues_dbs = {}
996 self.connections = {}
Joshua Hesketh850ccb62014-11-27 11:31:02 +1100997
Joshua Hesketh352264b2015-08-11 23:42:08 +1000998 for section_name in self.config.sections():
999 con_match = re.match(r'^connection ([\'\"]?)(.*)(\1)$',
1000 section_name, re.I)
1001 if not con_match:
1002 continue
1003 con_name = con_match.group(2)
1004 con_config = dict(self.config.items(section_name))
1005
1006 if 'driver' not in con_config:
1007 raise Exception("No driver specified for connection %s."
1008 % con_name)
1009
1010 con_driver = con_config['driver']
1011
1012 # TODO(jhesketh): load the required class automatically
1013 if con_driver == 'gerrit':
Joshua Heskethacccffc2015-03-31 23:38:17 +11001014 if con_config['server'] not in self.gerrit_changes_dbs.keys():
1015 self.gerrit_changes_dbs[con_config['server']] = {}
1016 if con_config['server'] not in self.gerrit_queues_dbs.keys():
1017 self.gerrit_queues_dbs[con_config['server']] = \
1018 Queue.Queue()
1019 self.event_queues.append(
1020 self.gerrit_queues_dbs[con_config['server']])
Joshua Hesketh352264b2015-08-11 23:42:08 +10001021 self.connections[con_name] = FakeGerritConnection(
1022 con_name, con_config,
Joshua Heskethacccffc2015-03-31 23:38:17 +11001023 changes_db=self.gerrit_changes_dbs[con_config['server']],
1024 queues_db=self.gerrit_queues_dbs[con_config['server']],
Jan Hruban6b71aff2015-10-22 16:58:08 +02001025 upstream_root=self.upstream_root
Joshua Hesketh352264b2015-08-11 23:42:08 +10001026 )
Joshua Heskethacccffc2015-03-31 23:38:17 +11001027 setattr(self, 'fake_' + con_name, self.connections[con_name])
Joshua Hesketh352264b2015-08-11 23:42:08 +10001028 elif con_driver == 'smtp':
1029 self.connections[con_name] = \
1030 zuul.connection.smtp.SMTPConnection(con_name, con_config)
1031 else:
1032 raise Exception("Unknown driver, %s, for connection %s"
1033 % (con_config['driver'], con_name))
1034
1035 # If the [gerrit] or [smtp] sections still exist, load them in as a
1036 # connection named 'gerrit' or 'smtp' respectfully
1037
1038 if 'gerrit' in self.config.sections():
1039 self.gerrit_changes_dbs['gerrit'] = {}
1040 self.gerrit_queues_dbs['gerrit'] = Queue.Queue()
Jan Hruban6b71aff2015-10-22 16:58:08 +02001041 self.event_queues.append(self.gerrit_queues_dbs['gerrit'])
Joshua Hesketh352264b2015-08-11 23:42:08 +10001042 self.connections['gerrit'] = FakeGerritConnection(
1043 '_legacy_gerrit', dict(self.config.items('gerrit')),
1044 changes_db=self.gerrit_changes_dbs['gerrit'],
1045 queues_db=self.gerrit_queues_dbs['gerrit'])
1046
1047 if 'smtp' in self.config.sections():
1048 self.connections['smtp'] = \
1049 zuul.connection.smtp.SMTPConnection(
1050 '_legacy_smtp', dict(self.config.items('smtp')))
Joshua Hesketh850ccb62014-11-27 11:31:02 +11001051
Joshua Heskethacccffc2015-03-31 23:38:17 +11001052 def setup_config(self, config_file='zuul.conf'):
Clark Boylanb640e052014-04-03 16:41:46 -07001053 """Per test config object. Override to set different config."""
1054 self.config = ConfigParser.ConfigParser()
Joshua Heskethacccffc2015-03-31 23:38:17 +11001055 self.config.read(os.path.join(FIXTURE_DIR, config_file))
Clark Boylanb640e052014-04-03 16:41:46 -07001056
1057 def assertFinalState(self):
Clark Boylanb640e052014-04-03 16:41:46 -07001058 # Make sure that git.Repo objects have been garbage collected.
1059 repos = []
1060 gc.collect()
1061 for obj in gc.get_objects():
1062 if isinstance(obj, git.Repo):
1063 repos.append(obj)
1064 self.assertEqual(len(repos), 0)
1065 self.assertEmptyQueues()
James E. Blair59fdbac2015-12-07 17:08:06 -08001066 for tenant in self.sched.abide.tenants.values():
1067 for pipeline in tenant.layout.pipelines.values():
1068 if isinstance(pipeline.manager,
1069 zuul.scheduler.IndependentPipelineManager):
1070 self.assertEqual(len(pipeline.queues), 0)
Clark Boylanb640e052014-04-03 16:41:46 -07001071
1072 def shutdown(self):
1073 self.log.debug("Shutting down after tests")
1074 self.launcher.stop()
1075 self.merge_server.stop()
1076 self.merge_server.join()
1077 self.merge_client.stop()
1078 self.worker.shutdown()
Clark Boylanb640e052014-04-03 16:41:46 -07001079 self.sched.stop()
1080 self.sched.join()
1081 self.statsd.stop()
1082 self.statsd.join()
1083 self.webapp.stop()
1084 self.webapp.join()
1085 self.rpc.stop()
1086 self.rpc.join()
1087 self.gearman_server.shutdown()
1088 threads = threading.enumerate()
1089 if len(threads) > 1:
1090 self.log.error("More than one thread is running: %s" % threads)
Clark Boylanb640e052014-04-03 16:41:46 -07001091
1092 def init_repo(self, project):
1093 parts = project.split('/')
1094 path = os.path.join(self.upstream_root, *parts[:-1])
1095 if not os.path.exists(path):
1096 os.makedirs(path)
1097 path = os.path.join(self.upstream_root, project)
1098 repo = git.Repo.init(path)
1099
1100 repo.config_writer().set_value('user', 'email', 'user@example.com')
1101 repo.config_writer().set_value('user', 'name', 'User Name')
1102 repo.config_writer().write()
1103
1104 fn = os.path.join(path, 'README')
1105 f = open(fn, 'w')
1106 f.write("test\n")
1107 f.close()
1108 repo.index.add([fn])
1109 repo.index.commit('initial commit')
1110 master = repo.create_head('master')
1111 repo.create_tag('init')
1112
James E. Blair97d902e2014-08-21 13:25:56 -07001113 repo.head.reference = master
James E. Blair879dafb2015-07-17 14:04:49 -07001114 zuul.merger.merger.reset_repo_to_head(repo)
James E. Blair97d902e2014-08-21 13:25:56 -07001115 repo.git.clean('-x', '-f', '-d')
1116
1117 self.create_branch(project, 'mp')
1118
1119 def create_branch(self, project, branch):
1120 path = os.path.join(self.upstream_root, project)
1121 repo = git.Repo.init(path)
1122 fn = os.path.join(path, 'README')
1123
1124 branch_head = repo.create_head(branch)
1125 repo.head.reference = branch_head
Clark Boylanb640e052014-04-03 16:41:46 -07001126 f = open(fn, 'a')
James E. Blair97d902e2014-08-21 13:25:56 -07001127 f.write("test %s\n" % branch)
Clark Boylanb640e052014-04-03 16:41:46 -07001128 f.close()
1129 repo.index.add([fn])
James E. Blair97d902e2014-08-21 13:25:56 -07001130 repo.index.commit('%s commit' % branch)
Clark Boylanb640e052014-04-03 16:41:46 -07001131
James E. Blair97d902e2014-08-21 13:25:56 -07001132 repo.head.reference = repo.heads['master']
James E. Blair879dafb2015-07-17 14:04:49 -07001133 zuul.merger.merger.reset_repo_to_head(repo)
Clark Boylanb640e052014-04-03 16:41:46 -07001134 repo.git.clean('-x', '-f', '-d')
1135
1136 def ref_has_change(self, ref, change):
1137 path = os.path.join(self.git_root, change.project)
1138 repo = git.Repo(path)
Mike Heald8225f522014-11-21 09:52:33 +00001139 try:
1140 for commit in repo.iter_commits(ref):
1141 if commit.message.strip() == ('%s-1' % change.subject):
1142 return True
1143 except GitCommandError:
1144 pass
Clark Boylanb640e052014-04-03 16:41:46 -07001145 return False
1146
1147 def job_has_changes(self, *args):
1148 job = args[0]
1149 commits = args[1:]
1150 if isinstance(job, FakeBuild):
1151 parameters = job.parameters
1152 else:
1153 parameters = json.loads(job.arguments)
1154 project = parameters['ZUUL_PROJECT']
1155 path = os.path.join(self.git_root, project)
1156 repo = git.Repo(path)
1157 ref = parameters['ZUUL_REF']
1158 sha = parameters['ZUUL_COMMIT']
1159 repo_messages = [c.message.strip() for c in repo.iter_commits(ref)]
1160 repo_shas = [c.hexsha for c in repo.iter_commits(ref)]
1161 commit_messages = ['%s-1' % commit.subject for commit in commits]
1162 self.log.debug("Checking if job %s has changes; commit_messages %s;"
1163 " repo_messages %s; sha %s" % (job, commit_messages,
1164 repo_messages, sha))
1165 for msg in commit_messages:
1166 if msg not in repo_messages:
1167 self.log.debug(" messages do not match")
1168 return False
1169 if repo_shas[0] != sha:
1170 self.log.debug(" sha does not match")
1171 return False
1172 self.log.debug(" OK")
1173 return True
1174
1175 def registerJobs(self):
1176 count = 0
James E. Blair59fdbac2015-12-07 17:08:06 -08001177 for tenant in self.sched.abide.tenants.values():
1178 for job in tenant.layout.jobs.keys():
1179 self.worker.registerFunction('build:' + job)
1180 count += 1
Clark Boylanb640e052014-04-03 16:41:46 -07001181 self.worker.registerFunction('stop:' + self.worker.worker_id)
1182 count += 1
1183
1184 while len(self.gearman_server.functions) < count:
1185 time.sleep(0)
1186
James E. Blairb8c16472015-05-05 14:55:26 -07001187 def orderedRelease(self):
1188 # Run one build at a time to ensure non-race order:
1189 while len(self.builds):
1190 self.release(self.builds[0])
1191 self.waitUntilSettled()
1192
Clark Boylanb640e052014-04-03 16:41:46 -07001193 def release(self, job):
1194 if isinstance(job, FakeBuild):
1195 job.release()
1196 else:
1197 job.waiting = False
1198 self.log.debug("Queued job %s released" % job.unique)
1199 self.gearman_server.wakeConnections()
1200
1201 def getParameter(self, job, name):
1202 if isinstance(job, FakeBuild):
1203 return job.parameters[name]
1204 else:
1205 parameters = json.loads(job.arguments)
1206 return parameters[name]
1207
1208 def resetGearmanServer(self):
1209 self.worker.setFunctions([])
1210 while True:
1211 done = True
1212 for connection in self.gearman_server.active_connections:
1213 if (connection.functions and
1214 connection.client_id not in ['Zuul RPC Listener',
1215 'Zuul Merger']):
1216 done = False
1217 if done:
1218 break
1219 time.sleep(0)
1220 self.gearman_server.functions = set()
1221 self.rpc.register()
1222 self.merge_server.register()
1223
1224 def haveAllBuildsReported(self):
1225 # See if Zuul is waiting on a meta job to complete
1226 if self.launcher.meta_jobs:
1227 return False
1228 # Find out if every build that the worker has completed has been
1229 # reported back to Zuul. If it hasn't then that means a Gearman
1230 # event is still in transit and the system is not stable.
1231 for build in self.worker.build_history:
1232 zbuild = self.launcher.builds.get(build.uuid)
1233 if not zbuild:
1234 # It has already been reported
1235 continue
1236 # It hasn't been reported yet.
1237 return False
1238 # Make sure that none of the worker connections are in GRAB_WAIT
1239 for connection in self.worker.active_connections:
1240 if connection.state == 'GRAB_WAIT':
1241 return False
1242 return True
1243
1244 def areAllBuildsWaiting(self):
Clark Boylanb640e052014-04-03 16:41:46 -07001245 builds = self.launcher.builds.values()
1246 for build in builds:
1247 client_job = None
1248 for conn in self.launcher.gearman.active_connections:
1249 for j in conn.related_jobs.values():
1250 if j.unique == build.uuid:
1251 client_job = j
1252 break
1253 if not client_job:
1254 self.log.debug("%s is not known to the gearman client" %
1255 build)
James E. Blairf15139b2015-04-02 16:37:15 -07001256 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001257 if not client_job.handle:
1258 self.log.debug("%s has no handle" % client_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001259 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001260 server_job = self.gearman_server.jobs.get(client_job.handle)
1261 if not server_job:
1262 self.log.debug("%s is not known to the gearman server" %
1263 client_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001264 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001265 if not hasattr(server_job, 'waiting'):
1266 self.log.debug("%s is being enqueued" % server_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001267 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001268 if server_job.waiting:
1269 continue
1270 worker_job = self.worker.gearman_jobs.get(server_job.unique)
1271 if worker_job:
James E. Blairf15139b2015-04-02 16:37:15 -07001272 if build.number is None:
1273 self.log.debug("%s has not reported start" % worker_job)
1274 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001275 if worker_job.build.isWaiting():
1276 continue
1277 else:
1278 self.log.debug("%s is running" % worker_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001279 return False
Clark Boylanb640e052014-04-03 16:41:46 -07001280 else:
1281 self.log.debug("%s is unassigned" % server_job)
James E. Blairf15139b2015-04-02 16:37:15 -07001282 return False
1283 return True
Clark Boylanb640e052014-04-03 16:41:46 -07001284
Jan Hruban6b71aff2015-10-22 16:58:08 +02001285 def eventQueuesEmpty(self):
1286 for queue in self.event_queues:
1287 yield queue.empty()
1288
1289 def eventQueuesJoin(self):
1290 for queue in self.event_queues:
1291 queue.join()
1292
Clark Boylanb640e052014-04-03 16:41:46 -07001293 def waitUntilSettled(self):
1294 self.log.debug("Waiting until settled...")
1295 start = time.time()
1296 while True:
1297 if time.time() - start > 10:
1298 print 'queue status:',
Jan Hruban6b71aff2015-10-22 16:58:08 +02001299 print ' '.join(self.eventQueuesEmpty())
Clark Boylanb640e052014-04-03 16:41:46 -07001300 print self.areAllBuildsWaiting()
1301 raise Exception("Timeout waiting for Zuul to settle")
1302 # Make sure no new events show up while we're checking
1303 self.worker.lock.acquire()
1304 # have all build states propogated to zuul?
1305 if self.haveAllBuildsReported():
1306 # Join ensures that the queue is empty _and_ events have been
1307 # processed
Jan Hruban6b71aff2015-10-22 16:58:08 +02001308 self.eventQueuesJoin()
Clark Boylanb640e052014-04-03 16:41:46 -07001309 self.sched.run_handler_lock.acquire()
James E. Blairae1b2d12015-02-07 08:01:21 -08001310 if (not self.merge_client.build_sets and
Jan Hruban6b71aff2015-10-22 16:58:08 +02001311 all(self.eventQueuesEmpty()) and
Clark Boylanb640e052014-04-03 16:41:46 -07001312 self.haveAllBuildsReported() and
1313 self.areAllBuildsWaiting()):
1314 self.sched.run_handler_lock.release()
1315 self.worker.lock.release()
1316 self.log.debug("...settled.")
1317 return
1318 self.sched.run_handler_lock.release()
1319 self.worker.lock.release()
1320 self.sched.wake_event.wait(0.1)
1321
1322 def countJobResults(self, jobs, result):
1323 jobs = filter(lambda x: x.result == result, jobs)
1324 return len(jobs)
1325
1326 def getJobFromHistory(self, name):
1327 history = self.worker.build_history
1328 for job in history:
1329 if job.name == name:
1330 return job
1331 raise Exception("Unable to find job %s in history" % name)
1332
1333 def assertEmptyQueues(self):
1334 # Make sure there are no orphaned jobs
James E. Blair59fdbac2015-12-07 17:08:06 -08001335 for tenant in self.sched.abide.tenants.values():
1336 for pipeline in tenant.layout.pipelines.values():
1337 for queue in pipeline.queues:
1338 if len(queue.queue) != 0:
1339 print 'pipeline %s queue %s contents %s' % (
1340 pipeline.name, queue.name, queue.queue)
1341 self.assertEqual(len(queue.queue), 0,
1342 "Pipelines queues should be empty")
Clark Boylanb640e052014-04-03 16:41:46 -07001343
1344 def assertReportedStat(self, key, value=None, kind=None):
1345 start = time.time()
1346 while time.time() < (start + 5):
1347 for stat in self.statsd.stats:
1348 pprint.pprint(self.statsd.stats)
1349 k, v = stat.split(':')
1350 if key == k:
1351 if value is None and kind is None:
1352 return
1353 elif value:
1354 if value == v:
1355 return
1356 elif kind:
1357 if v.endswith('|' + kind):
1358 return
1359 time.sleep(0.1)
1360
1361 pprint.pprint(self.statsd.stats)
1362 raise Exception("Key %s not found in reported stats" % key)
James E. Blair59fdbac2015-12-07 17:08:06 -08001363
1364 def getPipeline(self, name):
James E. Blairf84026c2015-12-08 16:11:46 -08001365 return self.sched.abide.tenants.values()[0].layout.pipelines.get(name)
1366
1367 def updateConfigLayout(self, path):
1368 root = os.path.join(self.test_root, "config")
1369 os.makedirs(root)
1370 f = tempfile.NamedTemporaryFile(dir=root, delete=False)
1371 f.write("""
1372tenants:
1373 - name: openstack
1374 include:
1375 - %s
1376 """ % os.path.abspath(path))
1377 f.close()
1378 self.config.set('zuul', 'tenant_config', f.name)