blob: a13fcba23a8308ff3c82bec9abfd41443338253b [file] [log] [blame]
James E. Blairee743612012-05-29 14:49:32 -07001# 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
James E. Blair1b265312014-06-24 09:35:21 -070015import copy
James E. Blairce8a2132016-05-19 15:21:52 -070016import os
James E. Blairee743612012-05-29 14:49:32 -070017import re
James E. Blairce8a2132016-05-19 15:21:52 -070018import struct
James E. Blairff986a12012-05-30 14:56:51 -070019import time
James E. Blair4886cc12012-07-18 15:39:41 -070020from uuid import uuid4
James E. Blair5a9918a2013-08-27 10:06:27 -070021import extras
22
23OrderedDict = extras.try_imports(['collections.OrderedDict',
24 'ordereddict.OrderedDict'])
James E. Blair4886cc12012-07-18 15:39:41 -070025
26
K Jonathan Harkerf95e7232015-04-29 13:33:16 -070027EMPTY_GIT_REF = '0' * 40 # git sha of all zeros, used during creates/deletes
28
James E. Blair19deff22013-08-25 13:17:35 -070029MERGER_MERGE = 1 # "git merge"
30MERGER_MERGE_RESOLVE = 2 # "git merge -s resolve"
31MERGER_CHERRY_PICK = 3 # "git cherry-pick"
32
33MERGER_MAP = {
34 'merge': MERGER_MERGE,
35 'merge-resolve': MERGER_MERGE_RESOLVE,
36 'cherry-pick': MERGER_CHERRY_PICK,
37}
James E. Blairee743612012-05-29 14:49:32 -070038
James E. Blair64ed6f22013-07-10 14:07:23 -070039PRECEDENCE_NORMAL = 0
40PRECEDENCE_LOW = 1
41PRECEDENCE_HIGH = 2
42
43PRECEDENCE_MAP = {
44 None: PRECEDENCE_NORMAL,
45 'low': PRECEDENCE_LOW,
46 'normal': PRECEDENCE_NORMAL,
47 'high': PRECEDENCE_HIGH,
48}
49
James E. Blair1e8dd892012-05-30 09:15:05 -070050
James E. Blairc053d022014-01-22 14:57:33 -080051def time_to_seconds(s):
52 if s.endswith('s'):
53 return int(s[:-1])
54 if s.endswith('m'):
55 return int(s[:-1]) * 60
56 if s.endswith('h'):
57 return int(s[:-1]) * 60 * 60
58 if s.endswith('d'):
59 return int(s[:-1]) * 24 * 60 * 60
60 if s.endswith('w'):
61 return int(s[:-1]) * 7 * 24 * 60 * 60
62 raise Exception("Unable to parse time value: %s" % s)
63
64
James E. Blair11041d22014-05-02 14:49:53 -070065def normalizeCategory(name):
66 name = name.lower()
67 return re.sub(' ', '-', name)
68
69
James E. Blair4aea70c2012-07-26 14:23:24 -070070class Pipeline(object):
Monty Taylora42a55b2016-07-29 07:53:33 -070071 """A configuration that ties triggers, reporters, managers and sources.
72
Monty Taylor82dfd412016-07-29 12:01:28 -070073 Source
74 Where changes should come from. It is a named connection to
Monty Taylora42a55b2016-07-29 07:53:33 -070075 an external service defined in zuul.conf
Monty Taylor82dfd412016-07-29 12:01:28 -070076
77 Trigger
78 A description of which events should be processed
79
80 Manager
81 Responsible for enqueing and dequeing Changes
82
83 Reporter
84 Communicates success and failure results somewhere
Monty Taylora42a55b2016-07-29 07:53:33 -070085 """
James E. Blair83005782015-12-11 14:46:03 -080086 def __init__(self, name, layout):
James E. Blair4aea70c2012-07-26 14:23:24 -070087 self.name = name
James E. Blair83005782015-12-11 14:46:03 -080088 self.layout = layout
James E. Blair8dbd56a2012-12-22 10:55:10 -080089 self.description = None
James E. Blair56370192013-01-14 15:47:28 -080090 self.failure_message = None
Joshua Heskethb7179772014-01-30 23:30:46 +110091 self.merge_failure_message = None
James E. Blair56370192013-01-14 15:47:28 -080092 self.success_message = None
Joshua Hesketh3979e3e2014-03-04 11:21:10 +110093 self.footer_message = None
James E. Blair60af7f42016-03-11 16:11:06 -080094 self.start_message = None
James E. Blair2fa50962013-01-30 21:50:41 -080095 self.dequeue_on_new_patchset = True
James E. Blair17dd6772015-02-09 14:45:18 -080096 self.ignore_dependencies = False
James E. Blair4aea70c2012-07-26 14:23:24 -070097 self.job_trees = {} # project -> JobTree
98 self.manager = None
James E. Blaire0487072012-08-29 17:38:31 -070099 self.queues = []
James E. Blair64ed6f22013-07-10 14:07:23 -0700100 self.precedence = PRECEDENCE_NORMAL
James E. Blairc0dedf82014-08-06 09:37:52 -0700101 self.source = None
James E. Blair83005782015-12-11 14:46:03 -0800102 self.triggers = []
Joshua Hesketh352264b2015-08-11 23:42:08 +1000103 self.start_actions = []
104 self.success_actions = []
105 self.failure_actions = []
106 self.merge_failure_actions = []
107 self.disabled_actions = []
Joshua Hesketh89e829d2015-02-10 16:29:45 +1100108 self.disable_at = None
109 self._consecutive_failures = 0
110 self._disabled = False
Clark Boylan7603a372014-01-21 11:43:20 -0800111 self.window = None
112 self.window_floor = None
113 self.window_increase_type = None
114 self.window_increase_factor = None
115 self.window_decrease_type = None
116 self.window_decrease_factor = None
James E. Blair4aea70c2012-07-26 14:23:24 -0700117
James E. Blair83005782015-12-11 14:46:03 -0800118 @property
119 def actions(self):
120 return (
121 self.start_actions +
122 self.success_actions +
123 self.failure_actions +
124 self.merge_failure_actions +
125 self.disabled_actions
126 )
127
James E. Blaird09c17a2012-08-07 09:23:14 -0700128 def __repr__(self):
129 return '<Pipeline %s>' % self.name
130
James E. Blair4aea70c2012-07-26 14:23:24 -0700131 def setManager(self, manager):
132 self.manager = manager
133
James E. Blair4aea70c2012-07-26 14:23:24 -0700134 def getProjects(self):
Monty Taylor74fa3862016-06-02 07:39:49 +0300135 # cmp is not in python3, applied idiom from
136 # http://python-future.org/compatible_idioms.html#cmp
137 return sorted(
138 self.job_trees.keys(),
139 key=lambda p: p.name)
James E. Blair4aea70c2012-07-26 14:23:24 -0700140
James E. Blaire0487072012-08-29 17:38:31 -0700141 def addQueue(self, queue):
142 self.queues.append(queue)
143
144 def getQueue(self, project):
145 for queue in self.queues:
146 if project in queue.projects:
147 return queue
148 return None
149
James E. Blairbfb8e042014-12-30 17:01:44 -0800150 def removeQueue(self, queue):
151 self.queues.remove(queue)
152
James E. Blair4aea70c2012-07-26 14:23:24 -0700153 def getJobTree(self, project):
154 tree = self.job_trees.get(project)
155 return tree
156
James E. Blaire0487072012-08-29 17:38:31 -0700157 def getChangesInQueue(self):
158 changes = []
159 for shared_queue in self.queues:
James E. Blairfee8d652013-06-07 08:57:52 -0700160 changes.extend([x.change for x in shared_queue.queue])
James E. Blaire0487072012-08-29 17:38:31 -0700161 return changes
162
James E. Blairfee8d652013-06-07 08:57:52 -0700163 def getAllItems(self):
164 items = []
James E. Blaire0487072012-08-29 17:38:31 -0700165 for shared_queue in self.queues:
James E. Blairfee8d652013-06-07 08:57:52 -0700166 items.extend(shared_queue.queue)
James E. Blairfee8d652013-06-07 08:57:52 -0700167 return items
James E. Blaire0487072012-08-29 17:38:31 -0700168
James E. Blairb7273ef2016-04-19 08:58:51 -0700169 def formatStatusJSON(self, url_pattern=None):
James E. Blair8dbd56a2012-12-22 10:55:10 -0800170 j_pipeline = dict(name=self.name,
171 description=self.description)
172 j_queues = []
173 j_pipeline['change_queues'] = j_queues
174 for queue in self.queues:
175 j_queue = dict(name=queue.name)
176 j_queues.append(j_queue)
177 j_queue['heads'] = []
Clark Boylanaf2476f2014-01-23 14:47:36 -0800178 j_queue['window'] = queue.window
James E. Blair972e3c72013-08-29 12:04:55 -0700179
180 j_changes = []
181 for e in queue.queue:
182 if not e.item_ahead:
183 if j_changes:
184 j_queue['heads'].append(j_changes)
185 j_changes = []
James E. Blairb7273ef2016-04-19 08:58:51 -0700186 j_changes.append(e.formatJSON(url_pattern))
James E. Blair972e3c72013-08-29 12:04:55 -0700187 if (len(j_changes) > 1 and
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000188 (j_changes[-2]['remaining_time'] is not None) and
189 (j_changes[-1]['remaining_time'] is not None)):
James E. Blair972e3c72013-08-29 12:04:55 -0700190 j_changes[-1]['remaining_time'] = max(
191 j_changes[-2]['remaining_time'],
192 j_changes[-1]['remaining_time'])
193 if j_changes:
James E. Blair8dbd56a2012-12-22 10:55:10 -0800194 j_queue['heads'].append(j_changes)
195 return j_pipeline
196
James E. Blair4aea70c2012-07-26 14:23:24 -0700197
James E. Blairee743612012-05-29 14:49:32 -0700198class ChangeQueue(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700199 """A ChangeQueue contains Changes to be processed related projects.
200
Monty Taylor82dfd412016-07-29 12:01:28 -0700201 A Pipeline with a DependentPipelineManager has multiple parallel
202 ChangeQueues shared by different projects. For instance, there may a
203 ChangeQueue shared by interrelated projects foo and bar, and a second queue
204 for independent project baz.
Monty Taylora42a55b2016-07-29 07:53:33 -0700205
Monty Taylor82dfd412016-07-29 12:01:28 -0700206 A Pipeline with an IndependentPipelineManager puts every Change into its
207 own ChangeQueue
Monty Taylora42a55b2016-07-29 07:53:33 -0700208
209 The ChangeQueue Window is inspired by TCP windows and controlls how many
210 Changes in a given ChangeQueue will be considered active and ready to
211 be processed. If a Change succeeds, the Window is increased by
212 `window_increase_factor`. If a Change fails, the Window is decreased by
213 `window_decrease_factor`.
214 """
James E. Blairbfb8e042014-12-30 17:01:44 -0800215 def __init__(self, pipeline, window=0, window_floor=1,
Clark Boylan7603a372014-01-21 11:43:20 -0800216 window_increase_type='linear', window_increase_factor=1,
James E. Blair0dcef7a2016-08-19 09:35:17 -0700217 window_decrease_type='exponential', window_decrease_factor=2,
218 name=None):
James E. Blair4aea70c2012-07-26 14:23:24 -0700219 self.pipeline = pipeline
James E. Blair0dcef7a2016-08-19 09:35:17 -0700220 if name:
221 self.name = name
222 else:
223 self.name = ''
James E. Blairee743612012-05-29 14:49:32 -0700224 self.projects = []
225 self._jobs = set()
226 self.queue = []
Clark Boylan7603a372014-01-21 11:43:20 -0800227 self.window = window
228 self.window_floor = window_floor
229 self.window_increase_type = window_increase_type
230 self.window_increase_factor = window_increase_factor
231 self.window_decrease_type = window_decrease_type
232 self.window_decrease_factor = window_decrease_factor
James E. Blairee743612012-05-29 14:49:32 -0700233
James E. Blair9f9667e2012-06-12 17:51:08 -0700234 def __repr__(self):
James E. Blair4aea70c2012-07-26 14:23:24 -0700235 return '<ChangeQueue %s: %s>' % (self.pipeline.name, self.name)
James E. Blairee743612012-05-29 14:49:32 -0700236
237 def getJobs(self):
238 return self._jobs
239
240 def addProject(self, project):
241 if project not in self.projects:
242 self.projects.append(project)
James E. Blairc8a1e052014-02-25 09:29:26 -0800243
James E. Blair0dcef7a2016-08-19 09:35:17 -0700244 if not self.name:
245 self.name = project.name
James E. Blairee743612012-05-29 14:49:32 -0700246
247 def enqueueChange(self, change):
James E. Blairbfb8e042014-12-30 17:01:44 -0800248 item = QueueItem(self, change)
James E. Blaircdccd972013-07-01 12:10:22 -0700249 self.enqueueItem(item)
250 item.enqueue_time = time.time()
251 return item
252
253 def enqueueItem(self, item):
James E. Blair4a035d92014-01-23 13:10:48 -0800254 item.pipeline = self.pipeline
James E. Blairbfb8e042014-12-30 17:01:44 -0800255 item.queue = self
256 if self.queue:
James E. Blairfee8d652013-06-07 08:57:52 -0700257 item.item_ahead = self.queue[-1]
James E. Blair972e3c72013-08-29 12:04:55 -0700258 item.item_ahead.items_behind.append(item)
James E. Blairfee8d652013-06-07 08:57:52 -0700259 self.queue.append(item)
James E. Blairee743612012-05-29 14:49:32 -0700260
James E. Blairfee8d652013-06-07 08:57:52 -0700261 def dequeueItem(self, item):
262 if item in self.queue:
263 self.queue.remove(item)
James E. Blairfee8d652013-06-07 08:57:52 -0700264 if item.item_ahead:
James E. Blair972e3c72013-08-29 12:04:55 -0700265 item.item_ahead.items_behind.remove(item)
266 for item_behind in item.items_behind:
267 if item.item_ahead:
268 item.item_ahead.items_behind.append(item_behind)
269 item_behind.item_ahead = item.item_ahead
James E. Blairfee8d652013-06-07 08:57:52 -0700270 item.item_ahead = None
James E. Blair972e3c72013-08-29 12:04:55 -0700271 item.items_behind = []
James E. Blairfee8d652013-06-07 08:57:52 -0700272 item.dequeue_time = time.time()
James E. Blaire0487072012-08-29 17:38:31 -0700273
James E. Blair972e3c72013-08-29 12:04:55 -0700274 def moveItem(self, item, item_ahead):
James E. Blair972e3c72013-08-29 12:04:55 -0700275 if item.item_ahead == item_ahead:
276 return False
277 # Remove from current location
278 if item.item_ahead:
279 item.item_ahead.items_behind.remove(item)
280 for item_behind in item.items_behind:
281 if item.item_ahead:
282 item.item_ahead.items_behind.append(item_behind)
283 item_behind.item_ahead = item.item_ahead
284 # Add to new location
285 item.item_ahead = item_ahead
James E. Blair00451262013-09-20 11:40:17 -0700286 item.items_behind = []
James E. Blair972e3c72013-08-29 12:04:55 -0700287 if item.item_ahead:
288 item.item_ahead.items_behind.append(item)
289 return True
James E. Blairee743612012-05-29 14:49:32 -0700290
291 def mergeChangeQueue(self, other):
292 for project in other.projects:
293 self.addProject(project)
Clark Boylan7603a372014-01-21 11:43:20 -0800294 self.window = min(self.window, other.window)
295 # TODO merge semantics
296
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800297 def isActionable(self, item):
James E. Blairbfb8e042014-12-30 17:01:44 -0800298 if self.window:
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800299 return item in self.queue[:self.window]
Clark Boylan7603a372014-01-21 11:43:20 -0800300 else:
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800301 return True
Clark Boylan7603a372014-01-21 11:43:20 -0800302
303 def increaseWindowSize(self):
James E. Blairbfb8e042014-12-30 17:01:44 -0800304 if self.window:
Clark Boylan7603a372014-01-21 11:43:20 -0800305 if self.window_increase_type == 'linear':
306 self.window += self.window_increase_factor
307 elif self.window_increase_type == 'exponential':
308 self.window *= self.window_increase_factor
309
310 def decreaseWindowSize(self):
James E. Blairbfb8e042014-12-30 17:01:44 -0800311 if self.window:
Clark Boylan7603a372014-01-21 11:43:20 -0800312 if self.window_decrease_type == 'linear':
313 self.window = max(
314 self.window_floor,
315 self.window - self.window_decrease_factor)
316 elif self.window_decrease_type == 'exponential':
317 self.window = max(
318 self.window_floor,
Morgan Fainbergfdae2252016-06-07 20:13:20 -0700319 int(self.window / self.window_decrease_factor))
James E. Blairee743612012-05-29 14:49:32 -0700320
James E. Blair1e8dd892012-05-30 09:15:05 -0700321
James E. Blair4aea70c2012-07-26 14:23:24 -0700322class Project(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700323 """A Project represents a git repository such as openstack/nova."""
324
James E. Blaircf440a22016-07-15 09:11:58 -0700325 # NOTE: Projects should only be instantiated via a Source object
326 # so that they are associated with and cached by their Connection.
327 # This makes a Project instance a unique identifier for a given
328 # project from a given source.
329
Evgeny Antyshev0deaaad2015-08-03 20:22:56 +0000330 def __init__(self, name, foreign=False):
James E. Blair4aea70c2012-07-26 14:23:24 -0700331 self.name = name
Evgeny Antyshev0deaaad2015-08-03 20:22:56 +0000332 # foreign projects are those referenced in dependencies
333 # of layout projects, this should matter
334 # when deciding whether to enqueue their changes
James E. Blaircf440a22016-07-15 09:11:58 -0700335 # TODOv3 (jeblair): re-add support for foreign projects if needed
Evgeny Antyshev0deaaad2015-08-03 20:22:56 +0000336 self.foreign = foreign
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700337 self.unparsed_config = None
James E. Blair4aea70c2012-07-26 14:23:24 -0700338
339 def __str__(self):
340 return self.name
341
342 def __repr__(self):
343 return '<Project %s>' % (self.name)
344
345
James E. Blair34776ee2016-08-25 13:53:54 -0700346class Node(object):
James E. Blaira98340f2016-09-02 11:33:49 -0700347 """A single node for use by a job.
348
349 This may represent a request for a node, or an actual node
350 provided by Nodepool.
351 """
352
James E. Blair34776ee2016-08-25 13:53:54 -0700353 def __init__(self, name, image):
354 self.name = name
355 self.image = image
James E. Blaircbf43672017-01-04 14:33:41 -0800356 self.id = None
James E. Blaira38c28e2017-01-04 10:33:20 -0800357 self.lock = None
358 # Attributes from Nodepool
359 self._state = 'unknown'
360 self.state_time = time.time()
361 self.public_ipv4 = None
362 self.private_ipv4 = None
363 self.public_ipv6 = None
364
365 @property
366 def state(self):
367 return self._state
368
369 @state.setter
370 def state(self, value):
371 # TODOv3(jeblair): reinstate
372 # if value not in STATES:
373 # raise TypeError("'%s' is not a valid state" % value)
374 self._state = value
375 self.state_time = time.time()
James E. Blair34776ee2016-08-25 13:53:54 -0700376
377 def __repr__(self):
James E. Blaircbf43672017-01-04 14:33:41 -0800378 return '<Node %s %s:%s>' % (self.id, self.name, self.image)
James E. Blair34776ee2016-08-25 13:53:54 -0700379
James E. Blaira38c28e2017-01-04 10:33:20 -0800380 def updateFromDict(self, data):
381 self._state = data['state']
382 self.state_time = data['state_time']
383 self.public_ipv4 = data.get('public_ipv4')
384 self.private_ipv4 = data.get('private_ipv4')
385 self.public_ipv6 = data.get('public_ipv6')
386
James E. Blair34776ee2016-08-25 13:53:54 -0700387
James E. Blaira98340f2016-09-02 11:33:49 -0700388class NodeSet(object):
389 """A set of nodes.
390
391 In configuration, NodeSets are attributes of Jobs indicating that
392 a Job requires nodes matching this description.
393
394 They may appear as top-level configuration objects and be named,
395 or they may appears anonymously in in-line job definitions.
396 """
397
398 def __init__(self, name=None):
399 self.name = name or ''
400 self.nodes = OrderedDict()
401
James E. Blaircbf43672017-01-04 14:33:41 -0800402 def copy(self):
403 n = NodeSet(self.name)
404 for name, node in self.nodes.items():
405 n.addNode(Node(node.name, node.image))
406 return n
407
James E. Blaira98340f2016-09-02 11:33:49 -0700408 def addNode(self, node):
409 if node.name in self.nodes:
410 raise Exception("Duplicate node in %s" % (self,))
411 self.nodes[node.name] = node
412
James E. Blair0eaad552016-09-02 12:09:54 -0700413 def getNodes(self):
414 return self.nodes.values()
415
James E. Blaira98340f2016-09-02 11:33:49 -0700416 def __repr__(self):
417 if self.name:
418 name = self.name + ' '
419 else:
420 name = ''
421 return '<NodeSet %s%s>' % (name, self.nodes)
422
423
James E. Blair34776ee2016-08-25 13:53:54 -0700424class NodeRequest(object):
James E. Blaira98340f2016-09-02 11:33:49 -0700425 """A request for a set of nodes."""
426
James E. Blair0eaad552016-09-02 12:09:54 -0700427 def __init__(self, build_set, job, nodeset):
James E. Blair34776ee2016-08-25 13:53:54 -0700428 self.build_set = build_set
429 self.job = job
James E. Blair0eaad552016-09-02 12:09:54 -0700430 self.nodeset = nodeset
James E. Blairdce6cea2016-12-20 16:45:32 -0800431 self._state = 'requested'
432 self.state_time = time.time()
433 self.stat = None
434 self.uid = uuid4().hex
James E. Blaircbf43672017-01-04 14:33:41 -0800435 self.id = None
James E. Blaira38c28e2017-01-04 10:33:20 -0800436 # Zuul internal failure flag (not stored in ZK so it's not
437 # overwritten).
438 self.failed = False
James E. Blairdce6cea2016-12-20 16:45:32 -0800439
440 @property
441 def state(self):
442 return self._state
443
444 @state.setter
445 def state(self, value):
446 # TODOv3(jeblair): reinstate
447 # if value not in STATES:
448 # raise TypeError("'%s' is not a valid state" % value)
449 self._state = value
450 self.state_time = time.time()
James E. Blair34776ee2016-08-25 13:53:54 -0700451
452 def __repr__(self):
James E. Blaircbf43672017-01-04 14:33:41 -0800453 return '<NodeRequest %s %s>' % (self.id, self.nodeset)
James E. Blair34776ee2016-08-25 13:53:54 -0700454
James E. Blairdce6cea2016-12-20 16:45:32 -0800455 def toDict(self):
456 d = {}
457 nodes = [n.image for n in self.nodeset.getNodes()]
458 d['node_types'] = nodes
459 d['requestor'] = 'zuul' # TODOv3(jeblair): better descriptor
460 d['state'] = self.state
461 d['state_time'] = self.state_time
462 return d
463
464 def updateFromDict(self, data):
465 self._state = data['state']
466 self.state_time = data['state_time']
467
James E. Blair34776ee2016-08-25 13:53:54 -0700468
James E. Blairee743612012-05-29 14:49:32 -0700469class Job(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700470 """A Job represents the defintion of actions to perform."""
471
James E. Blair83005782015-12-11 14:46:03 -0800472 attributes = dict(
473 timeout=None,
474 # variables={},
James E. Blair0eaad552016-09-02 12:09:54 -0700475 nodeset=NodeSet(),
Ricardo Carrillo Cruz4e94f612016-07-25 16:11:56 +0000476 auth={},
James E. Blair83005782015-12-11 14:46:03 -0800477 workspace=None,
478 pre_run=None,
479 post_run=None,
480 voting=None,
James E. Blair791b5392016-08-03 11:25:56 -0700481 hold_following_changes=None,
James E. Blair83005782015-12-11 14:46:03 -0800482 failure_message=None,
483 success_message=None,
484 failure_url=None,
485 success_url=None,
486 # Matchers. These are separate so they can be individually
487 # overidden.
488 branch_matcher=None,
489 file_matcher=None,
490 irrelevant_file_matcher=None, # skip-if
Joshua Heskethdc7820c2016-03-11 13:14:28 +1100491 tags=set(),
Joshua Hesketh89b67f62016-02-11 21:22:14 +1100492 mutex=None,
Joshua Hesketh3f7def32016-11-21 17:36:44 +1100493 attempts=3,
James E. Blair83005782015-12-11 14:46:03 -0800494 )
495
James E. Blairee743612012-05-29 14:49:32 -0700496 def __init__(self, name):
497 self.name = name
James E. Blair4317e9f2016-07-15 10:05:47 -0700498 self.project_source = None
James E. Blair83005782015-12-11 14:46:03 -0800499 for k, v in self.attributes.items():
500 setattr(self, k, v)
501
Paul Belangere22baea2016-11-03 16:59:27 -0400502 def __eq__(self, other):
James E. Blair83005782015-12-11 14:46:03 -0800503 # Compare the name and all inheritable attributes to determine
504 # whether two jobs with the same name are identically
505 # configured. Useful upon reconfiguration.
506 if not isinstance(other, Job):
507 return False
508 if self.name != other.name:
509 return False
510 for k, v in self.attributes.items():
511 if getattr(self, k) != getattr(other, k):
512 return False
513 return True
James E. Blairee743612012-05-29 14:49:32 -0700514
515 def __str__(self):
516 return self.name
517
518 def __repr__(self):
James E. Blair34776ee2016-08-25 13:53:54 -0700519 return '<Job %s branches: %s>' % (self.name, self.branch_matcher)
James E. Blair83005782015-12-11 14:46:03 -0800520
521 def inheritFrom(self, other):
522 """Copy the inheritable attributes which have been set on the other
523 job to this job."""
524
525 if not isinstance(other, Job):
526 raise Exception("Job unable to inherit from %s" % (other,))
527 for k, v in self.attributes.items():
Ricardo Carrillo Cruz4e94f612016-07-25 16:11:56 +0000528 if getattr(other, k) != v and k != 'auth':
James E. Blair83005782015-12-11 14:46:03 -0800529 setattr(self, k, getattr(other, k))
Ricardo Carrillo Cruz4e94f612016-07-25 16:11:56 +0000530 # Inherit auth only if explicitly allowed
531 if other.auth and 'inherit' in other.auth and other.auth['inherit']:
532 setattr(self, 'auth', getattr(other, 'auth'))
James E. Blairee743612012-05-29 14:49:32 -0700533
James E. Blaire421a232012-07-25 16:59:21 -0700534 def changeMatches(self, change):
James E. Blair83005782015-12-11 14:46:03 -0800535 if self.branch_matcher and not self.branch_matcher.matches(change):
James E. Blair70c71582013-03-06 08:50:50 -0800536 return False
537
James E. Blair83005782015-12-11 14:46:03 -0800538 if self.file_matcher and not self.file_matcher.matches(change):
James E. Blair70c71582013-03-06 08:50:50 -0800539 return False
540
James E. Blair83005782015-12-11 14:46:03 -0800541 # NB: This is a negative match.
542 if (self.irrelevant_file_matcher and
543 self.irrelevant_file_matcher.matches(change)):
Maru Newby3fe5f852015-01-13 04:22:14 +0000544 return False
545
James E. Blair70c71582013-03-06 08:50:50 -0800546 return True
James E. Blaire5a847f2012-07-10 15:29:14 -0700547
James E. Blair1e8dd892012-05-30 09:15:05 -0700548
James E. Blairee743612012-05-29 14:49:32 -0700549class JobTree(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700550 """A JobTree holds one or more Jobs to represent Job dependencies.
551
552 If Job foo should only execute if Job bar succeeds, then there will
553 be a JobTree for foo, which will contain a JobTree for bar. A JobTree
554 can hold more than one dependent JobTrees, such that jobs bar and bang
555 both depend on job foo being successful.
556
557 A root node of a JobTree will have no associated Job."""
James E. Blairee743612012-05-29 14:49:32 -0700558
559 def __init__(self, job):
560 self.job = job
561 self.job_trees = []
562
563 def addJob(self, job):
James E. Blair12a92b12014-03-26 11:54:53 -0700564 if job not in [x.job for x in self.job_trees]:
565 t = JobTree(job)
566 self.job_trees.append(t)
567 return t
James E. Blaire4ad55a2015-06-11 08:22:43 -0700568 for tree in self.job_trees:
569 if tree.job == job:
570 return tree
James E. Blairee743612012-05-29 14:49:32 -0700571
572 def getJobs(self):
573 jobs = []
574 for x in self.job_trees:
575 jobs.append(x.job)
576 jobs.extend(x.getJobs())
577 return jobs
578
579 def getJobTreeForJob(self, job):
580 if self.job == job:
581 return self
582 for tree in self.job_trees:
583 ret = tree.getJobTreeForJob(job)
584 if ret:
585 return ret
586 return None
587
James E. Blairb97ed802015-12-21 15:55:35 -0800588 def inheritFrom(self, other):
589 if other.job:
590 self.job = Job(other.job.name)
591 self.job.inheritFrom(other.job)
592 for other_tree in other.job_trees:
593 this_tree = self.getJobTreeForJob(other_tree.job)
594 if not this_tree:
595 this_tree = JobTree(None)
596 self.job_trees.append(this_tree)
597 this_tree.inheritFrom(other_tree)
598
James E. Blair1e8dd892012-05-30 09:15:05 -0700599
James E. Blair4aea70c2012-07-26 14:23:24 -0700600class Build(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700601 """A Build is an instance of a single running Job."""
602
James E. Blair4aea70c2012-07-26 14:23:24 -0700603 def __init__(self, job, uuid):
604 self.job = job
605 self.uuid = uuid
James E. Blair4aea70c2012-07-26 14:23:24 -0700606 self.url = None
James E. Blair4aea70c2012-07-26 14:23:24 -0700607 self.result = None
608 self.build_set = None
609 self.launch_time = time.time()
James E. Blair71e94122012-12-24 17:53:08 -0800610 self.start_time = None
611 self.end_time = None
James E. Blairbea9ef12013-07-15 11:52:23 -0700612 self.estimated_time = None
James E. Blair66eeebf2013-07-27 17:44:32 -0700613 self.pipeline = None
James E. Blair0aac4872013-08-23 14:02:38 -0700614 self.canceled = False
James E. Blair4a28a882013-08-23 15:17:33 -0700615 self.retry = False
James E. Blaird78576a2013-07-09 10:39:17 -0700616 self.parameters = {}
Joshua Heskethba8776a2014-01-12 14:35:40 +0800617 self.worker = Worker()
Timothy Chavezb2332082015-08-07 20:08:04 -0500618 self.node_labels = []
619 self.node_name = None
James E. Blairee743612012-05-29 14:49:32 -0700620
621 def __repr__(self):
Joshua Heskethba8776a2014-01-12 14:35:40 +0800622 return ('<Build %s of %s on %s>' %
623 (self.uuid, self.job.name, self.worker))
624
625
626class Worker(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700627 """Information about the specific worker executing a Build."""
Joshua Heskethba8776a2014-01-12 14:35:40 +0800628 def __init__(self):
629 self.name = "Unknown"
630 self.hostname = None
631 self.ips = []
632 self.fqdn = None
633 self.program = None
634 self.version = None
635 self.extra = {}
636
637 def updateFromData(self, data):
638 """Update worker information if contained in the WORK_DATA response."""
639 self.name = data.get('worker_name', self.name)
640 self.hostname = data.get('worker_hostname', self.hostname)
641 self.ips = data.get('worker_ips', self.ips)
642 self.fqdn = data.get('worker_fqdn', self.fqdn)
643 self.program = data.get('worker_program', self.program)
644 self.version = data.get('worker_version', self.version)
645 self.extra = data.get('worker_extra', self.extra)
646
647 def __repr__(self):
648 return '<Worker %s>' % self.name
James E. Blairee743612012-05-29 14:49:32 -0700649
James E. Blair1e8dd892012-05-30 09:15:05 -0700650
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700651class RepoFiles(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700652 """RepoFiles holds config-file content for per-project job config."""
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700653 # When we ask a merger to prepare a future multiple-repo state and
654 # collect files so that we can dynamically load our configuration,
655 # this class provides easy access to that data.
656 def __init__(self):
657 self.projects = {}
658
659 def __repr__(self):
660 return '<RepoFiles %s>' % self.projects
661
662 def setFiles(self, items):
663 self.projects = {}
664 for item in items:
665 project = self.projects.setdefault(item['project'], {})
666 branch = project.setdefault(item['branch'], {})
667 branch.update(item['files'])
668
669 def getFile(self, project, branch, fn):
670 return self.projects.get(project, {}).get(branch, {}).get(fn)
671
672
James E. Blair7e530ad2012-07-03 16:12:28 -0700673class BuildSet(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700674 """Contains the Builds for a Change representing potential future state.
675
676 A BuildSet also holds the UUID used to produce the Zuul Ref that builders
677 check out.
678 """
James E. Blair4076e2b2014-01-28 12:42:20 -0800679 # Merge states:
680 NEW = 1
681 PENDING = 2
682 COMPLETE = 3
683
Antoine Musso9b229282014-08-18 23:45:43 +0200684 states_map = {
685 1: 'NEW',
686 2: 'PENDING',
687 3: 'COMPLETE',
688 }
689
James E. Blairfee8d652013-06-07 08:57:52 -0700690 def __init__(self, item):
691 self.item = item
James E. Blair11700c32012-07-05 17:50:05 -0700692 self.other_changes = []
James E. Blair7e530ad2012-07-03 16:12:28 -0700693 self.builds = {}
James E. Blair11700c32012-07-05 17:50:05 -0700694 self.result = None
695 self.next_build_set = None
696 self.previous_build_set = None
James E. Blair4886cc12012-07-18 15:39:41 -0700697 self.ref = None
James E. Blair81515ad2012-10-01 18:29:08 -0700698 self.commit = None
James E. Blair4076e2b2014-01-28 12:42:20 -0800699 self.zuul_url = None
James E. Blair973721f2012-08-15 10:19:43 -0700700 self.unable_to_merge = False
James E. Blair972e3c72013-08-29 12:04:55 -0700701 self.failing_reasons = []
James E. Blair4076e2b2014-01-28 12:42:20 -0800702 self.merge_state = self.NEW
James E. Blair0eaad552016-09-02 12:09:54 -0700703 self.nodesets = {} # job -> nodeset
James E. Blair8d692392016-04-08 17:47:58 -0700704 self.node_requests = {} # job -> reqs
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700705 self.files = RepoFiles()
706 self.layout = None
Paul Belanger71d98172016-11-08 10:56:31 -0500707 self.tries = {}
James E. Blair7e530ad2012-07-03 16:12:28 -0700708
Antoine Musso9b229282014-08-18 23:45:43 +0200709 def __repr__(self):
710 return '<BuildSet item: %s #builds: %s merge state: %s>' % (
711 self.item,
712 len(self.builds),
713 self.getStateName(self.merge_state))
714
James E. Blair4886cc12012-07-18 15:39:41 -0700715 def setConfiguration(self):
James E. Blair11700c32012-07-05 17:50:05 -0700716 # The change isn't enqueued until after it's created
717 # so we don't know what the other changes ahead will be
718 # until jobs start.
719 if not self.other_changes:
James E. Blairfee8d652013-06-07 08:57:52 -0700720 next_item = self.item.item_ahead
721 while next_item:
722 self.other_changes.append(next_item.change)
723 next_item = next_item.item_ahead
James E. Blair4886cc12012-07-18 15:39:41 -0700724 if not self.ref:
725 self.ref = 'Z' + uuid4().hex
726
Antoine Musso9b229282014-08-18 23:45:43 +0200727 def getStateName(self, state_num):
728 return self.states_map.get(
729 state_num, 'UNKNOWN (%s)' % state_num)
730
James E. Blair4886cc12012-07-18 15:39:41 -0700731 def addBuild(self, build):
732 self.builds[build.job.name] = build
Paul Belanger71d98172016-11-08 10:56:31 -0500733 if build.job.name not in self.tries:
Clint Byrum5bb5feb2016-12-08 12:39:05 -0800734 self.tries[build.job.name] = 0
James E. Blair4886cc12012-07-18 15:39:41 -0700735 build.build_set = self
James E. Blair11700c32012-07-05 17:50:05 -0700736
James E. Blair4a28a882013-08-23 15:17:33 -0700737 def removeBuild(self, build):
Paul Belanger71d98172016-11-08 10:56:31 -0500738 self.tries[build.job.name] += 1
James E. Blair4a28a882013-08-23 15:17:33 -0700739 del self.builds[build.job.name]
740
James E. Blair7e530ad2012-07-03 16:12:28 -0700741 def getBuild(self, job_name):
742 return self.builds.get(job_name)
743
James E. Blair11700c32012-07-05 17:50:05 -0700744 def getBuilds(self):
745 keys = self.builds.keys()
746 keys.sort()
747 return [self.builds.get(x) for x in keys]
748
James E. Blair0eaad552016-09-02 12:09:54 -0700749 def getJobNodeSet(self, job_name):
750 # Return None if not provisioned; empty NodeSet if no nodes
751 # required
752 return self.nodesets.get(job_name)
James E. Blair8d692392016-04-08 17:47:58 -0700753
754 def setJobNodeRequest(self, job_name, req):
755 if job_name in self.node_requests:
756 raise Exception("Prior node request for %s" % (job_name))
757 self.node_requests[job_name] = req
758
759 def getJobNodeRequest(self, job_name):
760 return self.node_requests.get(job_name)
761
James E. Blair0eaad552016-09-02 12:09:54 -0700762 def jobNodeRequestComplete(self, job_name, req, nodeset):
763 if job_name in self.nodesets:
James E. Blair8d692392016-04-08 17:47:58 -0700764 raise Exception("Prior node request for %s" % (job_name))
James E. Blair0eaad552016-09-02 12:09:54 -0700765 self.nodesets[job_name] = nodeset
James E. Blair8d692392016-04-08 17:47:58 -0700766 del self.node_requests[job_name]
767
Paul Belanger71d98172016-11-08 10:56:31 -0500768 def getTries(self, job_name):
769 return self.tries.get(job_name)
770
Adam Gandelman8bd57102016-12-02 12:58:42 -0800771 def getMergeMode(self, job_name):
772 if not self.layout or job_name not in self.layout.project_configs:
773 return MERGER_MERGE_RESOLVE
774 return self.layout.project_configs[job_name].merge_mode
775
James E. Blair7e530ad2012-07-03 16:12:28 -0700776
James E. Blairfee8d652013-06-07 08:57:52 -0700777class QueueItem(object):
Monty Taylora42a55b2016-07-29 07:53:33 -0700778 """Represents the position of a Change in a ChangeQueue.
779
780 All Changes are enqueued into ChangeQueue in a QueueItem. The QueueItem
781 holds the current `BuildSet` as well as all previous `BuildSets` that were
782 produced for this `QueueItem`.
783 """
James E. Blair32663402012-06-01 10:04:18 -0700784
James E. Blairbfb8e042014-12-30 17:01:44 -0800785 def __init__(self, queue, change):
786 self.pipeline = queue.pipeline
787 self.queue = queue
James E. Blairfee8d652013-06-07 08:57:52 -0700788 self.change = change # a changeish
James E. Blair7e530ad2012-07-03 16:12:28 -0700789 self.build_sets = []
James E. Blaircaec0c52012-08-22 14:52:22 -0700790 self.dequeued_needing_change = False
James E. Blair11700c32012-07-05 17:50:05 -0700791 self.current_build_set = BuildSet(self)
792 self.build_sets.append(self.current_build_set)
James E. Blairfee8d652013-06-07 08:57:52 -0700793 self.item_ahead = None
James E. Blair972e3c72013-08-29 12:04:55 -0700794 self.items_behind = []
James E. Blair8fa16972013-01-15 16:57:20 -0800795 self.enqueue_time = None
796 self.dequeue_time = None
James E. Blairfee8d652013-06-07 08:57:52 -0700797 self.reported = False
James E. Blairbfb8e042014-12-30 17:01:44 -0800798 self.active = False # Whether an item is within an active window
799 self.live = True # Whether an item is intended to be processed at all
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700800 self.layout = None # This item's shadow layout
James E. Blair83005782015-12-11 14:46:03 -0800801 self.job_tree = None
James E. Blaire5a847f2012-07-10 15:29:14 -0700802
James E. Blair972e3c72013-08-29 12:04:55 -0700803 def __repr__(self):
804 if self.pipeline:
805 pipeline = self.pipeline.name
806 else:
807 pipeline = None
808 return '<QueueItem 0x%x for %s in %s>' % (
809 id(self), self.change, pipeline)
810
James E. Blairee743612012-05-29 14:49:32 -0700811 def resetAllBuilds(self):
James E. Blair11700c32012-07-05 17:50:05 -0700812 old = self.current_build_set
813 self.current_build_set.result = 'CANCELED'
814 self.current_build_set = BuildSet(self)
815 old.next_build_set = self.current_build_set
816 self.current_build_set.previous_build_set = old
James E. Blair7e530ad2012-07-03 16:12:28 -0700817 self.build_sets.append(self.current_build_set)
James E. Blairee743612012-05-29 14:49:32 -0700818
819 def addBuild(self, build):
James E. Blair7e530ad2012-07-03 16:12:28 -0700820 self.current_build_set.addBuild(build)
James E. Blair66eeebf2013-07-27 17:44:32 -0700821 build.pipeline = self.pipeline
James E. Blairee743612012-05-29 14:49:32 -0700822
James E. Blair4a28a882013-08-23 15:17:33 -0700823 def removeBuild(self, build):
824 self.current_build_set.removeBuild(build)
825
James E. Blairfee8d652013-06-07 08:57:52 -0700826 def setReportedResult(self, result):
827 self.current_build_set.result = result
828
James E. Blair83005782015-12-11 14:46:03 -0800829 def freezeJobTree(self):
830 """Find or create actual matching jobs for this item's change and
831 store the resulting job tree."""
James E. Blair8b1dc3f2016-07-05 16:49:00 -0700832 layout = self.current_build_set.layout
833 self.job_tree = layout.createJobTree(self)
834
835 def hasJobTree(self):
836 """Returns True if the item has a job tree."""
837 return self.job_tree is not None
James E. Blair83005782015-12-11 14:46:03 -0800838
839 def getJobs(self):
840 if not self.live or not self.job_tree:
841 return []
842 return self.job_tree.getJobs()
843
James E. Blairdbfd3282016-07-21 10:46:19 -0700844 def haveAllJobsStarted(self):
845 if not self.hasJobTree():
846 return False
847 for job in self.getJobs():
848 build = self.current_build_set.getBuild(job.name)
849 if not build or not build.start_time:
850 return False
851 return True
852
853 def areAllJobsComplete(self):
854 if not self.hasJobTree():
855 return False
856 for job in self.getJobs():
857 build = self.current_build_set.getBuild(job.name)
858 if not build or not build.result:
859 return False
860 return True
861
862 def didAllJobsSucceed(self):
863 if not self.hasJobTree():
864 return False
865 for job in self.getJobs():
866 if not job.voting:
867 continue
868 build = self.current_build_set.getBuild(job.name)
869 if not build:
870 return False
871 if build.result != 'SUCCESS':
872 return False
873 return True
874
875 def didAnyJobFail(self):
876 if not self.hasJobTree():
877 return False
878 for job in self.getJobs():
879 if not job.voting:
880 continue
881 build = self.current_build_set.getBuild(job.name)
882 if build and build.result and (build.result != 'SUCCESS'):
883 return True
884 return False
885
886 def didMergerFail(self):
887 if self.current_build_set.unable_to_merge:
888 return True
889 return False
890
James E. Blairdbfd3282016-07-21 10:46:19 -0700891 def isHoldingFollowingChanges(self):
892 if not self.live:
893 return False
894 if not self.hasJobTree():
895 return False
896 for job in self.getJobs():
897 if not job.hold_following_changes:
898 continue
899 build = self.current_build_set.getBuild(job.name)
900 if not build:
901 return True
902 if build.result != 'SUCCESS':
903 return True
904
905 if not self.item_ahead:
906 return False
907 return self.item_ahead.isHoldingFollowingChanges()
908
909 def _findJobsToRun(self, job_trees, mutex):
910 torun = []
James E. Blair791b5392016-08-03 11:25:56 -0700911 if self.item_ahead:
912 # Only run jobs if any 'hold' jobs on the change ahead
913 # have completed successfully.
914 if self.item_ahead.isHoldingFollowingChanges():
915 return []
James E. Blairdbfd3282016-07-21 10:46:19 -0700916 for tree in job_trees:
917 job = tree.job
918 result = None
919 if job:
920 if not job.changeMatches(self.change):
921 continue
922 build = self.current_build_set.getBuild(job.name)
923 if build:
924 result = build.result
925 else:
926 # There is no build for the root of this job tree,
James E. Blair34776ee2016-08-25 13:53:54 -0700927 # so it has not run yet.
James E. Blair0eaad552016-09-02 12:09:54 -0700928 nodeset = self.current_build_set.getJobNodeSet(job.name)
929 if nodeset is None:
James E. Blair34776ee2016-08-25 13:53:54 -0700930 # The nodes for this job are not ready, skip
931 # it for now.
932 continue
James E. Blairdbfd3282016-07-21 10:46:19 -0700933 if mutex.acquire(self, job):
934 # If this job needs a mutex, either acquire it or make
935 # sure that we have it before running the job.
936 torun.append(job)
937 # If there is no job, this is a null job tree, and we should
938 # run all of its jobs.
939 if result == 'SUCCESS' or not job:
940 torun.extend(self._findJobsToRun(tree.job_trees, mutex))
941 return torun
942
943 def findJobsToRun(self, mutex):
944 if not self.live:
945 return []
946 tree = self.job_tree
947 if not tree:
948 return []
949 return self._findJobsToRun(tree.job_trees, mutex)
950
951 def _findJobsToRequest(self, job_trees):
952 toreq = []
953 for tree in job_trees:
954 job = tree.job
955 if job:
956 if not job.changeMatches(self.change):
957 continue
James E. Blair0eaad552016-09-02 12:09:54 -0700958 nodeset = self.current_build_set.getJobNodeSet(job.name)
959 if nodeset is None:
James E. Blairdbfd3282016-07-21 10:46:19 -0700960 req = self.current_build_set.getJobNodeRequest(job.name)
961 if req is None:
962 toreq.append(job)
James E. Blair34776ee2016-08-25 13:53:54 -0700963 toreq.extend(self._findJobsToRequest(tree.job_trees))
James E. Blairdbfd3282016-07-21 10:46:19 -0700964 return toreq
965
966 def findJobsToRequest(self):
967 if not self.live:
968 return []
969 tree = self.job_tree
970 if not tree:
971 return []
972 return self._findJobsToRequest(tree.job_trees)
973
974 def setResult(self, build):
975 if build.retry:
976 self.removeBuild(build)
977 elif build.result != 'SUCCESS':
978 # Get a JobTree from a Job so we can find only its dependent jobs
979 tree = self.job_tree.getJobTreeForJob(build.job)
980 for job in tree.getJobs():
981 fakebuild = Build(job, None)
982 fakebuild.result = 'SKIPPED'
983 self.addBuild(fakebuild)
984
985 def setDequeuedNeedingChange(self):
986 self.dequeued_needing_change = True
987 self._setAllJobsSkipped()
988
989 def setUnableToMerge(self):
990 self.current_build_set.unable_to_merge = True
991 self._setAllJobsSkipped()
992
993 def _setAllJobsSkipped(self):
994 for job in self.getJobs():
995 fakebuild = Build(job, None)
996 fakebuild.result = 'SKIPPED'
997 self.addBuild(fakebuild)
998
James E. Blairb7273ef2016-04-19 08:58:51 -0700999 def formatJobResult(self, job, url_pattern=None):
1000 build = self.current_build_set.getBuild(job.name)
1001 result = build.result
1002 pattern = url_pattern
1003 if result == 'SUCCESS':
1004 if job.success_message:
1005 result = job.success_message
James E. Blaira5dba232016-08-08 15:53:24 -07001006 if job.success_url:
1007 pattern = job.success_url
James E. Blairb7273ef2016-04-19 08:58:51 -07001008 elif result == 'FAILURE':
1009 if job.failure_message:
1010 result = job.failure_message
James E. Blaira5dba232016-08-08 15:53:24 -07001011 if job.failure_url:
1012 pattern = job.failure_url
James E. Blairb7273ef2016-04-19 08:58:51 -07001013 url = None
1014 if pattern:
1015 try:
1016 url = pattern.format(change=self.change,
1017 pipeline=self.pipeline,
1018 job=job,
1019 build=build)
1020 except Exception:
1021 pass # FIXME: log this or something?
1022 if not url:
1023 url = build.url or job.name
1024 return (result, url)
1025
1026 def formatJSON(self, url_pattern=None):
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001027 changeish = self.change
1028 ret = {}
1029 ret['active'] = self.active
James E. Blair107c3852015-02-07 08:23:10 -08001030 ret['live'] = self.live
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001031 if hasattr(changeish, 'url') and changeish.url is not None:
1032 ret['url'] = changeish.url
1033 else:
1034 ret['url'] = None
1035 ret['id'] = changeish._id()
1036 if self.item_ahead:
1037 ret['item_ahead'] = self.item_ahead.change._id()
1038 else:
1039 ret['item_ahead'] = None
1040 ret['items_behind'] = [i.change._id() for i in self.items_behind]
1041 ret['failing_reasons'] = self.current_build_set.failing_reasons
1042 ret['zuul_ref'] = self.current_build_set.ref
Ramy Asselin07cc33c2015-06-12 14:06:34 -07001043 if changeish.project:
1044 ret['project'] = changeish.project.name
1045 else:
1046 # For cross-project dependencies with the depends-on
1047 # project not known to zuul, the project is None
1048 # Set it to a static value
1049 ret['project'] = "Unknown Project"
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001050 ret['enqueue_time'] = int(self.enqueue_time * 1000)
1051 ret['jobs'] = []
Davanum Srinivasb6bfbcc2014-11-18 13:26:52 -05001052 if hasattr(changeish, 'owner'):
1053 ret['owner'] = changeish.owner
1054 else:
1055 ret['owner'] = None
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001056 max_remaining = 0
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001057 for job in self.getJobs():
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001058 now = time.time()
1059 build = self.current_build_set.getBuild(job.name)
1060 elapsed = None
1061 remaining = None
1062 result = None
James E. Blairb7273ef2016-04-19 08:58:51 -07001063 build_url = None
1064 report_url = None
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001065 worker = None
1066 if build:
1067 result = build.result
James E. Blairb7273ef2016-04-19 08:58:51 -07001068 build_url = build.url
1069 (unused, report_url) = self.formatJobResult(job, url_pattern)
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001070 if build.start_time:
1071 if build.end_time:
1072 elapsed = int((build.end_time -
1073 build.start_time) * 1000)
1074 remaining = 0
1075 else:
1076 elapsed = int((now - build.start_time) * 1000)
1077 if build.estimated_time:
1078 remaining = max(
1079 int(build.estimated_time * 1000) - elapsed,
1080 0)
1081 worker = {
1082 'name': build.worker.name,
1083 'hostname': build.worker.hostname,
1084 'ips': build.worker.ips,
1085 'fqdn': build.worker.fqdn,
1086 'program': build.worker.program,
1087 'version': build.worker.version,
1088 'extra': build.worker.extra
1089 }
1090 if remaining and remaining > max_remaining:
1091 max_remaining = remaining
1092
1093 ret['jobs'].append({
1094 'name': job.name,
1095 'elapsed_time': elapsed,
1096 'remaining_time': remaining,
James E. Blairb7273ef2016-04-19 08:58:51 -07001097 'url': build_url,
1098 'report_url': report_url,
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001099 'result': result,
1100 'voting': job.voting,
1101 'uuid': build.uuid if build else None,
1102 'launch_time': build.launch_time if build else None,
1103 'start_time': build.start_time if build else None,
1104 'end_time': build.end_time if build else None,
1105 'estimated_time': build.estimated_time if build else None,
1106 'pipeline': build.pipeline.name if build else None,
1107 'canceled': build.canceled if build else None,
1108 'retry': build.retry if build else None,
Timothy Chavezb2332082015-08-07 20:08:04 -05001109 'node_labels': build.node_labels if build else [],
1110 'node_name': build.node_name if build else None,
1111 'worker': worker,
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001112 })
1113
James E. Blairdbfd3282016-07-21 10:46:19 -07001114 if self.haveAllJobsStarted():
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001115 ret['remaining_time'] = max_remaining
1116 else:
1117 ret['remaining_time'] = None
1118 return ret
1119
1120 def formatStatus(self, indent=0, html=False):
1121 changeish = self.change
1122 indent_str = ' ' * indent
1123 ret = ''
1124 if html and hasattr(changeish, 'url') and changeish.url is not None:
1125 ret += '%sProject %s change <a href="%s">%s</a>\n' % (
1126 indent_str,
1127 changeish.project.name,
1128 changeish.url,
1129 changeish._id())
1130 else:
1131 ret += '%sProject %s change %s based on %s\n' % (
1132 indent_str,
1133 changeish.project.name,
1134 changeish._id(),
1135 self.item_ahead)
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001136 for job in self.getJobs():
Joshua Hesketh85af4e92014-02-21 08:28:58 -08001137 build = self.current_build_set.getBuild(job.name)
1138 if build:
1139 result = build.result
1140 else:
1141 result = None
1142 job_name = job.name
1143 if not job.voting:
1144 voting = ' (non-voting)'
1145 else:
1146 voting = ''
1147 if html:
1148 if build:
1149 url = build.url
1150 else:
1151 url = None
1152 if url is not None:
1153 job_name = '<a href="%s">%s</a>' % (url, job_name)
1154 ret += '%s %s: %s%s' % (indent_str, job_name, result, voting)
1155 ret += '\n'
1156 return ret
1157
James E. Blairfee8d652013-06-07 08:57:52 -07001158
1159class Changeish(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001160 """Base class for Change and Ref."""
James E. Blairfee8d652013-06-07 08:57:52 -07001161
1162 def __init__(self, project):
1163 self.project = project
1164
Joshua Hesketh36c3fa52014-01-22 11:40:52 +11001165 def getBasePath(self):
1166 base_path = ''
1167 if hasattr(self, 'refspec'):
1168 base_path = "%s/%s/%s" % (
1169 self.number[-2:], self.number, self.patchset)
1170 elif hasattr(self, 'ref'):
1171 base_path = "%s/%s" % (self.newrev[:2], self.newrev)
1172
1173 return base_path
1174
James E. Blairfee8d652013-06-07 08:57:52 -07001175 def equals(self, other):
1176 raise NotImplementedError()
1177
1178 def isUpdateOf(self, other):
1179 raise NotImplementedError()
1180
1181 def filterJobs(self, jobs):
1182 return filter(lambda job: job.changeMatches(self), jobs)
1183
1184 def getRelatedChanges(self):
1185 return set()
1186
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001187 def updatesConfig(self):
1188 return False
1189
James E. Blair1e8dd892012-05-30 09:15:05 -07001190
James E. Blair4aea70c2012-07-26 14:23:24 -07001191class Change(Changeish):
Monty Taylora42a55b2016-07-29 07:53:33 -07001192 """A proposed new state for a Project."""
James E. Blair4aea70c2012-07-26 14:23:24 -07001193 def __init__(self, project):
1194 super(Change, self).__init__(project)
1195 self.branch = None
1196 self.number = None
1197 self.url = None
1198 self.patchset = None
1199 self.refspec = None
1200
James E. Blair70c71582013-03-06 08:50:50 -08001201 self.files = []
James E. Blair6965a4b2014-12-16 17:19:04 -08001202 self.needs_changes = []
James E. Blair4aea70c2012-07-26 14:23:24 -07001203 self.needed_by_changes = []
1204 self.is_current_patchset = True
1205 self.can_merge = False
1206 self.is_merged = False
James E. Blairfee8d652013-06-07 08:57:52 -07001207 self.failed_to_merge = False
James E. Blairc053d022014-01-22 14:57:33 -08001208 self.approvals = []
James E. Blair11041d22014-05-02 14:49:53 -07001209 self.open = None
1210 self.status = None
Davanum Srinivasb6bfbcc2014-11-18 13:26:52 -05001211 self.owner = None
James E. Blair4aea70c2012-07-26 14:23:24 -07001212
1213 def _id(self):
James E. Blairbe765db2012-08-07 08:36:20 -07001214 return '%s,%s' % (self.number, self.patchset)
James E. Blair4aea70c2012-07-26 14:23:24 -07001215
1216 def __repr__(self):
1217 return '<Change 0x%x %s>' % (id(self), self._id())
1218
1219 def equals(self, other):
Zhongyue Luoaa85ebf2012-09-21 16:38:33 +08001220 if self.number == other.number and self.patchset == other.patchset:
James E. Blair4aea70c2012-07-26 14:23:24 -07001221 return True
1222 return False
1223
James E. Blair2fa50962013-01-30 21:50:41 -08001224 def isUpdateOf(self, other):
Clark Boylan01976242013-02-17 18:41:48 -08001225 if ((hasattr(other, 'number') and self.number == other.number) and
James E. Blair7a192e42013-07-11 14:10:36 -07001226 (hasattr(other, 'patchset') and
1227 self.patchset is not None and
1228 other.patchset is not None and
1229 int(self.patchset) > int(other.patchset))):
James E. Blair2fa50962013-01-30 21:50:41 -08001230 return True
1231 return False
1232
James E. Blairfee8d652013-06-07 08:57:52 -07001233 def getRelatedChanges(self):
1234 related = set()
James E. Blair6965a4b2014-12-16 17:19:04 -08001235 for c in self.needs_changes:
1236 related.add(c)
James E. Blairfee8d652013-06-07 08:57:52 -07001237 for c in self.needed_by_changes:
1238 related.add(c)
1239 related.update(c.getRelatedChanges())
1240 return related
James E. Blair4aea70c2012-07-26 14:23:24 -07001241
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001242 def updatesConfig(self):
1243 if 'zuul.yaml' in self.files or '.zuul.yaml' in self.files:
1244 return True
1245 return False
1246
James E. Blair4aea70c2012-07-26 14:23:24 -07001247
1248class Ref(Changeish):
Monty Taylora42a55b2016-07-29 07:53:33 -07001249 """An existing state of a Project."""
James E. Blair4aea70c2012-07-26 14:23:24 -07001250 def __init__(self, project):
James E. Blairbe765db2012-08-07 08:36:20 -07001251 super(Ref, self).__init__(project)
James E. Blair4aea70c2012-07-26 14:23:24 -07001252 self.ref = None
1253 self.oldrev = None
1254 self.newrev = None
1255
James E. Blairbe765db2012-08-07 08:36:20 -07001256 def _id(self):
1257 return self.newrev
1258
Antoine Musso68bdcd72013-01-17 12:31:28 +01001259 def __repr__(self):
1260 rep = None
1261 if self.newrev == '0000000000000000000000000000000000000000':
1262 rep = '<Ref 0x%x deletes %s from %s' % (
1263 id(self), self.ref, self.oldrev)
1264 elif self.oldrev == '0000000000000000000000000000000000000000':
1265 rep = '<Ref 0x%x creates %s on %s>' % (
1266 id(self), self.ref, self.newrev)
1267 else:
1268 # Catch all
1269 rep = '<Ref 0x%x %s updated %s..%s>' % (
1270 id(self), self.ref, self.oldrev, self.newrev)
1271
1272 return rep
1273
James E. Blair4aea70c2012-07-26 14:23:24 -07001274 def equals(self, other):
James E. Blair9358c612012-09-28 08:29:39 -07001275 if (self.project == other.project
1276 and self.ref == other.ref
1277 and self.newrev == other.newrev):
James E. Blair4aea70c2012-07-26 14:23:24 -07001278 return True
1279 return False
1280
James E. Blair2fa50962013-01-30 21:50:41 -08001281 def isUpdateOf(self, other):
1282 return False
1283
James E. Blair4aea70c2012-07-26 14:23:24 -07001284
James E. Blair63bb0ef2013-07-29 17:14:51 -07001285class NullChange(Changeish):
James E. Blair23161912016-07-28 15:42:14 -07001286 # TODOv3(jeblair): remove this in favor of enqueueing Refs (eg
1287 # current master) instead.
James E. Blaire5910202013-12-27 09:50:31 -08001288 def __repr__(self):
1289 return '<NullChange for %s>' % (self.project)
James E. Blair63bb0ef2013-07-29 17:14:51 -07001290
James E. Blair63bb0ef2013-07-29 17:14:51 -07001291 def _id(self):
Alex Gaynorddb9ef32013-09-16 21:04:58 -07001292 return None
James E. Blair63bb0ef2013-07-29 17:14:51 -07001293
1294 def equals(self, other):
Steve Varnau7b78b312015-04-03 14:49:46 -07001295 if (self.project == other.project
1296 and other._id() is None):
James E. Blair4f6033c2014-03-27 15:49:09 -07001297 return True
James E. Blair63bb0ef2013-07-29 17:14:51 -07001298 return False
1299
1300 def isUpdateOf(self, other):
1301 return False
1302
1303
James E. Blairee743612012-05-29 14:49:32 -07001304class TriggerEvent(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001305 """Incoming event from an external system."""
James E. Blairee743612012-05-29 14:49:32 -07001306 def __init__(self):
1307 self.data = None
James E. Blair32663402012-06-01 10:04:18 -07001308 # common
James E. Blairee743612012-05-29 14:49:32 -07001309 self.type = None
Paul Belangerbaca3132016-11-04 12:49:54 -04001310 # For management events (eg: enqueue / promote)
1311 self.tenant_name = None
James E. Blairee743612012-05-29 14:49:32 -07001312 self.project_name = None
James E. Blair6c358e72013-07-29 17:06:47 -07001313 self.trigger_name = None
Antoine Mussob4e809e2012-12-06 16:58:06 +01001314 # Representation of the user account that performed the event.
1315 self.account = None
James E. Blair32663402012-06-01 10:04:18 -07001316 # patchset-created, comment-added, etc.
James E. Blairee743612012-05-29 14:49:32 -07001317 self.change_number = None
Clark Boylanfc56df32012-06-28 15:25:57 -07001318 self.change_url = None
James E. Blairee743612012-05-29 14:49:32 -07001319 self.patch_number = None
James E. Blaira03262c2012-05-30 09:41:16 -07001320 self.refspec = None
James E. Blairee743612012-05-29 14:49:32 -07001321 self.approvals = []
1322 self.branch = None
Clark Boylanb9bcb402012-06-29 17:44:05 -07001323 self.comment = None
James E. Blair32663402012-06-01 10:04:18 -07001324 # ref-updated
James E. Blairee743612012-05-29 14:49:32 -07001325 self.ref = None
James E. Blair32663402012-06-01 10:04:18 -07001326 self.oldrev = None
James E. Blair89cae0f2012-07-18 11:18:32 -07001327 self.newrev = None
James E. Blair63bb0ef2013-07-29 17:14:51 -07001328 # timer
1329 self.timespec = None
James E. Blairc494d542014-08-06 09:23:52 -07001330 # zuultrigger
1331 self.pipeline_name = None
James E. Blairad28e912013-11-27 10:43:22 -08001332 # For events that arrive with a destination pipeline (eg, from
1333 # an admin command, etc):
1334 self.forced_pipeline = None
James E. Blairee743612012-05-29 14:49:32 -07001335
James E. Blair9f9667e2012-06-12 17:51:08 -07001336 def __repr__(self):
James E. Blairee743612012-05-29 14:49:32 -07001337 ret = '<TriggerEvent %s %s' % (self.type, self.project_name)
James E. Blair1e8dd892012-05-30 09:15:05 -07001338
James E. Blairee743612012-05-29 14:49:32 -07001339 if self.branch:
1340 ret += " %s" % self.branch
1341 if self.change_number:
1342 ret += " %s,%s" % (self.change_number, self.patch_number)
1343 if self.approvals:
James E. Blair1e8dd892012-05-30 09:15:05 -07001344 ret += ' ' + ', '.join(
1345 ['%s:%s' % (a['type'], a['value']) for a in self.approvals])
James E. Blairee743612012-05-29 14:49:32 -07001346 ret += '>'
1347
1348 return ret
1349
James E. Blair1e8dd892012-05-30 09:15:05 -07001350
James E. Blair9c17dbf2014-06-23 14:21:58 -07001351class BaseFilter(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001352 """Base Class for filtering which Changes and Events to process."""
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001353 def __init__(self, required_approvals=[], reject_approvals=[]):
James E. Blair5bf78a32015-07-30 18:08:24 +00001354 self._required_approvals = copy.deepcopy(required_approvals)
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001355 self.required_approvals = self._tidy_approvals(required_approvals)
1356 self._reject_approvals = copy.deepcopy(reject_approvals)
1357 self.reject_approvals = self._tidy_approvals(reject_approvals)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001358
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001359 def _tidy_approvals(self, approvals):
1360 for a in approvals:
James E. Blair9c17dbf2014-06-23 14:21:58 -07001361 for k, v in a.items():
1362 if k == 'username':
James E. Blairb01ec542016-06-16 09:46:49 -07001363 a['username'] = re.compile(v)
James E. Blair1fbfceb2014-06-23 14:42:53 -07001364 elif k in ['email', 'email-filter']:
James E. Blair5bf78a32015-07-30 18:08:24 +00001365 a['email'] = re.compile(v)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001366 elif k == 'newer-than':
James E. Blair5bf78a32015-07-30 18:08:24 +00001367 a[k] = time_to_seconds(v)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001368 elif k == 'older-than':
James E. Blair5bf78a32015-07-30 18:08:24 +00001369 a[k] = time_to_seconds(v)
James E. Blair1fbfceb2014-06-23 14:42:53 -07001370 if 'email-filter' in a:
1371 del a['email-filter']
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001372 return approvals
1373
1374 def _match_approval_required_approval(self, rapproval, approval):
1375 # Check if the required approval and approval match
1376 if 'description' not in approval:
1377 return False
1378 now = time.time()
1379 by = approval.get('by', {})
1380 for k, v in rapproval.items():
1381 if k == 'username':
James E. Blairb01ec542016-06-16 09:46:49 -07001382 if (not v.search(by.get('username', ''))):
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001383 return False
1384 elif k == 'email':
1385 if (not v.search(by.get('email', ''))):
1386 return False
1387 elif k == 'newer-than':
1388 t = now - v
1389 if (approval['grantedOn'] < t):
1390 return False
1391 elif k == 'older-than':
1392 t = now - v
1393 if (approval['grantedOn'] >= t):
1394 return False
1395 else:
1396 if not isinstance(v, list):
1397 v = [v]
1398 if (normalizeCategory(approval['description']) != k or
1399 int(approval['value']) not in v):
1400 return False
1401 return True
1402
1403 def matchesApprovals(self, change):
1404 if (self.required_approvals and not change.approvals
1405 or self.reject_approvals and not change.approvals):
1406 # A change with no approvals can not match
1407 return False
1408
1409 # TODO(jhesketh): If we wanted to optimise this slightly we could
1410 # analyse both the REQUIRE and REJECT filters by looping over the
1411 # approvals on the change and keeping track of what we have checked
1412 # rather than needing to loop on the change approvals twice
1413 return (self.matchesRequiredApprovals(change) and
1414 self.matchesNoRejectApprovals(change))
James E. Blair9c17dbf2014-06-23 14:21:58 -07001415
1416 def matchesRequiredApprovals(self, change):
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001417 # Check if any approvals match the requirements
James E. Blair5bf78a32015-07-30 18:08:24 +00001418 for rapproval in self.required_approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001419 matches_rapproval = False
James E. Blair9c17dbf2014-06-23 14:21:58 -07001420 for approval in change.approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001421 if self._match_approval_required_approval(rapproval, approval):
1422 # We have a matching approval so this requirement is
1423 # fulfilled
1424 matches_rapproval = True
James E. Blair5bf78a32015-07-30 18:08:24 +00001425 break
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001426 if not matches_rapproval:
James E. Blair5bf78a32015-07-30 18:08:24 +00001427 return False
James E. Blair9c17dbf2014-06-23 14:21:58 -07001428 return True
1429
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001430 def matchesNoRejectApprovals(self, change):
1431 # Check to make sure no approvals match a reject criteria
1432 for rapproval in self.reject_approvals:
1433 for approval in change.approvals:
1434 if self._match_approval_required_approval(rapproval, approval):
1435 # A reject approval has been matched, so we reject
1436 # immediately
1437 return False
1438 # To get here no rejects can have been matched so we should be good to
1439 # queue
1440 return True
1441
James E. Blair9c17dbf2014-06-23 14:21:58 -07001442
1443class EventFilter(BaseFilter):
Monty Taylora42a55b2016-07-29 07:53:33 -07001444 """Allows a Pipeline to only respond to certain events."""
James E. Blairc0dedf82014-08-06 09:37:52 -07001445 def __init__(self, trigger, types=[], branches=[], refs=[],
1446 event_approvals={}, comments=[], emails=[], usernames=[],
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001447 timespecs=[], required_approvals=[], reject_approvals=[],
1448 pipelines=[], ignore_deletes=True):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001449 super(EventFilter, self).__init__(
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001450 required_approvals=required_approvals,
1451 reject_approvals=reject_approvals)
James E. Blairc0dedf82014-08-06 09:37:52 -07001452 self.trigger = trigger
James E. Blairee743612012-05-29 14:49:32 -07001453 self._types = types
1454 self._branches = branches
1455 self._refs = refs
James E. Blair1fbfceb2014-06-23 14:42:53 -07001456 self._comments = comments
1457 self._emails = emails
1458 self._usernames = usernames
James E. Blairc494d542014-08-06 09:23:52 -07001459 self._pipelines = pipelines
James E. Blairee743612012-05-29 14:49:32 -07001460 self.types = [re.compile(x) for x in types]
1461 self.branches = [re.compile(x) for x in branches]
1462 self.refs = [re.compile(x) for x in refs]
James E. Blair1fbfceb2014-06-23 14:42:53 -07001463 self.comments = [re.compile(x) for x in comments]
1464 self.emails = [re.compile(x) for x in emails]
1465 self.usernames = [re.compile(x) for x in usernames]
James E. Blairc494d542014-08-06 09:23:52 -07001466 self.pipelines = [re.compile(x) for x in pipelines]
James E. Blairc053d022014-01-22 14:57:33 -08001467 self.event_approvals = event_approvals
James E. Blair63bb0ef2013-07-29 17:14:51 -07001468 self.timespecs = timespecs
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001469 self.ignore_deletes = ignore_deletes
James E. Blairee743612012-05-29 14:49:32 -07001470
James E. Blair9f9667e2012-06-12 17:51:08 -07001471 def __repr__(self):
James E. Blairee743612012-05-29 14:49:32 -07001472 ret = '<EventFilter'
James E. Blair1e8dd892012-05-30 09:15:05 -07001473
James E. Blairee743612012-05-29 14:49:32 -07001474 if self._types:
1475 ret += ' types: %s' % ', '.join(self._types)
James E. Blairc494d542014-08-06 09:23:52 -07001476 if self._pipelines:
1477 ret += ' pipelines: %s' % ', '.join(self._pipelines)
James E. Blairee743612012-05-29 14:49:32 -07001478 if self._branches:
1479 ret += ' branches: %s' % ', '.join(self._branches)
1480 if self._refs:
1481 ret += ' refs: %s' % ', '.join(self._refs)
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001482 if self.ignore_deletes:
1483 ret += ' ignore_deletes: %s' % self.ignore_deletes
James E. Blairc053d022014-01-22 14:57:33 -08001484 if self.event_approvals:
1485 ret += ' event_approvals: %s' % ', '.join(
1486 ['%s:%s' % a for a in self.event_approvals.items()])
James E. Blair5bf78a32015-07-30 18:08:24 +00001487 if self.required_approvals:
1488 ret += ' required_approvals: %s' % ', '.join(
1489 ['%s' % a for a in self._required_approvals])
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001490 if self.reject_approvals:
1491 ret += ' reject_approvals: %s' % ', '.join(
1492 ['%s' % a for a in self._reject_approvals])
James E. Blair1fbfceb2014-06-23 14:42:53 -07001493 if self._comments:
1494 ret += ' comments: %s' % ', '.join(self._comments)
1495 if self._emails:
1496 ret += ' emails: %s' % ', '.join(self._emails)
1497 if self._usernames:
1498 ret += ' username_filters: %s' % ', '.join(self._usernames)
James E. Blair63bb0ef2013-07-29 17:14:51 -07001499 if self.timespecs:
1500 ret += ' timespecs: %s' % ', '.join(self.timespecs)
James E. Blairee743612012-05-29 14:49:32 -07001501 ret += '>'
1502
1503 return ret
1504
James E. Blairc053d022014-01-22 14:57:33 -08001505 def matches(self, event, change):
James E. Blairee743612012-05-29 14:49:32 -07001506 # event types are ORed
1507 matches_type = False
1508 for etype in self.types:
1509 if etype.match(event.type):
1510 matches_type = True
1511 if self.types and not matches_type:
1512 return False
1513
James E. Blairc494d542014-08-06 09:23:52 -07001514 # pipelines are ORed
1515 matches_pipeline = False
1516 for epipe in self.pipelines:
1517 if epipe.match(event.pipeline_name):
1518 matches_pipeline = True
1519 if self.pipelines and not matches_pipeline:
1520 return False
1521
James E. Blairee743612012-05-29 14:49:32 -07001522 # branches are ORed
1523 matches_branch = False
1524 for branch in self.branches:
1525 if branch.match(event.branch):
1526 matches_branch = True
1527 if self.branches and not matches_branch:
1528 return False
1529
1530 # refs are ORed
1531 matches_ref = False
Yolanda Robla16698872014-08-25 11:59:27 +02001532 if event.ref is not None:
1533 for ref in self.refs:
1534 if ref.match(event.ref):
1535 matches_ref = True
James E. Blairee743612012-05-29 14:49:32 -07001536 if self.refs and not matches_ref:
1537 return False
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001538 if self.ignore_deletes and event.newrev == EMPTY_GIT_REF:
1539 # If the updated ref has an empty git sha (all 0s),
1540 # then the ref is being deleted
1541 return False
James E. Blairee743612012-05-29 14:49:32 -07001542
James E. Blair1fbfceb2014-06-23 14:42:53 -07001543 # comments are ORed
1544 matches_comment_re = False
1545 for comment_re in self.comments:
Clark Boylanb9bcb402012-06-29 17:44:05 -07001546 if (event.comment is not None and
James E. Blair1fbfceb2014-06-23 14:42:53 -07001547 comment_re.search(event.comment)):
1548 matches_comment_re = True
1549 if self.comments and not matches_comment_re:
Clark Boylanb9bcb402012-06-29 17:44:05 -07001550 return False
1551
Antoine Mussob4e809e2012-12-06 16:58:06 +01001552 # We better have an account provided by Gerrit to do
1553 # email filtering.
1554 if event.account is not None:
James E. Blaircf429f32012-12-20 14:28:24 -08001555 account_email = event.account.get('email')
James E. Blair1fbfceb2014-06-23 14:42:53 -07001556 # emails are ORed
1557 matches_email_re = False
1558 for email_re in self.emails:
Antoine Mussob4e809e2012-12-06 16:58:06 +01001559 if (account_email is not None and
Joshua Hesketh29d99b72014-08-19 16:27:42 +10001560 email_re.search(account_email)):
James E. Blair1fbfceb2014-06-23 14:42:53 -07001561 matches_email_re = True
1562 if self.emails and not matches_email_re:
Antoine Mussob4e809e2012-12-06 16:58:06 +01001563 return False
1564
James E. Blair1fbfceb2014-06-23 14:42:53 -07001565 # usernames are ORed
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001566 account_username = event.account.get('username')
James E. Blair1fbfceb2014-06-23 14:42:53 -07001567 matches_username_re = False
1568 for username_re in self.usernames:
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001569 if (account_username is not None and
James E. Blair1fbfceb2014-06-23 14:42:53 -07001570 username_re.search(account_username)):
1571 matches_username_re = True
1572 if self.usernames and not matches_username_re:
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001573 return False
1574
James E. Blairee743612012-05-29 14:49:32 -07001575 # approvals are ANDed
James E. Blairc053d022014-01-22 14:57:33 -08001576 for category, value in self.event_approvals.items():
James E. Blairee743612012-05-29 14:49:32 -07001577 matches_approval = False
1578 for eapproval in event.approvals:
1579 if (normalizeCategory(eapproval['description']) == category and
1580 int(eapproval['value']) == int(value)):
1581 matches_approval = True
James E. Blair1e8dd892012-05-30 09:15:05 -07001582 if not matches_approval:
1583 return False
James E. Blair63bb0ef2013-07-29 17:14:51 -07001584
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001585 # required approvals are ANDed (reject approvals are ORed)
1586 if not self.matchesApprovals(change):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001587 return False
James E. Blairc053d022014-01-22 14:57:33 -08001588
James E. Blair63bb0ef2013-07-29 17:14:51 -07001589 # timespecs are ORed
1590 matches_timespec = False
1591 for timespec in self.timespecs:
1592 if (event.timespec == timespec):
1593 matches_timespec = True
1594 if self.timespecs and not matches_timespec:
1595 return False
1596
James E. Blairee743612012-05-29 14:49:32 -07001597 return True
James E. Blaireff88162013-07-01 12:44:14 -04001598
1599
James E. Blair9c17dbf2014-06-23 14:21:58 -07001600class ChangeishFilter(BaseFilter):
Monty Taylora42a55b2016-07-29 07:53:33 -07001601 """Allows a Manager to only enqueue Changes that meet certain criteria."""
Clark Boylana9702ad2014-05-08 17:17:24 -07001602 def __init__(self, open=None, current_patchset=None,
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001603 statuses=[], required_approvals=[],
1604 reject_approvals=[]):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001605 super(ChangeishFilter, self).__init__(
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001606 required_approvals=required_approvals,
1607 reject_approvals=reject_approvals)
James E. Blair11041d22014-05-02 14:49:53 -07001608 self.open = open
Clark Boylana9702ad2014-05-08 17:17:24 -07001609 self.current_patchset = current_patchset
James E. Blair11041d22014-05-02 14:49:53 -07001610 self.statuses = statuses
James E. Blair11041d22014-05-02 14:49:53 -07001611
1612 def __repr__(self):
1613 ret = '<ChangeishFilter'
1614
1615 if self.open is not None:
1616 ret += ' open: %s' % self.open
Clark Boylana9702ad2014-05-08 17:17:24 -07001617 if self.current_patchset is not None:
1618 ret += ' current-patchset: %s' % self.current_patchset
James E. Blair11041d22014-05-02 14:49:53 -07001619 if self.statuses:
1620 ret += ' statuses: %s' % ', '.join(self.statuses)
James E. Blair5bf78a32015-07-30 18:08:24 +00001621 if self.required_approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001622 ret += (' required_approvals: %s' %
1623 str(self.required_approvals))
1624 if self.reject_approvals:
1625 ret += (' reject_approvals: %s' %
1626 str(self.reject_approvals))
James E. Blair11041d22014-05-02 14:49:53 -07001627 ret += '>'
1628
1629 return ret
1630
1631 def matches(self, change):
1632 if self.open is not None:
1633 if self.open != change.open:
1634 return False
1635
Clark Boylana9702ad2014-05-08 17:17:24 -07001636 if self.current_patchset is not None:
1637 if self.current_patchset != change.is_current_patchset:
1638 return False
1639
James E. Blair11041d22014-05-02 14:49:53 -07001640 if self.statuses:
1641 if change.status not in self.statuses:
1642 return False
1643
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001644 # required approvals are ANDed (reject approvals are ORed)
1645 if not self.matchesApprovals(change):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001646 return False
James E. Blair11041d22014-05-02 14:49:53 -07001647
1648 return True
1649
1650
James E. Blairb97ed802015-12-21 15:55:35 -08001651class ProjectPipelineConfig(object):
1652 # Represents a project cofiguration in the context of a pipeline
1653 def __init__(self):
1654 self.job_tree = None
1655 self.queue_name = None
Adam Gandelman8bd57102016-12-02 12:58:42 -08001656 self.merge_mode = None
James E. Blairb97ed802015-12-21 15:55:35 -08001657
1658
1659class ProjectConfig(object):
1660 # Represents a project cofiguration
1661 def __init__(self, name):
1662 self.name = name
Adam Gandelman8bd57102016-12-02 12:58:42 -08001663 self.merge_mode = None
James E. Blairb97ed802015-12-21 15:55:35 -08001664 self.pipelines = {}
1665
1666
James E. Blaird8e778f2015-12-22 14:09:20 -08001667class UnparsedAbideConfig(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001668 """A collection of yaml lists that has not yet been parsed into objects.
1669
1670 An Abide is a collection of tenants.
1671 """
1672
James E. Blaird8e778f2015-12-22 14:09:20 -08001673 def __init__(self):
1674 self.tenants = []
1675
1676 def extend(self, conf):
1677 if isinstance(conf, UnparsedAbideConfig):
1678 self.tenants.extend(conf.tenants)
1679 return
1680
1681 if not isinstance(conf, list):
1682 raise Exception("Configuration items must be in the form of "
1683 "a list of dictionaries (when parsing %s)" %
1684 (conf,))
1685 for item in conf:
1686 if not isinstance(item, dict):
1687 raise Exception("Configuration items must be in the form of "
1688 "a list of dictionaries (when parsing %s)" %
1689 (conf,))
1690 if len(item.keys()) > 1:
1691 raise Exception("Configuration item dictionaries must have "
1692 "a single key (when parsing %s)" %
1693 (conf,))
1694 key, value = item.items()[0]
1695 if key == 'tenant':
1696 self.tenants.append(value)
1697 else:
1698 raise Exception("Configuration item not recognized "
1699 "(when parsing %s)" %
1700 (conf,))
1701
1702
1703class UnparsedTenantConfig(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001704 """A collection of yaml lists that has not yet been parsed into objects."""
1705
James E. Blaird8e778f2015-12-22 14:09:20 -08001706 def __init__(self):
1707 self.pipelines = []
1708 self.jobs = []
1709 self.project_templates = []
1710 self.projects = []
James E. Blaira98340f2016-09-02 11:33:49 -07001711 self.nodesets = []
James E. Blaird8e778f2015-12-22 14:09:20 -08001712
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001713 def copy(self):
1714 r = UnparsedTenantConfig()
1715 r.pipelines = copy.deepcopy(self.pipelines)
1716 r.jobs = copy.deepcopy(self.jobs)
1717 r.project_templates = copy.deepcopy(self.project_templates)
1718 r.projects = copy.deepcopy(self.projects)
James E. Blaira98340f2016-09-02 11:33:49 -07001719 r.nodesets = copy.deepcopy(self.nodesets)
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001720 return r
1721
James E. Blaire208c482016-10-04 14:35:30 -07001722 def extend(self, conf, source_project=None, source_branch=None):
James E. Blaird8e778f2015-12-22 14:09:20 -08001723 if isinstance(conf, UnparsedTenantConfig):
1724 self.pipelines.extend(conf.pipelines)
1725 self.jobs.extend(conf.jobs)
1726 self.project_templates.extend(conf.project_templates)
1727 self.projects.extend(conf.projects)
James E. Blaira98340f2016-09-02 11:33:49 -07001728 self.nodesets.extend(conf.nodesets)
James E. Blaird8e778f2015-12-22 14:09:20 -08001729 return
1730
1731 if not isinstance(conf, list):
1732 raise Exception("Configuration items must be in the form of "
1733 "a list of dictionaries (when parsing %s)" %
1734 (conf,))
1735 for item in conf:
1736 if not isinstance(item, dict):
1737 raise Exception("Configuration items must be in the form of "
1738 "a list of dictionaries (when parsing %s)" %
1739 (conf,))
1740 if len(item.keys()) > 1:
1741 raise Exception("Configuration item dictionaries must have "
1742 "a single key (when parsing %s)" %
1743 (conf,))
1744 key, value = item.items()[0]
1745 if key == 'project':
1746 self.projects.append(value)
1747 elif key == 'job':
James E. Blair4317e9f2016-07-15 10:05:47 -07001748 if source_project is not None:
1749 value['_source_project'] = source_project
James E. Blaire208c482016-10-04 14:35:30 -07001750 if source_branch is not None:
1751 value['_source_branch'] = source_branch
James E. Blaird8e778f2015-12-22 14:09:20 -08001752 self.jobs.append(value)
1753 elif key == 'project-template':
1754 self.project_templates.append(value)
1755 elif key == 'pipeline':
1756 self.pipelines.append(value)
James E. Blaira98340f2016-09-02 11:33:49 -07001757 elif key == 'nodeset':
1758 self.nodesets.append(value)
James E. Blaird8e778f2015-12-22 14:09:20 -08001759 else:
Morgan Fainberg4245a422016-08-05 16:20:12 -07001760 raise Exception("Configuration item `%s` not recognized "
James E. Blaird8e778f2015-12-22 14:09:20 -08001761 "(when parsing %s)" %
Morgan Fainberg4245a422016-08-05 16:20:12 -07001762 (item, conf,))
James E. Blaird8e778f2015-12-22 14:09:20 -08001763
1764
James E. Blaireff88162013-07-01 12:44:14 -04001765class Layout(object):
Monty Taylora42a55b2016-07-29 07:53:33 -07001766 """Holds all of the Pipelines."""
1767
James E. Blaireff88162013-07-01 12:44:14 -04001768 def __init__(self):
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001769 self.tenant = None
James E. Blaireff88162013-07-01 12:44:14 -04001770 self.projects = {}
James E. Blairb97ed802015-12-21 15:55:35 -08001771 self.project_configs = {}
1772 self.project_templates = {}
James E. Blair5a9918a2013-08-27 10:06:27 -07001773 self.pipelines = OrderedDict()
James E. Blair83005782015-12-11 14:46:03 -08001774 # This is a dictionary of name -> [jobs]. The first element
1775 # of the list is the first job added with that name. It is
1776 # the reference definition for a given job. Subsequent
1777 # elements are aspects of that job with different matchers
1778 # that override some attribute of the job. These aspects all
1779 # inherit from the reference definition.
James E. Blairfef88ec2016-11-30 08:38:27 -08001780 self.jobs = {'noop': [Job('noop')]}
James E. Blaira98340f2016-09-02 11:33:49 -07001781 self.nodesets = {}
James E. Blaireff88162013-07-01 12:44:14 -04001782
1783 def getJob(self, name):
1784 if name in self.jobs:
James E. Blair83005782015-12-11 14:46:03 -08001785 return self.jobs[name][0]
James E. Blairb97ed802015-12-21 15:55:35 -08001786 raise Exception("Job %s not defined" % (name,))
James E. Blair83005782015-12-11 14:46:03 -08001787
1788 def getJobs(self, name):
1789 return self.jobs.get(name, [])
1790
1791 def addJob(self, job):
James E. Blair4317e9f2016-07-15 10:05:47 -07001792 # We can have multiple variants of a job all with the same
1793 # name, but these variants must all be defined in the same repo.
1794 prior_jobs = [j for j in self.getJobs(job.name)
1795 if j.source_project != job.source_project]
1796 if prior_jobs:
1797 raise Exception("Job %s in %s is not permitted to shadow "
1798 "job %s in %s" % (job, job.source_project,
1799 prior_jobs[0],
1800 prior_jobs[0].source_project))
1801
James E. Blair83005782015-12-11 14:46:03 -08001802 if job.name in self.jobs:
1803 self.jobs[job.name].append(job)
1804 else:
1805 self.jobs[job.name] = [job]
1806
James E. Blaira98340f2016-09-02 11:33:49 -07001807 def addNodeSet(self, nodeset):
1808 if nodeset.name in self.nodesets:
1809 raise Exception("NodeSet %s already defined" % (nodeset.name,))
1810 self.nodesets[nodeset.name] = nodeset
1811
James E. Blair83005782015-12-11 14:46:03 -08001812 def addPipeline(self, pipeline):
1813 self.pipelines[pipeline.name] = pipeline
James E. Blair59fdbac2015-12-07 17:08:06 -08001814
James E. Blairb97ed802015-12-21 15:55:35 -08001815 def addProjectTemplate(self, project_template):
1816 self.project_templates[project_template.name] = project_template
1817
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001818 def addProjectConfig(self, project_config, update_pipeline=True):
James E. Blairb97ed802015-12-21 15:55:35 -08001819 self.project_configs[project_config.name] = project_config
1820 # TODOv3(jeblair): tidy up the relationship between pipelines
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001821 # and projects and projectconfigs. Specifically, move
1822 # job_trees out of the pipeline since they are more dynamic
1823 # than pipelines. Remove the update_pipeline argument
1824 if not update_pipeline:
1825 return
James E. Blairb97ed802015-12-21 15:55:35 -08001826 for pipeline_name, pipeline_config in project_config.pipelines.items():
1827 pipeline = self.pipelines[pipeline_name]
1828 project = pipeline.source.getProject(project_config.name)
1829 pipeline.job_trees[project] = pipeline_config.job_tree
1830
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001831 def _createJobTree(self, change, job_trees, parent):
1832 for tree in job_trees:
1833 job = tree.job
1834 if not job.changeMatches(change):
1835 continue
1836 frozen_job = Job(job.name)
1837 frozen_tree = JobTree(frozen_job)
1838 inherited = set()
1839 for variant in self.getJobs(job.name):
1840 if variant.changeMatches(change):
1841 if variant not in inherited:
1842 frozen_job.inheritFrom(variant)
1843 inherited.add(variant)
James E. Blair6e85c2b2016-11-21 16:47:01 -08001844 if not inherited:
1845 # A change must match at least one defined job variant
1846 # (that is to say that it must match more than just
1847 # the job that is defined in the tree).
1848 continue
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001849 if job not in inherited:
1850 # Only update from the job in the tree if it is
1851 # unique, otherwise we might unset an attribute we
1852 # have overloaded.
1853 frozen_job.inheritFrom(job)
1854 parent.job_trees.append(frozen_tree)
1855 self._createJobTree(change, tree.job_trees, frozen_tree)
1856
1857 def createJobTree(self, item):
Paul Belanger160cb8e2016-11-11 19:04:24 -05001858 project_config = self.project_configs.get(
1859 item.change.project.name, None)
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001860 ret = JobTree(None)
Paul Belanger15e3e202016-10-14 16:27:34 -04001861 # NOTE(pabelanger): It is possible for a foreign project not to have a
1862 # configured pipeline, if so return an empty JobTree.
Paul Belanger160cb8e2016-11-11 19:04:24 -05001863 if project_config and item.pipeline.name in project_config.pipelines:
Paul Belanger15e3e202016-10-14 16:27:34 -04001864 project_tree = \
1865 project_config.pipelines[item.pipeline.name].job_tree
1866 self._createJobTree(item.change, project_tree.job_trees, ret)
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001867 return ret
1868
James E. Blair59fdbac2015-12-07 17:08:06 -08001869
1870class Tenant(object):
1871 def __init__(self, name):
1872 self.name = name
1873 self.layout = None
James E. Blair8b1dc3f2016-07-05 16:49:00 -07001874 # The list of repos from which we will read main
1875 # configuration. (source, project)
1876 self.config_repos = []
1877 # The unparsed config from those repos.
1878 self.config_repos_config = None
1879 # The list of projects from which we will read in-repo
1880 # configuration. (source, project)
1881 self.project_repos = []
1882 # The unparsed config from those repos.
1883 self.project_repos_config = None
James E. Blair59fdbac2015-12-07 17:08:06 -08001884
1885
1886class Abide(object):
1887 def __init__(self):
1888 self.tenants = OrderedDict()
James E. Blairce8a2132016-05-19 15:21:52 -07001889
1890
1891class JobTimeData(object):
1892 format = 'B10H10H10B'
1893 version = 0
1894
1895 def __init__(self, path):
1896 self.path = path
1897 self.success_times = [0 for x in range(10)]
1898 self.failure_times = [0 for x in range(10)]
1899 self.results = [0 for x in range(10)]
1900
1901 def load(self):
1902 if not os.path.exists(self.path):
1903 return
1904 with open(self.path) as f:
1905 data = struct.unpack(self.format, f.read())
1906 version = data[0]
1907 if version != self.version:
1908 raise Exception("Unkown data version")
1909 self.success_times = list(data[1:11])
1910 self.failure_times = list(data[11:21])
1911 self.results = list(data[21:32])
1912
1913 def save(self):
1914 tmpfile = self.path + '.tmp'
1915 data = [self.version]
1916 data.extend(self.success_times)
1917 data.extend(self.failure_times)
1918 data.extend(self.results)
1919 data = struct.pack(self.format, *data)
1920 with open(tmpfile, 'w') as f:
1921 f.write(data)
1922 os.rename(tmpfile, self.path)
1923
1924 def add(self, elapsed, result):
1925 elapsed = int(elapsed)
1926 if result == 'SUCCESS':
1927 self.success_times.append(elapsed)
1928 self.success_times.pop(0)
1929 result = 0
1930 else:
1931 self.failure_times.append(elapsed)
1932 self.failure_times.pop(0)
1933 result = 1
1934 self.results.append(result)
1935 self.results.pop(0)
1936
1937 def getEstimatedTime(self):
1938 times = [x for x in self.success_times if x]
1939 if times:
1940 return float(sum(times)) / len(times)
1941 return 0.0
1942
1943
1944class TimeDataBase(object):
1945 def __init__(self, root):
1946 self.root = root
1947 self.jobs = {}
1948
1949 def _getTD(self, name):
1950 td = self.jobs.get(name)
1951 if not td:
1952 td = JobTimeData(os.path.join(self.root, name))
1953 self.jobs[name] = td
1954 td.load()
1955 return td
1956
1957 def getEstimatedTime(self, name):
1958 return self._getTD(name).getEstimatedTime()
1959
1960 def update(self, name, elapsed, result):
1961 td = self._getTD(name)
1962 td.add(elapsed, result)
1963 td.save()