blob: a88c365d416deea7c4f5cd2560152a7acb1bf1fb [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. Blairee743612012-05-29 14:49:32 -070016import re
James E. Blairff986a12012-05-30 14:56:51 -070017import time
James E. Blair4886cc12012-07-18 15:39:41 -070018from uuid import uuid4
James E. Blair5a9918a2013-08-27 10:06:27 -070019import extras
20
21OrderedDict = extras.try_imports(['collections.OrderedDict',
22 'ordereddict.OrderedDict'])
James E. Blair4886cc12012-07-18 15:39:41 -070023
24
K Jonathan Harkerf95e7232015-04-29 13:33:16 -070025EMPTY_GIT_REF = '0' * 40 # git sha of all zeros, used during creates/deletes
26
James E. Blair19deff22013-08-25 13:17:35 -070027MERGER_MERGE = 1 # "git merge"
28MERGER_MERGE_RESOLVE = 2 # "git merge -s resolve"
29MERGER_CHERRY_PICK = 3 # "git cherry-pick"
30
31MERGER_MAP = {
32 'merge': MERGER_MERGE,
33 'merge-resolve': MERGER_MERGE_RESOLVE,
34 'cherry-pick': MERGER_CHERRY_PICK,
35}
James E. Blairee743612012-05-29 14:49:32 -070036
James E. Blair64ed6f22013-07-10 14:07:23 -070037PRECEDENCE_NORMAL = 0
38PRECEDENCE_LOW = 1
39PRECEDENCE_HIGH = 2
40
41PRECEDENCE_MAP = {
42 None: PRECEDENCE_NORMAL,
43 'low': PRECEDENCE_LOW,
44 'normal': PRECEDENCE_NORMAL,
45 'high': PRECEDENCE_HIGH,
46}
47
James E. Blair1e8dd892012-05-30 09:15:05 -070048
James E. Blairc053d022014-01-22 14:57:33 -080049def time_to_seconds(s):
50 if s.endswith('s'):
51 return int(s[:-1])
52 if s.endswith('m'):
53 return int(s[:-1]) * 60
54 if s.endswith('h'):
55 return int(s[:-1]) * 60 * 60
56 if s.endswith('d'):
57 return int(s[:-1]) * 24 * 60 * 60
58 if s.endswith('w'):
59 return int(s[:-1]) * 7 * 24 * 60 * 60
60 raise Exception("Unable to parse time value: %s" % s)
61
62
James E. Blair11041d22014-05-02 14:49:53 -070063def normalizeCategory(name):
64 name = name.lower()
65 return re.sub(' ', '-', name)
66
67
James E. Blair4aea70c2012-07-26 14:23:24 -070068class Pipeline(object):
69 """A top-level pipeline such as check, gate, post, etc."""
James E. Blair83005782015-12-11 14:46:03 -080070 def __init__(self, name, layout):
James E. Blair4aea70c2012-07-26 14:23:24 -070071 self.name = name
James E. Blair83005782015-12-11 14:46:03 -080072 self.layout = layout
James E. Blair8dbd56a2012-12-22 10:55:10 -080073 self.description = None
James E. Blair56370192013-01-14 15:47:28 -080074 self.failure_message = None
Joshua Heskethb7179772014-01-30 23:30:46 +110075 self.merge_failure_message = None
James E. Blair56370192013-01-14 15:47:28 -080076 self.success_message = None
Joshua Hesketh3979e3e2014-03-04 11:21:10 +110077 self.footer_message = None
James E. Blair2fa50962013-01-30 21:50:41 -080078 self.dequeue_on_new_patchset = True
James E. Blair17dd6772015-02-09 14:45:18 -080079 self.ignore_dependencies = False
James E. Blair4aea70c2012-07-26 14:23:24 -070080 self.job_trees = {} # project -> JobTree
81 self.manager = None
James E. Blaire0487072012-08-29 17:38:31 -070082 self.queues = []
James E. Blair64ed6f22013-07-10 14:07:23 -070083 self.precedence = PRECEDENCE_NORMAL
James E. Blairc0dedf82014-08-06 09:37:52 -070084 self.source = None
James E. Blair83005782015-12-11 14:46:03 -080085 self.triggers = []
Joshua Hesketh352264b2015-08-11 23:42:08 +100086 self.start_actions = []
87 self.success_actions = []
88 self.failure_actions = []
89 self.merge_failure_actions = []
90 self.disabled_actions = []
Joshua Hesketh89e829d2015-02-10 16:29:45 +110091 self.disable_at = None
92 self._consecutive_failures = 0
93 self._disabled = False
Clark Boylan7603a372014-01-21 11:43:20 -080094 self.window = None
95 self.window_floor = None
96 self.window_increase_type = None
97 self.window_increase_factor = None
98 self.window_decrease_type = None
99 self.window_decrease_factor = None
James E. Blair4aea70c2012-07-26 14:23:24 -0700100
James E. Blair83005782015-12-11 14:46:03 -0800101 @property
102 def actions(self):
103 return (
104 self.start_actions +
105 self.success_actions +
106 self.failure_actions +
107 self.merge_failure_actions +
108 self.disabled_actions
109 )
110
James E. Blaird09c17a2012-08-07 09:23:14 -0700111 def __repr__(self):
112 return '<Pipeline %s>' % self.name
113
James E. Blair4aea70c2012-07-26 14:23:24 -0700114 def setManager(self, manager):
115 self.manager = manager
116
117 def addProject(self, project):
118 job_tree = JobTree(None) # Null job == job tree root
119 self.job_trees[project] = job_tree
120 return job_tree
121
122 def getProjects(self):
James E. Blairc3d428e2013-12-03 15:06:48 -0800123 return sorted(self.job_trees.keys(), lambda a, b: cmp(a.name, b.name))
James E. Blair4aea70c2012-07-26 14:23:24 -0700124
James E. Blaire0487072012-08-29 17:38:31 -0700125 def addQueue(self, queue):
126 self.queues.append(queue)
127
128 def getQueue(self, project):
129 for queue in self.queues:
130 if project in queue.projects:
131 return queue
132 return None
133
James E. Blairbfb8e042014-12-30 17:01:44 -0800134 def removeQueue(self, queue):
135 self.queues.remove(queue)
136
James E. Blair4aea70c2012-07-26 14:23:24 -0700137 def getJobTree(self, project):
138 tree = self.job_trees.get(project)
139 return tree
140
James E. Blair107c3852015-02-07 08:23:10 -0800141 def getJobs(self, item):
142 if not item.live:
143 return []
144 tree = self.getJobTree(item.change.project)
James E. Blair4aea70c2012-07-26 14:23:24 -0700145 if not tree:
146 return []
James E. Blair107c3852015-02-07 08:23:10 -0800147 return item.change.filterJobs(tree.getJobs())
James E. Blair4aea70c2012-07-26 14:23:24 -0700148
James E. Blairaf17a972016-02-03 15:07:18 -0800149 def _findJobsToRun(self, job_trees, item, mutex):
James E. Blair4aea70c2012-07-26 14:23:24 -0700150 torun = []
James E. Blair4aea70c2012-07-26 14:23:24 -0700151 for tree in job_trees:
152 job = tree.job
153 result = None
154 if job:
James E. Blairfee8d652013-06-07 08:57:52 -0700155 if not job.changeMatches(item.change):
James E. Blair4aea70c2012-07-26 14:23:24 -0700156 continue
James E. Blairfee8d652013-06-07 08:57:52 -0700157 build = item.current_build_set.getBuild(job.name)
James E. Blair4aea70c2012-07-26 14:23:24 -0700158 if build:
159 result = build.result
160 else:
161 # There is no build for the root of this job tree,
162 # so we should run it.
James E. Blairaf17a972016-02-03 15:07:18 -0800163 if mutex.acquire(item, job):
164 # If this job needs a mutex, either acquire it or make
165 # sure that we have it before running the job.
166 torun.append(job)
James E. Blair4aea70c2012-07-26 14:23:24 -0700167 # If there is no job, this is a null job tree, and we should
168 # run all of its jobs.
169 if result == 'SUCCESS' or not job:
James E. Blairaf17a972016-02-03 15:07:18 -0800170 torun.extend(self._findJobsToRun(tree.job_trees, item, mutex))
James E. Blair4aea70c2012-07-26 14:23:24 -0700171 return torun
172
James E. Blairaf17a972016-02-03 15:07:18 -0800173 def findJobsToRun(self, item, mutex):
James E. Blairbfb8e042014-12-30 17:01:44 -0800174 if not item.live:
175 return []
James E. Blair83005782015-12-11 14:46:03 -0800176 tree = item.job_tree
James E. Blair4aea70c2012-07-26 14:23:24 -0700177 if not tree:
178 return []
James E. Blairaf17a972016-02-03 15:07:18 -0800179 return self._findJobsToRun(tree.job_trees, item, mutex)
James E. Blair4aea70c2012-07-26 14:23:24 -0700180
James E. Blairbea9ef12013-07-15 11:52:23 -0700181 def haveAllJobsStarted(self, item):
James E. Blair107c3852015-02-07 08:23:10 -0800182 for job in self.getJobs(item):
James E. Blairbea9ef12013-07-15 11:52:23 -0700183 build = item.current_build_set.getBuild(job.name)
184 if not build or not build.start_time:
185 return False
186 return True
187
James E. Blairfee8d652013-06-07 08:57:52 -0700188 def areAllJobsComplete(self, item):
James E. Blair107c3852015-02-07 08:23:10 -0800189 for job in self.getJobs(item):
James E. Blairfee8d652013-06-07 08:57:52 -0700190 build = item.current_build_set.getBuild(job.name)
James E. Blair4aea70c2012-07-26 14:23:24 -0700191 if not build or not build.result:
192 return False
193 return True
194
James E. Blairfee8d652013-06-07 08:57:52 -0700195 def didAllJobsSucceed(self, item):
James E. Blair107c3852015-02-07 08:23:10 -0800196 for job in self.getJobs(item):
James E. Blair4ec821f2012-08-23 15:28:28 -0700197 if not job.voting:
198 continue
James E. Blairfee8d652013-06-07 08:57:52 -0700199 build = item.current_build_set.getBuild(job.name)
James E. Blair4aea70c2012-07-26 14:23:24 -0700200 if not build:
201 return False
202 if build.result != 'SUCCESS':
203 return False
204 return True
205
Joshua Heskethb7179772014-01-30 23:30:46 +1100206 def didMergerSucceed(self, item):
207 if item.current_build_set.unable_to_merge:
208 return False
209 return True
210
James E. Blairfee8d652013-06-07 08:57:52 -0700211 def didAnyJobFail(self, item):
James E. Blair107c3852015-02-07 08:23:10 -0800212 for job in self.getJobs(item):
James E. Blair4ec821f2012-08-23 15:28:28 -0700213 if not job.voting:
214 continue
James E. Blairfee8d652013-06-07 08:57:52 -0700215 build = item.current_build_set.getBuild(job.name)
James E. Blair0018a6c2013-02-27 14:11:45 -0800216 if build and build.result and (build.result != 'SUCCESS'):
James E. Blair4aea70c2012-07-26 14:23:24 -0700217 return True
218 return False
219
James E. Blairfee8d652013-06-07 08:57:52 -0700220 def isHoldingFollowingChanges(self, item):
James E. Blairbfb8e042014-12-30 17:01:44 -0800221 if not item.live:
222 return False
James E. Blair107c3852015-02-07 08:23:10 -0800223 for job in self.getJobs(item):
James E. Blair4aea70c2012-07-26 14:23:24 -0700224 if not job.hold_following_changes:
225 continue
James E. Blairfee8d652013-06-07 08:57:52 -0700226 build = item.current_build_set.getBuild(job.name)
James E. Blair4aea70c2012-07-26 14:23:24 -0700227 if not build:
228 return True
229 if build.result != 'SUCCESS':
230 return True
James E. Blair972e3c72013-08-29 12:04:55 -0700231
James E. Blairfee8d652013-06-07 08:57:52 -0700232 if not item.item_ahead:
James E. Blair4aea70c2012-07-26 14:23:24 -0700233 return False
James E. Blairfee8d652013-06-07 08:57:52 -0700234 return self.isHoldingFollowingChanges(item.item_ahead)
James E. Blair4aea70c2012-07-26 14:23:24 -0700235
James E. Blairfee8d652013-06-07 08:57:52 -0700236 def setResult(self, item, build):
James E. Blair4a28a882013-08-23 15:17:33 -0700237 if build.retry:
238 item.removeBuild(build)
239 elif build.result != 'SUCCESS':
James E. Blair4aea70c2012-07-26 14:23:24 -0700240 # Get a JobTree from a Job so we can find only its dependent jobs
James E. Blairf5dbd002015-12-23 15:26:17 -0800241 tree = item.job_tree.getJobTreeForJob(build.job)
James E. Blair4aea70c2012-07-26 14:23:24 -0700242 for job in tree.getJobs():
243 fakebuild = Build(job, None)
244 fakebuild.result = 'SKIPPED'
James E. Blairfee8d652013-06-07 08:57:52 -0700245 item.addBuild(fakebuild)
James E. Blair4aea70c2012-07-26 14:23:24 -0700246
Joshua Heskethb7179772014-01-30 23:30:46 +1100247 def setUnableToMerge(self, item):
James E. Blairfee8d652013-06-07 08:57:52 -0700248 item.current_build_set.unable_to_merge = True
249 root = self.getJobTree(item.change.project)
James E. Blair973721f2012-08-15 10:19:43 -0700250 for job in root.getJobs():
251 fakebuild = Build(job, None)
252 fakebuild.result = 'SKIPPED'
James E. Blairfee8d652013-06-07 08:57:52 -0700253 item.addBuild(fakebuild)
James E. Blair973721f2012-08-15 10:19:43 -0700254
James E. Blairfee8d652013-06-07 08:57:52 -0700255 def setDequeuedNeedingChange(self, item):
256 item.dequeued_needing_change = True
257 root = self.getJobTree(item.change.project)
James E. Blaircaec0c52012-08-22 14:52:22 -0700258 for job in root.getJobs():
259 fakebuild = Build(job, None)
260 fakebuild.result = 'SKIPPED'
James E. Blairfee8d652013-06-07 08:57:52 -0700261 item.addBuild(fakebuild)
James E. Blaircaec0c52012-08-22 14:52:22 -0700262
James E. Blaire0487072012-08-29 17:38:31 -0700263 def getChangesInQueue(self):
264 changes = []
265 for shared_queue in self.queues:
James E. Blairfee8d652013-06-07 08:57:52 -0700266 changes.extend([x.change for x in shared_queue.queue])
James E. Blaire0487072012-08-29 17:38:31 -0700267 return changes
268
James E. Blairfee8d652013-06-07 08:57:52 -0700269 def getAllItems(self):
270 items = []
James E. Blaire0487072012-08-29 17:38:31 -0700271 for shared_queue in self.queues:
James E. Blairfee8d652013-06-07 08:57:52 -0700272 items.extend(shared_queue.queue)
James E. Blairfee8d652013-06-07 08:57:52 -0700273 return items
James E. Blaire0487072012-08-29 17:38:31 -0700274
James E. Blair8dbd56a2012-12-22 10:55:10 -0800275 def formatStatusJSON(self):
276 j_pipeline = dict(name=self.name,
277 description=self.description)
278 j_queues = []
279 j_pipeline['change_queues'] = j_queues
280 for queue in self.queues:
281 j_queue = dict(name=queue.name)
282 j_queues.append(j_queue)
283 j_queue['heads'] = []
Clark Boylanaf2476f2014-01-23 14:47:36 -0800284 j_queue['window'] = queue.window
James E. Blair972e3c72013-08-29 12:04:55 -0700285
286 j_changes = []
287 for e in queue.queue:
288 if not e.item_ahead:
289 if j_changes:
290 j_queue['heads'].append(j_changes)
291 j_changes = []
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800292 j_changes.append(e.formatJSON())
James E. Blair972e3c72013-08-29 12:04:55 -0700293 if (len(j_changes) > 1 and
Joshua Hesketh29d99b72014-08-19 16:27:42 +1000294 (j_changes[-2]['remaining_time'] is not None) and
295 (j_changes[-1]['remaining_time'] is not None)):
James E. Blair972e3c72013-08-29 12:04:55 -0700296 j_changes[-1]['remaining_time'] = max(
297 j_changes[-2]['remaining_time'],
298 j_changes[-1]['remaining_time'])
299 if j_changes:
James E. Blair8dbd56a2012-12-22 10:55:10 -0800300 j_queue['heads'].append(j_changes)
301 return j_pipeline
302
James E. Blair4aea70c2012-07-26 14:23:24 -0700303
James E. Blairee743612012-05-29 14:49:32 -0700304class ChangeQueue(object):
James E. Blair4aea70c2012-07-26 14:23:24 -0700305 """DependentPipelines have multiple parallel queues shared by
306 different projects; this is one of them. For instance, there may
307 a queue shared by interrelated projects foo and bar, and a second
308 queue for independent project baz. Pipelines have one or more
James E. Blairbfb8e042014-12-30 17:01:44 -0800309 ChangeQueues."""
310 def __init__(self, pipeline, window=0, window_floor=1,
Clark Boylan7603a372014-01-21 11:43:20 -0800311 window_increase_type='linear', window_increase_factor=1,
312 window_decrease_type='exponential', window_decrease_factor=2):
James E. Blair4aea70c2012-07-26 14:23:24 -0700313 self.pipeline = pipeline
James E. Blairee743612012-05-29 14:49:32 -0700314 self.name = ''
James E. Blairc8a1e052014-02-25 09:29:26 -0800315 self.assigned_name = None
316 self.generated_name = None
James E. Blairee743612012-05-29 14:49:32 -0700317 self.projects = []
318 self._jobs = set()
319 self.queue = []
Clark Boylan7603a372014-01-21 11:43:20 -0800320 self.window = window
321 self.window_floor = window_floor
322 self.window_increase_type = window_increase_type
323 self.window_increase_factor = window_increase_factor
324 self.window_decrease_type = window_decrease_type
325 self.window_decrease_factor = window_decrease_factor
James E. Blairee743612012-05-29 14:49:32 -0700326
James E. Blair9f9667e2012-06-12 17:51:08 -0700327 def __repr__(self):
James E. Blair4aea70c2012-07-26 14:23:24 -0700328 return '<ChangeQueue %s: %s>' % (self.pipeline.name, self.name)
James E. Blairee743612012-05-29 14:49:32 -0700329
330 def getJobs(self):
331 return self._jobs
332
333 def addProject(self, project):
334 if project not in self.projects:
335 self.projects.append(project)
James E. Blairc8a1e052014-02-25 09:29:26 -0800336
James E. Blairee743612012-05-29 14:49:32 -0700337 names = [x.name for x in self.projects]
338 names.sort()
James E. Blairc8a1e052014-02-25 09:29:26 -0800339 self.generated_name = ', '.join(names)
James E. Blairc8a1e052014-02-25 09:29:26 -0800340 self.name = self.assigned_name or self.generated_name
James E. Blairee743612012-05-29 14:49:32 -0700341
342 def enqueueChange(self, change):
James E. Blairbfb8e042014-12-30 17:01:44 -0800343 item = QueueItem(self, change)
James E. Blair83005782015-12-11 14:46:03 -0800344 item.freezeJobTree()
James E. Blaircdccd972013-07-01 12:10:22 -0700345 self.enqueueItem(item)
346 item.enqueue_time = time.time()
347 return item
348
349 def enqueueItem(self, item):
James E. Blair4a035d92014-01-23 13:10:48 -0800350 item.pipeline = self.pipeline
James E. Blairbfb8e042014-12-30 17:01:44 -0800351 item.queue = self
352 if self.queue:
James E. Blairfee8d652013-06-07 08:57:52 -0700353 item.item_ahead = self.queue[-1]
James E. Blair972e3c72013-08-29 12:04:55 -0700354 item.item_ahead.items_behind.append(item)
James E. Blairfee8d652013-06-07 08:57:52 -0700355 self.queue.append(item)
James E. Blairee743612012-05-29 14:49:32 -0700356
James E. Blairfee8d652013-06-07 08:57:52 -0700357 def dequeueItem(self, item):
358 if item in self.queue:
359 self.queue.remove(item)
James E. Blairfee8d652013-06-07 08:57:52 -0700360 if item.item_ahead:
James E. Blair972e3c72013-08-29 12:04:55 -0700361 item.item_ahead.items_behind.remove(item)
362 for item_behind in item.items_behind:
363 if item.item_ahead:
364 item.item_ahead.items_behind.append(item_behind)
365 item_behind.item_ahead = item.item_ahead
James E. Blairfee8d652013-06-07 08:57:52 -0700366 item.item_ahead = None
James E. Blair972e3c72013-08-29 12:04:55 -0700367 item.items_behind = []
James E. Blairfee8d652013-06-07 08:57:52 -0700368 item.dequeue_time = time.time()
James E. Blaire0487072012-08-29 17:38:31 -0700369
James E. Blair972e3c72013-08-29 12:04:55 -0700370 def moveItem(self, item, item_ahead):
James E. Blair972e3c72013-08-29 12:04:55 -0700371 if item.item_ahead == item_ahead:
372 return False
373 # Remove from current location
374 if item.item_ahead:
375 item.item_ahead.items_behind.remove(item)
376 for item_behind in item.items_behind:
377 if item.item_ahead:
378 item.item_ahead.items_behind.append(item_behind)
379 item_behind.item_ahead = item.item_ahead
380 # Add to new location
381 item.item_ahead = item_ahead
James E. Blair00451262013-09-20 11:40:17 -0700382 item.items_behind = []
James E. Blair972e3c72013-08-29 12:04:55 -0700383 if item.item_ahead:
384 item.item_ahead.items_behind.append(item)
385 return True
James E. Blairee743612012-05-29 14:49:32 -0700386
387 def mergeChangeQueue(self, other):
388 for project in other.projects:
389 self.addProject(project)
Clark Boylan7603a372014-01-21 11:43:20 -0800390 self.window = min(self.window, other.window)
391 # TODO merge semantics
392
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800393 def isActionable(self, item):
James E. Blairbfb8e042014-12-30 17:01:44 -0800394 if self.window:
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800395 return item in self.queue[:self.window]
Clark Boylan7603a372014-01-21 11:43:20 -0800396 else:
Clark Boylan3d2f7a72014-01-23 11:07:42 -0800397 return True
Clark Boylan7603a372014-01-21 11:43:20 -0800398
399 def increaseWindowSize(self):
James E. Blairbfb8e042014-12-30 17:01:44 -0800400 if self.window:
Clark Boylan7603a372014-01-21 11:43:20 -0800401 if self.window_increase_type == 'linear':
402 self.window += self.window_increase_factor
403 elif self.window_increase_type == 'exponential':
404 self.window *= self.window_increase_factor
405
406 def decreaseWindowSize(self):
James E. Blairbfb8e042014-12-30 17:01:44 -0800407 if self.window:
Clark Boylan7603a372014-01-21 11:43:20 -0800408 if self.window_decrease_type == 'linear':
409 self.window = max(
410 self.window_floor,
411 self.window - self.window_decrease_factor)
412 elif self.window_decrease_type == 'exponential':
413 self.window = max(
414 self.window_floor,
415 self.window / self.window_decrease_factor)
James E. Blairee743612012-05-29 14:49:32 -0700416
James E. Blair1e8dd892012-05-30 09:15:05 -0700417
James E. Blair4aea70c2012-07-26 14:23:24 -0700418class Project(object):
Evgeny Antyshev0deaaad2015-08-03 20:22:56 +0000419 def __init__(self, name, foreign=False):
James E. Blair4aea70c2012-07-26 14:23:24 -0700420 self.name = name
James E. Blair19deff22013-08-25 13:17:35 -0700421 self.merge_mode = MERGER_MERGE_RESOLVE
Evgeny Antyshev0deaaad2015-08-03 20:22:56 +0000422 # foreign projects are those referenced in dependencies
423 # of layout projects, this should matter
424 # when deciding whether to enqueue their changes
425 self.foreign = foreign
James E. Blair4aea70c2012-07-26 14:23:24 -0700426
427 def __str__(self):
428 return self.name
429
430 def __repr__(self):
431 return '<Project %s>' % (self.name)
432
433
James E. Blair83005782015-12-11 14:46:03 -0800434class Inheritable(object):
435 def __init__(self, parent=None):
436 self.parent = parent
437
438 def __getattribute__(self, name):
439 parent = object.__getattribute__(self, 'parent')
440 try:
441 return object.__getattribute__(self, name)
442 except AttributeError:
443 if parent:
444 return getattr(parent, name)
445 raise
446
447
James E. Blairee743612012-05-29 14:49:32 -0700448class Job(object):
James E. Blair83005782015-12-11 14:46:03 -0800449 attributes = dict(
450 timeout=None,
451 # variables={},
452 # nodes=[],
453 # auth={},
454 workspace=None,
455 pre_run=None,
456 post_run=None,
457 voting=None,
458 failure_message=None,
459 success_message=None,
460 failure_url=None,
461 success_url=None,
462 # Matchers. These are separate so they can be individually
463 # overidden.
464 branch_matcher=None,
465 file_matcher=None,
466 irrelevant_file_matcher=None, # skip-if
467 swift=None, # TODOv3(jeblair): move to auth
468 parameter_function=None, # TODOv3(jeblair): remove
469 success_pattern=None, # TODOv3(jeblair): remove
Joshua Heskethdc7820c2016-03-11 13:14:28 +1100470 tags=set(),
Joshua Hesketh89b67f62016-02-11 21:22:14 +1100471 mutex=None,
James E. Blair83005782015-12-11 14:46:03 -0800472 )
473
James E. Blairee743612012-05-29 14:49:32 -0700474 def __init__(self, name):
475 self.name = name
James E. Blair83005782015-12-11 14:46:03 -0800476 for k, v in self.attributes.items():
477 setattr(self, k, v)
478
479 def __equals__(self, other):
480 # Compare the name and all inheritable attributes to determine
481 # whether two jobs with the same name are identically
482 # configured. Useful upon reconfiguration.
483 if not isinstance(other, Job):
484 return False
485 if self.name != other.name:
486 return False
487 for k, v in self.attributes.items():
488 if getattr(self, k) != getattr(other, k):
489 return False
490 return True
James E. Blairee743612012-05-29 14:49:32 -0700491
492 def __str__(self):
493 return self.name
494
495 def __repr__(self):
James E. Blair83005782015-12-11 14:46:03 -0800496 return '<Job %s>' % (self.name,)
497
498 def inheritFrom(self, other):
499 """Copy the inheritable attributes which have been set on the other
500 job to this job."""
501
502 if not isinstance(other, Job):
503 raise Exception("Job unable to inherit from %s" % (other,))
504 for k, v in self.attributes.items():
505 if getattr(other, k) != v:
506 setattr(self, k, getattr(other, k))
James E. Blairee743612012-05-29 14:49:32 -0700507
James E. Blaire421a232012-07-25 16:59:21 -0700508 def changeMatches(self, change):
James E. Blair83005782015-12-11 14:46:03 -0800509 if self.branch_matcher and not self.branch_matcher.matches(change):
James E. Blair70c71582013-03-06 08:50:50 -0800510 return False
511
James E. Blair83005782015-12-11 14:46:03 -0800512 if self.file_matcher and not self.file_matcher.matches(change):
James E. Blair70c71582013-03-06 08:50:50 -0800513 return False
514
James E. Blair83005782015-12-11 14:46:03 -0800515 # NB: This is a negative match.
516 if (self.irrelevant_file_matcher and
517 self.irrelevant_file_matcher.matches(change)):
Maru Newby3fe5f852015-01-13 04:22:14 +0000518 return False
519
James E. Blair70c71582013-03-06 08:50:50 -0800520 return True
James E. Blaire5a847f2012-07-10 15:29:14 -0700521
James E. Blair1e8dd892012-05-30 09:15:05 -0700522
James E. Blairee743612012-05-29 14:49:32 -0700523class JobTree(object):
524 """ A JobTree represents an instance of one Job, and holds JobTrees
525 whose jobs should be run if that Job succeeds. A root node of a
526 JobTree will have no associated Job. """
527
528 def __init__(self, job):
529 self.job = job
530 self.job_trees = []
531
532 def addJob(self, job):
James E. Blair12a92b12014-03-26 11:54:53 -0700533 if job not in [x.job for x in self.job_trees]:
534 t = JobTree(job)
535 self.job_trees.append(t)
536 return t
James E. Blaire4ad55a2015-06-11 08:22:43 -0700537 for tree in self.job_trees:
538 if tree.job == job:
539 return tree
James E. Blairee743612012-05-29 14:49:32 -0700540
541 def getJobs(self):
542 jobs = []
543 for x in self.job_trees:
544 jobs.append(x.job)
545 jobs.extend(x.getJobs())
546 return jobs
547
548 def getJobTreeForJob(self, job):
549 if self.job == job:
550 return self
551 for tree in self.job_trees:
552 ret = tree.getJobTreeForJob(job)
553 if ret:
554 return ret
555 return None
556
James E. Blairb97ed802015-12-21 15:55:35 -0800557 def inheritFrom(self, other):
558 if other.job:
559 self.job = Job(other.job.name)
560 self.job.inheritFrom(other.job)
561 for other_tree in other.job_trees:
562 this_tree = self.getJobTreeForJob(other_tree.job)
563 if not this_tree:
564 this_tree = JobTree(None)
565 self.job_trees.append(this_tree)
566 this_tree.inheritFrom(other_tree)
567
James E. Blair1e8dd892012-05-30 09:15:05 -0700568
James E. Blair4aea70c2012-07-26 14:23:24 -0700569class Build(object):
570 def __init__(self, job, uuid):
571 self.job = job
572 self.uuid = uuid
James E. Blair4aea70c2012-07-26 14:23:24 -0700573 self.url = None
574 self.number = None
575 self.result = None
576 self.build_set = None
577 self.launch_time = time.time()
James E. Blair71e94122012-12-24 17:53:08 -0800578 self.start_time = None
579 self.end_time = None
James E. Blairbea9ef12013-07-15 11:52:23 -0700580 self.estimated_time = None
James E. Blair66eeebf2013-07-27 17:44:32 -0700581 self.pipeline = None
James E. Blair0aac4872013-08-23 14:02:38 -0700582 self.canceled = False
James E. Blair4a28a882013-08-23 15:17:33 -0700583 self.retry = False
James E. Blaird78576a2013-07-09 10:39:17 -0700584 self.parameters = {}
Joshua Heskethba8776a2014-01-12 14:35:40 +0800585 self.worker = Worker()
Timothy Chavezb2332082015-08-07 20:08:04 -0500586 self.node_labels = []
587 self.node_name = None
James E. Blairee743612012-05-29 14:49:32 -0700588
589 def __repr__(self):
Joshua Heskethba8776a2014-01-12 14:35:40 +0800590 return ('<Build %s of %s on %s>' %
591 (self.uuid, self.job.name, self.worker))
592
593
594class Worker(object):
595 """A model of the worker running a job"""
596 def __init__(self):
597 self.name = "Unknown"
598 self.hostname = None
599 self.ips = []
600 self.fqdn = None
601 self.program = None
602 self.version = None
603 self.extra = {}
604
605 def updateFromData(self, data):
606 """Update worker information if contained in the WORK_DATA response."""
607 self.name = data.get('worker_name', self.name)
608 self.hostname = data.get('worker_hostname', self.hostname)
609 self.ips = data.get('worker_ips', self.ips)
610 self.fqdn = data.get('worker_fqdn', self.fqdn)
611 self.program = data.get('worker_program', self.program)
612 self.version = data.get('worker_version', self.version)
613 self.extra = data.get('worker_extra', self.extra)
614
615 def __repr__(self):
616 return '<Worker %s>' % self.name
James E. Blairee743612012-05-29 14:49:32 -0700617
James E. Blair1e8dd892012-05-30 09:15:05 -0700618
James E. Blair7e530ad2012-07-03 16:12:28 -0700619class BuildSet(object):
James E. Blair4076e2b2014-01-28 12:42:20 -0800620 # Merge states:
621 NEW = 1
622 PENDING = 2
623 COMPLETE = 3
624
Antoine Musso9b229282014-08-18 23:45:43 +0200625 states_map = {
626 1: 'NEW',
627 2: 'PENDING',
628 3: 'COMPLETE',
629 }
630
James E. Blairfee8d652013-06-07 08:57:52 -0700631 def __init__(self, item):
632 self.item = item
James E. Blair11700c32012-07-05 17:50:05 -0700633 self.other_changes = []
James E. Blair7e530ad2012-07-03 16:12:28 -0700634 self.builds = {}
James E. Blair11700c32012-07-05 17:50:05 -0700635 self.result = None
636 self.next_build_set = None
637 self.previous_build_set = None
James E. Blair4886cc12012-07-18 15:39:41 -0700638 self.ref = None
James E. Blair81515ad2012-10-01 18:29:08 -0700639 self.commit = None
James E. Blair4076e2b2014-01-28 12:42:20 -0800640 self.zuul_url = None
James E. Blair973721f2012-08-15 10:19:43 -0700641 self.unable_to_merge = False
James E. Blair972e3c72013-08-29 12:04:55 -0700642 self.failing_reasons = []
James E. Blair4076e2b2014-01-28 12:42:20 -0800643 self.merge_state = self.NEW
James E. Blair7e530ad2012-07-03 16:12:28 -0700644
Antoine Musso9b229282014-08-18 23:45:43 +0200645 def __repr__(self):
646 return '<BuildSet item: %s #builds: %s merge state: %s>' % (
647 self.item,
648 len(self.builds),
649 self.getStateName(self.merge_state))
650
James E. Blair4886cc12012-07-18 15:39:41 -0700651 def setConfiguration(self):
James E. Blair11700c32012-07-05 17:50:05 -0700652 # The change isn't enqueued until after it's created
653 # so we don't know what the other changes ahead will be
654 # until jobs start.
655 if not self.other_changes:
James E. Blairfee8d652013-06-07 08:57:52 -0700656 next_item = self.item.item_ahead
657 while next_item:
658 self.other_changes.append(next_item.change)
659 next_item = next_item.item_ahead
James E. Blair4886cc12012-07-18 15:39:41 -0700660 if not self.ref:
661 self.ref = 'Z' + uuid4().hex
662
Antoine Musso9b229282014-08-18 23:45:43 +0200663 def getStateName(self, state_num):
664 return self.states_map.get(
665 state_num, 'UNKNOWN (%s)' % state_num)
666
James E. Blair4886cc12012-07-18 15:39:41 -0700667 def addBuild(self, build):
668 self.builds[build.job.name] = build
669 build.build_set = self
James E. Blair11700c32012-07-05 17:50:05 -0700670
James E. Blair4a28a882013-08-23 15:17:33 -0700671 def removeBuild(self, build):
672 del self.builds[build.job.name]
673
James E. Blair7e530ad2012-07-03 16:12:28 -0700674 def getBuild(self, job_name):
675 return self.builds.get(job_name)
676
James E. Blair11700c32012-07-05 17:50:05 -0700677 def getBuilds(self):
678 keys = self.builds.keys()
679 keys.sort()
680 return [self.builds.get(x) for x in keys]
681
James E. Blair7e530ad2012-07-03 16:12:28 -0700682
James E. Blairfee8d652013-06-07 08:57:52 -0700683class QueueItem(object):
684 """A changish inside of a Pipeline queue"""
James E. Blair32663402012-06-01 10:04:18 -0700685
James E. Blairbfb8e042014-12-30 17:01:44 -0800686 def __init__(self, queue, change):
687 self.pipeline = queue.pipeline
688 self.queue = queue
James E. Blairfee8d652013-06-07 08:57:52 -0700689 self.change = change # a changeish
James E. Blair7e530ad2012-07-03 16:12:28 -0700690 self.build_sets = []
James E. Blaircaec0c52012-08-22 14:52:22 -0700691 self.dequeued_needing_change = False
James E. Blair11700c32012-07-05 17:50:05 -0700692 self.current_build_set = BuildSet(self)
693 self.build_sets.append(self.current_build_set)
James E. Blairfee8d652013-06-07 08:57:52 -0700694 self.item_ahead = None
James E. Blair972e3c72013-08-29 12:04:55 -0700695 self.items_behind = []
James E. Blair8fa16972013-01-15 16:57:20 -0800696 self.enqueue_time = None
697 self.dequeue_time = None
James E. Blairfee8d652013-06-07 08:57:52 -0700698 self.reported = False
James E. Blairbfb8e042014-12-30 17:01:44 -0800699 self.active = False # Whether an item is within an active window
700 self.live = True # Whether an item is intended to be processed at all
James E. Blair83005782015-12-11 14:46:03 -0800701 self.job_tree = None
James E. Blaire5a847f2012-07-10 15:29:14 -0700702
James E. Blair972e3c72013-08-29 12:04:55 -0700703 def __repr__(self):
704 if self.pipeline:
705 pipeline = self.pipeline.name
706 else:
707 pipeline = None
708 return '<QueueItem 0x%x for %s in %s>' % (
709 id(self), self.change, pipeline)
710
James E. Blairee743612012-05-29 14:49:32 -0700711 def resetAllBuilds(self):
James E. Blair11700c32012-07-05 17:50:05 -0700712 old = self.current_build_set
713 self.current_build_set.result = 'CANCELED'
714 self.current_build_set = BuildSet(self)
715 old.next_build_set = self.current_build_set
716 self.current_build_set.previous_build_set = old
James E. Blair7e530ad2012-07-03 16:12:28 -0700717 self.build_sets.append(self.current_build_set)
James E. Blairee743612012-05-29 14:49:32 -0700718
719 def addBuild(self, build):
James E. Blair7e530ad2012-07-03 16:12:28 -0700720 self.current_build_set.addBuild(build)
James E. Blair66eeebf2013-07-27 17:44:32 -0700721 build.pipeline = self.pipeline
James E. Blairee743612012-05-29 14:49:32 -0700722
James E. Blair4a28a882013-08-23 15:17:33 -0700723 def removeBuild(self, build):
724 self.current_build_set.removeBuild(build)
725
James E. Blairfee8d652013-06-07 08:57:52 -0700726 def setReportedResult(self, result):
727 self.current_build_set.result = result
728
James E. Blair83005782015-12-11 14:46:03 -0800729 def _createJobTree(self, job_trees, parent):
730 for tree in job_trees:
731 job = tree.job
732 if not job.changeMatches(self.change):
733 continue
734 frozen_job = Job(job.name)
735 frozen_tree = JobTree(frozen_job)
736 inherited = set()
737 for variant in self.pipeline.layout.getJobs(job.name):
738 if variant.changeMatches(self.change):
739 if variant not in inherited:
740 frozen_job.inheritFrom(variant)
741 inherited.add(variant)
742 if job not in inherited:
743 # Only update from the job in the tree if it is
744 # unique, otherwise we might unset an attribute we
745 # have overloaded.
746 frozen_job.inheritFrom(job)
747 parent.job_trees.append(frozen_tree)
748 self._createJobTree(tree.job_trees, frozen_tree)
749
750 def createJobTree(self):
751 project_tree = self.pipeline.getJobTree(self.change.project)
752 ret = JobTree(None)
753 self._createJobTree(project_tree.job_trees, ret)
754 return ret
755
756 def freezeJobTree(self):
757 """Find or create actual matching jobs for this item's change and
758 store the resulting job tree."""
759 self.job_tree = self.createJobTree()
760
761 def getJobs(self):
762 if not self.live or not self.job_tree:
763 return []
764 return self.job_tree.getJobs()
765
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800766 def formatJSON(self):
767 changeish = self.change
768 ret = {}
769 ret['active'] = self.active
James E. Blair107c3852015-02-07 08:23:10 -0800770 ret['live'] = self.live
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800771 if hasattr(changeish, 'url') and changeish.url is not None:
772 ret['url'] = changeish.url
773 else:
774 ret['url'] = None
775 ret['id'] = changeish._id()
776 if self.item_ahead:
777 ret['item_ahead'] = self.item_ahead.change._id()
778 else:
779 ret['item_ahead'] = None
780 ret['items_behind'] = [i.change._id() for i in self.items_behind]
781 ret['failing_reasons'] = self.current_build_set.failing_reasons
782 ret['zuul_ref'] = self.current_build_set.ref
Ramy Asselin07cc33c2015-06-12 14:06:34 -0700783 if changeish.project:
784 ret['project'] = changeish.project.name
785 else:
786 # For cross-project dependencies with the depends-on
787 # project not known to zuul, the project is None
788 # Set it to a static value
789 ret['project'] = "Unknown Project"
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800790 ret['enqueue_time'] = int(self.enqueue_time * 1000)
791 ret['jobs'] = []
Davanum Srinivasb6bfbcc2014-11-18 13:26:52 -0500792 if hasattr(changeish, 'owner'):
793 ret['owner'] = changeish.owner
794 else:
795 ret['owner'] = None
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800796 max_remaining = 0
James E. Blair107c3852015-02-07 08:23:10 -0800797 for job in self.pipeline.getJobs(self):
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800798 now = time.time()
799 build = self.current_build_set.getBuild(job.name)
800 elapsed = None
801 remaining = None
802 result = None
803 url = None
804 worker = None
805 if build:
806 result = build.result
807 url = build.url
808 if build.start_time:
809 if build.end_time:
810 elapsed = int((build.end_time -
811 build.start_time) * 1000)
812 remaining = 0
813 else:
814 elapsed = int((now - build.start_time) * 1000)
815 if build.estimated_time:
816 remaining = max(
817 int(build.estimated_time * 1000) - elapsed,
818 0)
819 worker = {
820 'name': build.worker.name,
821 'hostname': build.worker.hostname,
822 'ips': build.worker.ips,
823 'fqdn': build.worker.fqdn,
824 'program': build.worker.program,
825 'version': build.worker.version,
826 'extra': build.worker.extra
827 }
828 if remaining and remaining > max_remaining:
829 max_remaining = remaining
830
831 ret['jobs'].append({
832 'name': job.name,
833 'elapsed_time': elapsed,
834 'remaining_time': remaining,
835 'url': url,
836 'result': result,
837 'voting': job.voting,
838 'uuid': build.uuid if build else None,
839 'launch_time': build.launch_time if build else None,
840 'start_time': build.start_time if build else None,
841 'end_time': build.end_time if build else None,
842 'estimated_time': build.estimated_time if build else None,
843 'pipeline': build.pipeline.name if build else None,
844 'canceled': build.canceled if build else None,
845 'retry': build.retry if build else None,
846 'number': build.number if build else None,
Timothy Chavezb2332082015-08-07 20:08:04 -0500847 'node_labels': build.node_labels if build else [],
848 'node_name': build.node_name if build else None,
849 'worker': worker,
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800850 })
851
852 if self.pipeline.haveAllJobsStarted(self):
853 ret['remaining_time'] = max_remaining
854 else:
855 ret['remaining_time'] = None
856 return ret
857
858 def formatStatus(self, indent=0, html=False):
859 changeish = self.change
860 indent_str = ' ' * indent
861 ret = ''
862 if html and hasattr(changeish, 'url') and changeish.url is not None:
863 ret += '%sProject %s change <a href="%s">%s</a>\n' % (
864 indent_str,
865 changeish.project.name,
866 changeish.url,
867 changeish._id())
868 else:
869 ret += '%sProject %s change %s based on %s\n' % (
870 indent_str,
871 changeish.project.name,
872 changeish._id(),
873 self.item_ahead)
James E. Blair107c3852015-02-07 08:23:10 -0800874 for job in self.pipeline.getJobs(self):
Joshua Hesketh85af4e92014-02-21 08:28:58 -0800875 build = self.current_build_set.getBuild(job.name)
876 if build:
877 result = build.result
878 else:
879 result = None
880 job_name = job.name
881 if not job.voting:
882 voting = ' (non-voting)'
883 else:
884 voting = ''
885 if html:
886 if build:
887 url = build.url
888 else:
889 url = None
890 if url is not None:
891 job_name = '<a href="%s">%s</a>' % (url, job_name)
892 ret += '%s %s: %s%s' % (indent_str, job_name, result, voting)
893 ret += '\n'
894 return ret
895
James E. Blairfee8d652013-06-07 08:57:52 -0700896
897class Changeish(object):
898 """Something like a change; either a change or a ref"""
James E. Blairfee8d652013-06-07 08:57:52 -0700899
900 def __init__(self, project):
901 self.project = project
902
Joshua Hesketh36c3fa52014-01-22 11:40:52 +1100903 def getBasePath(self):
904 base_path = ''
905 if hasattr(self, 'refspec'):
906 base_path = "%s/%s/%s" % (
907 self.number[-2:], self.number, self.patchset)
908 elif hasattr(self, 'ref'):
909 base_path = "%s/%s" % (self.newrev[:2], self.newrev)
910
911 return base_path
912
James E. Blairfee8d652013-06-07 08:57:52 -0700913 def equals(self, other):
914 raise NotImplementedError()
915
916 def isUpdateOf(self, other):
917 raise NotImplementedError()
918
919 def filterJobs(self, jobs):
920 return filter(lambda job: job.changeMatches(self), jobs)
921
922 def getRelatedChanges(self):
923 return set()
924
James E. Blair1e8dd892012-05-30 09:15:05 -0700925
James E. Blair4aea70c2012-07-26 14:23:24 -0700926class Change(Changeish):
James E. Blair4aea70c2012-07-26 14:23:24 -0700927 def __init__(self, project):
928 super(Change, self).__init__(project)
929 self.branch = None
930 self.number = None
931 self.url = None
932 self.patchset = None
933 self.refspec = None
934
James E. Blair70c71582013-03-06 08:50:50 -0800935 self.files = []
James E. Blair6965a4b2014-12-16 17:19:04 -0800936 self.needs_changes = []
James E. Blair4aea70c2012-07-26 14:23:24 -0700937 self.needed_by_changes = []
938 self.is_current_patchset = True
939 self.can_merge = False
940 self.is_merged = False
James E. Blairfee8d652013-06-07 08:57:52 -0700941 self.failed_to_merge = False
James E. Blairc053d022014-01-22 14:57:33 -0800942 self.approvals = []
James E. Blair11041d22014-05-02 14:49:53 -0700943 self.open = None
944 self.status = None
Davanum Srinivasb6bfbcc2014-11-18 13:26:52 -0500945 self.owner = None
James E. Blair4aea70c2012-07-26 14:23:24 -0700946
947 def _id(self):
James E. Blairbe765db2012-08-07 08:36:20 -0700948 return '%s,%s' % (self.number, self.patchset)
James E. Blair4aea70c2012-07-26 14:23:24 -0700949
950 def __repr__(self):
951 return '<Change 0x%x %s>' % (id(self), self._id())
952
953 def equals(self, other):
Zhongyue Luoaa85ebf2012-09-21 16:38:33 +0800954 if self.number == other.number and self.patchset == other.patchset:
James E. Blair4aea70c2012-07-26 14:23:24 -0700955 return True
956 return False
957
James E. Blair2fa50962013-01-30 21:50:41 -0800958 def isUpdateOf(self, other):
Clark Boylan01976242013-02-17 18:41:48 -0800959 if ((hasattr(other, 'number') and self.number == other.number) and
James E. Blair7a192e42013-07-11 14:10:36 -0700960 (hasattr(other, 'patchset') and
961 self.patchset is not None and
962 other.patchset is not None and
963 int(self.patchset) > int(other.patchset))):
James E. Blair2fa50962013-01-30 21:50:41 -0800964 return True
965 return False
966
James E. Blairfee8d652013-06-07 08:57:52 -0700967 def getRelatedChanges(self):
968 related = set()
James E. Blair6965a4b2014-12-16 17:19:04 -0800969 for c in self.needs_changes:
970 related.add(c)
James E. Blairfee8d652013-06-07 08:57:52 -0700971 for c in self.needed_by_changes:
972 related.add(c)
973 related.update(c.getRelatedChanges())
974 return related
James E. Blair4aea70c2012-07-26 14:23:24 -0700975
976
977class Ref(Changeish):
James E. Blair4aea70c2012-07-26 14:23:24 -0700978 def __init__(self, project):
James E. Blairbe765db2012-08-07 08:36:20 -0700979 super(Ref, self).__init__(project)
James E. Blair4aea70c2012-07-26 14:23:24 -0700980 self.ref = None
981 self.oldrev = None
982 self.newrev = None
983
James E. Blairbe765db2012-08-07 08:36:20 -0700984 def _id(self):
985 return self.newrev
986
Antoine Musso68bdcd72013-01-17 12:31:28 +0100987 def __repr__(self):
988 rep = None
989 if self.newrev == '0000000000000000000000000000000000000000':
990 rep = '<Ref 0x%x deletes %s from %s' % (
991 id(self), self.ref, self.oldrev)
992 elif self.oldrev == '0000000000000000000000000000000000000000':
993 rep = '<Ref 0x%x creates %s on %s>' % (
994 id(self), self.ref, self.newrev)
995 else:
996 # Catch all
997 rep = '<Ref 0x%x %s updated %s..%s>' % (
998 id(self), self.ref, self.oldrev, self.newrev)
999
1000 return rep
1001
James E. Blair4aea70c2012-07-26 14:23:24 -07001002 def equals(self, other):
James E. Blair9358c612012-09-28 08:29:39 -07001003 if (self.project == other.project
1004 and self.ref == other.ref
1005 and self.newrev == other.newrev):
James E. Blair4aea70c2012-07-26 14:23:24 -07001006 return True
1007 return False
1008
James E. Blair2fa50962013-01-30 21:50:41 -08001009 def isUpdateOf(self, other):
1010 return False
1011
James E. Blair4aea70c2012-07-26 14:23:24 -07001012
James E. Blair63bb0ef2013-07-29 17:14:51 -07001013class NullChange(Changeish):
James E. Blaire5910202013-12-27 09:50:31 -08001014 def __repr__(self):
1015 return '<NullChange for %s>' % (self.project)
James E. Blair63bb0ef2013-07-29 17:14:51 -07001016
James E. Blair63bb0ef2013-07-29 17:14:51 -07001017 def _id(self):
Alex Gaynorddb9ef32013-09-16 21:04:58 -07001018 return None
James E. Blair63bb0ef2013-07-29 17:14:51 -07001019
1020 def equals(self, other):
Steve Varnau7b78b312015-04-03 14:49:46 -07001021 if (self.project == other.project
1022 and other._id() is None):
James E. Blair4f6033c2014-03-27 15:49:09 -07001023 return True
James E. Blair63bb0ef2013-07-29 17:14:51 -07001024 return False
1025
1026 def isUpdateOf(self, other):
1027 return False
1028
1029
James E. Blairee743612012-05-29 14:49:32 -07001030class TriggerEvent(object):
1031 def __init__(self):
1032 self.data = None
James E. Blair32663402012-06-01 10:04:18 -07001033 # common
James E. Blairee743612012-05-29 14:49:32 -07001034 self.type = None
1035 self.project_name = None
James E. Blair6c358e72013-07-29 17:06:47 -07001036 self.trigger_name = None
Antoine Mussob4e809e2012-12-06 16:58:06 +01001037 # Representation of the user account that performed the event.
1038 self.account = None
James E. Blair32663402012-06-01 10:04:18 -07001039 # patchset-created, comment-added, etc.
James E. Blairee743612012-05-29 14:49:32 -07001040 self.change_number = None
Clark Boylanfc56df32012-06-28 15:25:57 -07001041 self.change_url = None
James E. Blairee743612012-05-29 14:49:32 -07001042 self.patch_number = None
James E. Blaira03262c2012-05-30 09:41:16 -07001043 self.refspec = None
James E. Blairee743612012-05-29 14:49:32 -07001044 self.approvals = []
1045 self.branch = None
Clark Boylanb9bcb402012-06-29 17:44:05 -07001046 self.comment = None
James E. Blair32663402012-06-01 10:04:18 -07001047 # ref-updated
James E. Blairee743612012-05-29 14:49:32 -07001048 self.ref = None
James E. Blair32663402012-06-01 10:04:18 -07001049 self.oldrev = None
James E. Blair89cae0f2012-07-18 11:18:32 -07001050 self.newrev = None
James E. Blair63bb0ef2013-07-29 17:14:51 -07001051 # timer
1052 self.timespec = None
James E. Blairc494d542014-08-06 09:23:52 -07001053 # zuultrigger
1054 self.pipeline_name = None
James E. Blairad28e912013-11-27 10:43:22 -08001055 # For events that arrive with a destination pipeline (eg, from
1056 # an admin command, etc):
1057 self.forced_pipeline = None
James E. Blairee743612012-05-29 14:49:32 -07001058
James E. Blair9f9667e2012-06-12 17:51:08 -07001059 def __repr__(self):
James E. Blairee743612012-05-29 14:49:32 -07001060 ret = '<TriggerEvent %s %s' % (self.type, self.project_name)
James E. Blair1e8dd892012-05-30 09:15:05 -07001061
James E. Blairee743612012-05-29 14:49:32 -07001062 if self.branch:
1063 ret += " %s" % self.branch
1064 if self.change_number:
1065 ret += " %s,%s" % (self.change_number, self.patch_number)
1066 if self.approvals:
James E. Blair1e8dd892012-05-30 09:15:05 -07001067 ret += ' ' + ', '.join(
1068 ['%s:%s' % (a['type'], a['value']) for a in self.approvals])
James E. Blairee743612012-05-29 14:49:32 -07001069 ret += '>'
1070
1071 return ret
1072
James E. Blair1e8dd892012-05-30 09:15:05 -07001073
James E. Blair9c17dbf2014-06-23 14:21:58 -07001074class BaseFilter(object):
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001075 def __init__(self, required_approvals=[], reject_approvals=[]):
James E. Blair5bf78a32015-07-30 18:08:24 +00001076 self._required_approvals = copy.deepcopy(required_approvals)
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001077 self.required_approvals = self._tidy_approvals(required_approvals)
1078 self._reject_approvals = copy.deepcopy(reject_approvals)
1079 self.reject_approvals = self._tidy_approvals(reject_approvals)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001080
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001081 def _tidy_approvals(self, approvals):
1082 for a in approvals:
James E. Blair9c17dbf2014-06-23 14:21:58 -07001083 for k, v in a.items():
1084 if k == 'username':
1085 pass
James E. Blair1fbfceb2014-06-23 14:42:53 -07001086 elif k in ['email', 'email-filter']:
James E. Blair5bf78a32015-07-30 18:08:24 +00001087 a['email'] = re.compile(v)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001088 elif k == 'newer-than':
James E. Blair5bf78a32015-07-30 18:08:24 +00001089 a[k] = time_to_seconds(v)
James E. Blair9c17dbf2014-06-23 14:21:58 -07001090 elif k == 'older-than':
James E. Blair5bf78a32015-07-30 18:08:24 +00001091 a[k] = time_to_seconds(v)
James E. Blair1fbfceb2014-06-23 14:42:53 -07001092 if 'email-filter' in a:
1093 del a['email-filter']
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001094 return approvals
1095
1096 def _match_approval_required_approval(self, rapproval, approval):
1097 # Check if the required approval and approval match
1098 if 'description' not in approval:
1099 return False
1100 now = time.time()
1101 by = approval.get('by', {})
1102 for k, v in rapproval.items():
1103 if k == 'username':
1104 if (by.get('username', '') != v):
1105 return False
1106 elif k == 'email':
1107 if (not v.search(by.get('email', ''))):
1108 return False
1109 elif k == 'newer-than':
1110 t = now - v
1111 if (approval['grantedOn'] < t):
1112 return False
1113 elif k == 'older-than':
1114 t = now - v
1115 if (approval['grantedOn'] >= t):
1116 return False
1117 else:
1118 if not isinstance(v, list):
1119 v = [v]
1120 if (normalizeCategory(approval['description']) != k or
1121 int(approval['value']) not in v):
1122 return False
1123 return True
1124
1125 def matchesApprovals(self, change):
1126 if (self.required_approvals and not change.approvals
1127 or self.reject_approvals and not change.approvals):
1128 # A change with no approvals can not match
1129 return False
1130
1131 # TODO(jhesketh): If we wanted to optimise this slightly we could
1132 # analyse both the REQUIRE and REJECT filters by looping over the
1133 # approvals on the change and keeping track of what we have checked
1134 # rather than needing to loop on the change approvals twice
1135 return (self.matchesRequiredApprovals(change) and
1136 self.matchesNoRejectApprovals(change))
James E. Blair9c17dbf2014-06-23 14:21:58 -07001137
1138 def matchesRequiredApprovals(self, change):
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001139 # Check if any approvals match the requirements
James E. Blair5bf78a32015-07-30 18:08:24 +00001140 for rapproval in self.required_approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001141 matches_rapproval = False
James E. Blair9c17dbf2014-06-23 14:21:58 -07001142 for approval in change.approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001143 if self._match_approval_required_approval(rapproval, approval):
1144 # We have a matching approval so this requirement is
1145 # fulfilled
1146 matches_rapproval = True
James E. Blair5bf78a32015-07-30 18:08:24 +00001147 break
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001148 if not matches_rapproval:
James E. Blair5bf78a32015-07-30 18:08:24 +00001149 return False
James E. Blair9c17dbf2014-06-23 14:21:58 -07001150 return True
1151
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001152 def matchesNoRejectApprovals(self, change):
1153 # Check to make sure no approvals match a reject criteria
1154 for rapproval in self.reject_approvals:
1155 for approval in change.approvals:
1156 if self._match_approval_required_approval(rapproval, approval):
1157 # A reject approval has been matched, so we reject
1158 # immediately
1159 return False
1160 # To get here no rejects can have been matched so we should be good to
1161 # queue
1162 return True
1163
James E. Blair9c17dbf2014-06-23 14:21:58 -07001164
1165class EventFilter(BaseFilter):
James E. Blairc0dedf82014-08-06 09:37:52 -07001166 def __init__(self, trigger, types=[], branches=[], refs=[],
1167 event_approvals={}, comments=[], emails=[], usernames=[],
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001168 timespecs=[], required_approvals=[], reject_approvals=[],
1169 pipelines=[], ignore_deletes=True):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001170 super(EventFilter, self).__init__(
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001171 required_approvals=required_approvals,
1172 reject_approvals=reject_approvals)
James E. Blairc0dedf82014-08-06 09:37:52 -07001173 self.trigger = trigger
James E. Blairee743612012-05-29 14:49:32 -07001174 self._types = types
1175 self._branches = branches
1176 self._refs = refs
James E. Blair1fbfceb2014-06-23 14:42:53 -07001177 self._comments = comments
1178 self._emails = emails
1179 self._usernames = usernames
James E. Blairc494d542014-08-06 09:23:52 -07001180 self._pipelines = pipelines
James E. Blairee743612012-05-29 14:49:32 -07001181 self.types = [re.compile(x) for x in types]
1182 self.branches = [re.compile(x) for x in branches]
1183 self.refs = [re.compile(x) for x in refs]
James E. Blair1fbfceb2014-06-23 14:42:53 -07001184 self.comments = [re.compile(x) for x in comments]
1185 self.emails = [re.compile(x) for x in emails]
1186 self.usernames = [re.compile(x) for x in usernames]
James E. Blairc494d542014-08-06 09:23:52 -07001187 self.pipelines = [re.compile(x) for x in pipelines]
James E. Blairc053d022014-01-22 14:57:33 -08001188 self.event_approvals = event_approvals
James E. Blair63bb0ef2013-07-29 17:14:51 -07001189 self.timespecs = timespecs
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001190 self.ignore_deletes = ignore_deletes
James E. Blairee743612012-05-29 14:49:32 -07001191
James E. Blair9f9667e2012-06-12 17:51:08 -07001192 def __repr__(self):
James E. Blairee743612012-05-29 14:49:32 -07001193 ret = '<EventFilter'
James E. Blair1e8dd892012-05-30 09:15:05 -07001194
James E. Blairee743612012-05-29 14:49:32 -07001195 if self._types:
1196 ret += ' types: %s' % ', '.join(self._types)
James E. Blairc494d542014-08-06 09:23:52 -07001197 if self._pipelines:
1198 ret += ' pipelines: %s' % ', '.join(self._pipelines)
James E. Blairee743612012-05-29 14:49:32 -07001199 if self._branches:
1200 ret += ' branches: %s' % ', '.join(self._branches)
1201 if self._refs:
1202 ret += ' refs: %s' % ', '.join(self._refs)
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001203 if self.ignore_deletes:
1204 ret += ' ignore_deletes: %s' % self.ignore_deletes
James E. Blairc053d022014-01-22 14:57:33 -08001205 if self.event_approvals:
1206 ret += ' event_approvals: %s' % ', '.join(
1207 ['%s:%s' % a for a in self.event_approvals.items()])
James E. Blair5bf78a32015-07-30 18:08:24 +00001208 if self.required_approvals:
1209 ret += ' required_approvals: %s' % ', '.join(
1210 ['%s' % a for a in self._required_approvals])
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001211 if self.reject_approvals:
1212 ret += ' reject_approvals: %s' % ', '.join(
1213 ['%s' % a for a in self._reject_approvals])
James E. Blair1fbfceb2014-06-23 14:42:53 -07001214 if self._comments:
1215 ret += ' comments: %s' % ', '.join(self._comments)
1216 if self._emails:
1217 ret += ' emails: %s' % ', '.join(self._emails)
1218 if self._usernames:
1219 ret += ' username_filters: %s' % ', '.join(self._usernames)
James E. Blair63bb0ef2013-07-29 17:14:51 -07001220 if self.timespecs:
1221 ret += ' timespecs: %s' % ', '.join(self.timespecs)
James E. Blairee743612012-05-29 14:49:32 -07001222 ret += '>'
1223
1224 return ret
1225
James E. Blairc053d022014-01-22 14:57:33 -08001226 def matches(self, event, change):
James E. Blairee743612012-05-29 14:49:32 -07001227 # event types are ORed
1228 matches_type = False
1229 for etype in self.types:
1230 if etype.match(event.type):
1231 matches_type = True
1232 if self.types and not matches_type:
1233 return False
1234
James E. Blairc494d542014-08-06 09:23:52 -07001235 # pipelines are ORed
1236 matches_pipeline = False
1237 for epipe in self.pipelines:
1238 if epipe.match(event.pipeline_name):
1239 matches_pipeline = True
1240 if self.pipelines and not matches_pipeline:
1241 return False
1242
James E. Blairee743612012-05-29 14:49:32 -07001243 # branches are ORed
1244 matches_branch = False
1245 for branch in self.branches:
1246 if branch.match(event.branch):
1247 matches_branch = True
1248 if self.branches and not matches_branch:
1249 return False
1250
1251 # refs are ORed
1252 matches_ref = False
Yolanda Robla16698872014-08-25 11:59:27 +02001253 if event.ref is not None:
1254 for ref in self.refs:
1255 if ref.match(event.ref):
1256 matches_ref = True
James E. Blairee743612012-05-29 14:49:32 -07001257 if self.refs and not matches_ref:
1258 return False
K Jonathan Harkerf95e7232015-04-29 13:33:16 -07001259 if self.ignore_deletes and event.newrev == EMPTY_GIT_REF:
1260 # If the updated ref has an empty git sha (all 0s),
1261 # then the ref is being deleted
1262 return False
James E. Blairee743612012-05-29 14:49:32 -07001263
James E. Blair1fbfceb2014-06-23 14:42:53 -07001264 # comments are ORed
1265 matches_comment_re = False
1266 for comment_re in self.comments:
Clark Boylanb9bcb402012-06-29 17:44:05 -07001267 if (event.comment is not None and
James E. Blair1fbfceb2014-06-23 14:42:53 -07001268 comment_re.search(event.comment)):
1269 matches_comment_re = True
1270 if self.comments and not matches_comment_re:
Clark Boylanb9bcb402012-06-29 17:44:05 -07001271 return False
1272
Antoine Mussob4e809e2012-12-06 16:58:06 +01001273 # We better have an account provided by Gerrit to do
1274 # email filtering.
1275 if event.account is not None:
James E. Blaircf429f32012-12-20 14:28:24 -08001276 account_email = event.account.get('email')
James E. Blair1fbfceb2014-06-23 14:42:53 -07001277 # emails are ORed
1278 matches_email_re = False
1279 for email_re in self.emails:
Antoine Mussob4e809e2012-12-06 16:58:06 +01001280 if (account_email is not None and
Joshua Hesketh29d99b72014-08-19 16:27:42 +10001281 email_re.search(account_email)):
James E. Blair1fbfceb2014-06-23 14:42:53 -07001282 matches_email_re = True
1283 if self.emails and not matches_email_re:
Antoine Mussob4e809e2012-12-06 16:58:06 +01001284 return False
1285
James E. Blair1fbfceb2014-06-23 14:42:53 -07001286 # usernames are ORed
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001287 account_username = event.account.get('username')
James E. Blair1fbfceb2014-06-23 14:42:53 -07001288 matches_username_re = False
1289 for username_re in self.usernames:
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001290 if (account_username is not None and
James E. Blair1fbfceb2014-06-23 14:42:53 -07001291 username_re.search(account_username)):
1292 matches_username_re = True
1293 if self.usernames and not matches_username_re:
Joshua Heskethb8a817e2013-12-27 11:21:38 +11001294 return False
1295
James E. Blairee743612012-05-29 14:49:32 -07001296 # approvals are ANDed
James E. Blairc053d022014-01-22 14:57:33 -08001297 for category, value in self.event_approvals.items():
James E. Blairee743612012-05-29 14:49:32 -07001298 matches_approval = False
1299 for eapproval in event.approvals:
1300 if (normalizeCategory(eapproval['description']) == category and
1301 int(eapproval['value']) == int(value)):
1302 matches_approval = True
James E. Blair1e8dd892012-05-30 09:15:05 -07001303 if not matches_approval:
1304 return False
James E. Blair63bb0ef2013-07-29 17:14:51 -07001305
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001306 # required approvals are ANDed (reject approvals are ORed)
1307 if not self.matchesApprovals(change):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001308 return False
James E. Blairc053d022014-01-22 14:57:33 -08001309
James E. Blair63bb0ef2013-07-29 17:14:51 -07001310 # timespecs are ORed
1311 matches_timespec = False
1312 for timespec in self.timespecs:
1313 if (event.timespec == timespec):
1314 matches_timespec = True
1315 if self.timespecs and not matches_timespec:
1316 return False
1317
James E. Blairee743612012-05-29 14:49:32 -07001318 return True
James E. Blaireff88162013-07-01 12:44:14 -04001319
1320
James E. Blair9c17dbf2014-06-23 14:21:58 -07001321class ChangeishFilter(BaseFilter):
Clark Boylana9702ad2014-05-08 17:17:24 -07001322 def __init__(self, open=None, current_patchset=None,
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001323 statuses=[], required_approvals=[],
1324 reject_approvals=[]):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001325 super(ChangeishFilter, self).__init__(
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001326 required_approvals=required_approvals,
1327 reject_approvals=reject_approvals)
James E. Blair11041d22014-05-02 14:49:53 -07001328 self.open = open
Clark Boylana9702ad2014-05-08 17:17:24 -07001329 self.current_patchset = current_patchset
James E. Blair11041d22014-05-02 14:49:53 -07001330 self.statuses = statuses
James E. Blair11041d22014-05-02 14:49:53 -07001331
1332 def __repr__(self):
1333 ret = '<ChangeishFilter'
1334
1335 if self.open is not None:
1336 ret += ' open: %s' % self.open
Clark Boylana9702ad2014-05-08 17:17:24 -07001337 if self.current_patchset is not None:
1338 ret += ' current-patchset: %s' % self.current_patchset
James E. Blair11041d22014-05-02 14:49:53 -07001339 if self.statuses:
1340 ret += ' statuses: %s' % ', '.join(self.statuses)
James E. Blair5bf78a32015-07-30 18:08:24 +00001341 if self.required_approvals:
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001342 ret += (' required_approvals: %s' %
1343 str(self.required_approvals))
1344 if self.reject_approvals:
1345 ret += (' reject_approvals: %s' %
1346 str(self.reject_approvals))
James E. Blair11041d22014-05-02 14:49:53 -07001347 ret += '>'
1348
1349 return ret
1350
1351 def matches(self, change):
1352 if self.open is not None:
1353 if self.open != change.open:
1354 return False
1355
Clark Boylana9702ad2014-05-08 17:17:24 -07001356 if self.current_patchset is not None:
1357 if self.current_patchset != change.is_current_patchset:
1358 return False
1359
James E. Blair11041d22014-05-02 14:49:53 -07001360 if self.statuses:
1361 if change.status not in self.statuses:
1362 return False
1363
Joshua Hesketh66c8e522014-06-26 15:30:08 +10001364 # required approvals are ANDed (reject approvals are ORed)
1365 if not self.matchesApprovals(change):
James E. Blair9c17dbf2014-06-23 14:21:58 -07001366 return False
James E. Blair11041d22014-05-02 14:49:53 -07001367
1368 return True
1369
1370
James E. Blairb97ed802015-12-21 15:55:35 -08001371class ProjectPipelineConfig(object):
1372 # Represents a project cofiguration in the context of a pipeline
1373 def __init__(self):
1374 self.job_tree = None
1375 self.queue_name = None
1376 # TODOv3(jeblair): add merge mode
1377
1378
1379class ProjectConfig(object):
1380 # Represents a project cofiguration
1381 def __init__(self, name):
1382 self.name = name
1383 self.pipelines = {}
1384
1385
James E. Blaird8e778f2015-12-22 14:09:20 -08001386class UnparsedAbideConfig(object):
1387 # A collection of yaml lists that has not yet been parsed into
1388 # objects.
1389 def __init__(self):
1390 self.tenants = []
1391
1392 def extend(self, conf):
1393 if isinstance(conf, UnparsedAbideConfig):
1394 self.tenants.extend(conf.tenants)
1395 return
1396
1397 if not isinstance(conf, list):
1398 raise Exception("Configuration items must be in the form of "
1399 "a list of dictionaries (when parsing %s)" %
1400 (conf,))
1401 for item in conf:
1402 if not isinstance(item, dict):
1403 raise Exception("Configuration items must be in the form of "
1404 "a list of dictionaries (when parsing %s)" %
1405 (conf,))
1406 if len(item.keys()) > 1:
1407 raise Exception("Configuration item dictionaries must have "
1408 "a single key (when parsing %s)" %
1409 (conf,))
1410 key, value = item.items()[0]
1411 if key == 'tenant':
1412 self.tenants.append(value)
1413 else:
1414 raise Exception("Configuration item not recognized "
1415 "(when parsing %s)" %
1416 (conf,))
1417
1418
1419class UnparsedTenantConfig(object):
1420 # A collection of yaml lists that has not yet been parsed into
1421 # objects.
1422 def __init__(self):
1423 self.pipelines = []
1424 self.jobs = []
1425 self.project_templates = []
1426 self.projects = []
1427
1428 def extend(self, conf):
1429 if isinstance(conf, UnparsedTenantConfig):
1430 self.pipelines.extend(conf.pipelines)
1431 self.jobs.extend(conf.jobs)
1432 self.project_templates.extend(conf.project_templates)
1433 self.projects.extend(conf.projects)
1434 return
1435
1436 if not isinstance(conf, list):
1437 raise Exception("Configuration items must be in the form of "
1438 "a list of dictionaries (when parsing %s)" %
1439 (conf,))
1440 for item in conf:
1441 if not isinstance(item, dict):
1442 raise Exception("Configuration items must be in the form of "
1443 "a list of dictionaries (when parsing %s)" %
1444 (conf,))
1445 if len(item.keys()) > 1:
1446 raise Exception("Configuration item dictionaries must have "
1447 "a single key (when parsing %s)" %
1448 (conf,))
1449 key, value = item.items()[0]
1450 if key == 'project':
1451 self.projects.append(value)
1452 elif key == 'job':
1453 self.jobs.append(value)
1454 elif key == 'project-template':
1455 self.project_templates.append(value)
1456 elif key == 'pipeline':
1457 self.pipelines.append(value)
1458 else:
1459 raise Exception("Configuration item not recognized "
1460 "(when parsing %s)" %
1461 (conf,))
1462
1463
James E. Blaireff88162013-07-01 12:44:14 -04001464class Layout(object):
1465 def __init__(self):
1466 self.projects = {}
James E. Blairb97ed802015-12-21 15:55:35 -08001467 self.project_configs = {}
1468 self.project_templates = {}
James E. Blair5a9918a2013-08-27 10:06:27 -07001469 self.pipelines = OrderedDict()
James E. Blair83005782015-12-11 14:46:03 -08001470 # This is a dictionary of name -> [jobs]. The first element
1471 # of the list is the first job added with that name. It is
1472 # the reference definition for a given job. Subsequent
1473 # elements are aspects of that job with different matchers
1474 # that override some attribute of the job. These aspects all
1475 # inherit from the reference definition.
James E. Blaireff88162013-07-01 12:44:14 -04001476 self.jobs = {}
James E. Blaireff88162013-07-01 12:44:14 -04001477
1478 def getJob(self, name):
1479 if name in self.jobs:
James E. Blair83005782015-12-11 14:46:03 -08001480 return self.jobs[name][0]
James E. Blairb97ed802015-12-21 15:55:35 -08001481 raise Exception("Job %s not defined" % (name,))
James E. Blair83005782015-12-11 14:46:03 -08001482
1483 def getJobs(self, name):
1484 return self.jobs.get(name, [])
1485
1486 def addJob(self, job):
1487 if job.name in self.jobs:
1488 self.jobs[job.name].append(job)
1489 else:
1490 self.jobs[job.name] = [job]
1491
1492 def addPipeline(self, pipeline):
1493 self.pipelines[pipeline.name] = pipeline
James E. Blair59fdbac2015-12-07 17:08:06 -08001494
James E. Blairb97ed802015-12-21 15:55:35 -08001495 def addProjectTemplate(self, project_template):
1496 self.project_templates[project_template.name] = project_template
1497
1498 def addProjectConfig(self, project_config):
1499 self.project_configs[project_config.name] = project_config
1500 # TODOv3(jeblair): tidy up the relationship between pipelines
1501 # and projects and projectconfigs
1502 for pipeline_name, pipeline_config in project_config.pipelines.items():
1503 pipeline = self.pipelines[pipeline_name]
1504 project = pipeline.source.getProject(project_config.name)
1505 pipeline.job_trees[project] = pipeline_config.job_tree
1506
James E. Blair59fdbac2015-12-07 17:08:06 -08001507
1508class Tenant(object):
1509 def __init__(self, name):
1510 self.name = name
1511 self.layout = None
1512
1513
1514class Abide(object):
1515 def __init__(self):
1516 self.tenants = OrderedDict()