blob: f08eb99e03215b7f05ba1dced40be8c7c89a2c63 [file] [log] [blame]
mblighe8819cd2008-02-15 16:48:40 +00001"""\
2Utility functions for rpc_interface.py. We keep them in a separate file so that
3only RPC interface functions go into that file.
4"""
5
6__author__ = 'showard@google.com (Steve Howard)'
7
showard14374b12009-01-31 00:11:54 +00008import datetime, os
mblighec5546d2008-06-16 16:51:28 +00009from frontend.afe import models, model_logic
mblighe8819cd2008-02-15 16:48:40 +000010
showarda62866b2008-07-28 21:27:41 +000011NULL_DATETIME = datetime.datetime.max
12NULL_DATE = datetime.date.max
13
mblighe8819cd2008-02-15 16:48:40 +000014def prepare_for_serialization(objects):
jadmanski0afbb632008-06-06 21:10:57 +000015 """
16 Prepare Python objects to be returned via RPC.
17 """
18 if (isinstance(objects, list) and len(objects) and
19 isinstance(objects[0], dict) and 'id' in objects[0]):
20 objects = gather_unique_dicts(objects)
21 return _prepare_data(objects)
showardb8d34242008-04-25 18:11:16 +000022
23
showardc92da832009-04-07 18:14:34 +000024def prepare_rows_as_nested_dicts(query, nested_dict_column_names):
25 """
26 Prepare a Django query to be returned via RPC as a sequence of nested
27 dictionaries.
28
29 @param query - A Django model query object with a select_related() method.
30 @param nested_dict_column_names - A list of column/attribute names for the
31 rows returned by query to expand into nested dictionaries using
32 their get_object_dict() method when not None.
33
34 @returns An list suitable to returned in an RPC.
35 """
36 all_dicts = []
37 for row in query.select_related():
38 row_dict = row.get_object_dict()
39 for column in nested_dict_column_names:
40 if row_dict[column] is not None:
41 row_dict[column] = getattr(row, column).get_object_dict()
42 all_dicts.append(row_dict)
43 return prepare_for_serialization(all_dicts)
44
45
showardb8d34242008-04-25 18:11:16 +000046def _prepare_data(data):
jadmanski0afbb632008-06-06 21:10:57 +000047 """
48 Recursively process data structures, performing necessary type
49 conversions to values in data to allow for RPC serialization:
50 -convert datetimes to strings
showard2b9a88b2008-06-13 20:55:03 +000051 -convert tuples and sets to lists
jadmanski0afbb632008-06-06 21:10:57 +000052 """
53 if isinstance(data, dict):
54 new_data = {}
55 for key, value in data.iteritems():
56 new_data[key] = _prepare_data(value)
57 return new_data
showard2b9a88b2008-06-13 20:55:03 +000058 elif (isinstance(data, list) or isinstance(data, tuple) or
59 isinstance(data, set)):
jadmanski0afbb632008-06-06 21:10:57 +000060 return [_prepare_data(item) for item in data]
showard98659972008-07-17 17:00:07 +000061 elif isinstance(data, datetime.date):
showarda62866b2008-07-28 21:27:41 +000062 if data is NULL_DATETIME or data is NULL_DATE:
63 return None
jadmanski0afbb632008-06-06 21:10:57 +000064 return str(data)
65 else:
66 return data
mblighe8819cd2008-02-15 16:48:40 +000067
68
showardb0dfb9f2008-06-06 18:08:02 +000069def gather_unique_dicts(dict_iterable):
jadmanski0afbb632008-06-06 21:10:57 +000070 """\
71 Pick out unique objects (by ID) from an iterable of object dicts.
72 """
73 id_set = set()
74 result = []
75 for obj in dict_iterable:
76 if obj['id'] not in id_set:
77 id_set.add(obj['id'])
78 result.append(obj)
79 return result
showardb0dfb9f2008-06-06 18:08:02 +000080
81
mblighe8819cd2008-02-15 16:48:40 +000082def extra_job_filters(not_yet_run=False, running=False, finished=False):
jadmanski0afbb632008-06-06 21:10:57 +000083 """\
84 Generate a SQL WHERE clause for job status filtering, and return it in
85 a dict of keyword args to pass to query.extra(). No more than one of
86 the parameters should be passed as True.
87 """
88 assert not ((not_yet_run and running) or
89 (not_yet_run and finished) or
90 (running and finished)), ('Cannot specify more than one '
91 'filter to this function')
92 if not_yet_run:
93 where = ['id NOT IN (SELECT job_id FROM host_queue_entries '
94 'WHERE active OR complete)']
95 elif running:
96 where = ['(id IN (SELECT job_id FROM host_queue_entries '
97 'WHERE active OR complete)) AND '
98 '(id IN (SELECT job_id FROM host_queue_entries '
99 'WHERE not complete OR active))']
100 elif finished:
101 where = ['id NOT IN (SELECT job_id FROM host_queue_entries '
102 'WHERE not complete OR active)']
103 else:
104 return None
105 return {'where': where}
mblighe8819cd2008-02-15 16:48:40 +0000106
107
showard8e3aa5e2008-04-08 19:42:32 +0000108def extra_host_filters(multiple_labels=[]):
jadmanski0afbb632008-06-06 21:10:57 +0000109 """\
110 Generate SQL WHERE clauses for matching hosts in an intersection of
111 labels.
112 """
113 extra_args = {}
114 where_str = ('hosts.id in (select host_id from hosts_labels '
115 'where label_id=%s)')
116 extra_args['where'] = [where_str] * len(multiple_labels)
117 extra_args['params'] = [models.Label.smart_get(label).id
118 for label in multiple_labels]
119 return extra_args
showard8e3aa5e2008-04-08 19:42:32 +0000120
121
showard43a3d262008-11-12 18:17:05 +0000122def get_host_query(multiple_labels, exclude_only_if_needed_labels, filter_data):
123 query = models.Host.valid_objects.all()
124 if exclude_only_if_needed_labels:
125 only_if_needed_labels = models.Label.valid_objects.filter(
126 only_if_needed=True)
showardf7eac6f2008-11-13 21:18:01 +0000127 if only_if_needed_labels.count() > 0:
128 only_if_needed_ids = ','.join(str(label['id']) for label
129 in only_if_needed_labels.values('id'))
130 query = models.Host.objects.add_join(
131 query, 'hosts_labels', join_key='host_id',
132 join_condition='hosts_labels_exclude.label_id IN (%s)'
133 % only_if_needed_ids,
134 suffix='_exclude', exclude=True)
showard43a3d262008-11-12 18:17:05 +0000135 filter_data['extra_args'] = (extra_host_filters(multiple_labels))
136 return models.Host.query_objects(filter_data, initial_query=query)
137
138
showard8fd58242008-03-10 21:29:07 +0000139class InconsistencyException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000140 'Raised when a list of objects does not have a consistent value'
showard8fd58242008-03-10 21:29:07 +0000141
142
143def get_consistent_value(objects, field):
mblighc5ddfd12008-08-04 17:15:00 +0000144 if not objects:
145 # well a list of nothing is consistent
146 return None
147
jadmanski0afbb632008-06-06 21:10:57 +0000148 value = getattr(objects[0], field)
149 for obj in objects:
150 this_value = getattr(obj, field)
151 if this_value != value:
152 raise InconsistencyException(objects[0], obj)
153 return value
showard8fd58242008-03-10 21:29:07 +0000154
155
showard2b9a88b2008-06-13 20:55:03 +0000156def prepare_generate_control_file(tests, kernel, label, profilers):
jadmanski0afbb632008-06-06 21:10:57 +0000157 test_objects = [models.Test.smart_get(test) for test in tests]
showard2b9a88b2008-06-13 20:55:03 +0000158 profiler_objects = [models.Profiler.smart_get(profiler)
159 for profiler in profilers]
jadmanski0afbb632008-06-06 21:10:57 +0000160 # ensure tests are all the same type
161 try:
162 test_type = get_consistent_value(test_objects, 'test_type')
163 except InconsistencyException, exc:
164 test1, test2 = exc.args
mblighec5546d2008-06-16 16:51:28 +0000165 raise model_logic.ValidationError(
jadmanski0afbb632008-06-06 21:10:57 +0000166 {'tests' : 'You cannot run both server- and client-side '
167 'tests together (tests %s and %s differ' % (
168 test1.name, test2.name)})
showard8fd58242008-03-10 21:29:07 +0000169
jadmanski0afbb632008-06-06 21:10:57 +0000170 is_server = (test_type == models.Test.Types.SERVER)
showard14374b12009-01-31 00:11:54 +0000171 if test_objects:
172 synch_count = max(test.sync_count for test in test_objects)
173 else:
174 synch_count = 1
jadmanski0afbb632008-06-06 21:10:57 +0000175 if label:
176 label = models.Label.smart_get(label)
mblighe8819cd2008-02-15 16:48:40 +0000177
showard989f25d2008-10-01 11:38:11 +0000178 dependencies = set(label.name for label
179 in models.Label.objects.filter(test__in=test_objects))
180
showard2bab8f42008-11-12 18:15:22 +0000181 cf_info = dict(is_server=is_server, synch_count=synch_count,
182 dependencies=list(dependencies))
183 return cf_info, test_objects, profiler_objects, label
showard989f25d2008-10-01 11:38:11 +0000184
185
186def check_job_dependencies(host_objects, job_dependencies):
187 """
188 Check that a set of machines satisfies a job's dependencies.
189 host_objects: list of models.Host objects
190 job_dependencies: list of names of labels
191 """
192 # check that hosts satisfy dependencies
193 host_ids = [host.id for host in host_objects]
194 hosts_in_job = models.Host.objects.filter(id__in=host_ids)
195 ok_hosts = hosts_in_job
196 for index, dependency in enumerate(job_dependencies):
197 ok_hosts &= models.Host.objects.filter_custom_join(
198 '_label%d' % index, labels__name=dependency)
199 failing_hosts = (set(host.hostname for host in host_objects) -
200 set(host.hostname for host in ok_hosts))
201 if failing_hosts:
202 raise model_logic.ValidationError(
203 {'hosts' : 'Host(s) failed to meet job dependencies: ' +
204 ', '.join(failing_hosts)})
205
showard2bab8f42008-11-12 18:15:22 +0000206
207def _execution_key_for(host_queue_entry):
208 return (host_queue_entry.job.id, host_queue_entry.execution_subdir)
209
210
211def check_abort_synchronous_jobs(host_queue_entries):
212 # ensure user isn't aborting part of a synchronous autoserv execution
213 count_per_execution = {}
214 for queue_entry in host_queue_entries:
215 key = _execution_key_for(queue_entry)
216 count_per_execution.setdefault(key, 0)
217 count_per_execution[key] += 1
218
219 for queue_entry in host_queue_entries:
220 if not queue_entry.execution_subdir:
221 continue
222 execution_count = count_per_execution[_execution_key_for(queue_entry)]
223 if execution_count < queue_entry.job.synch_count:
224 raise model_logic.ValidationError(
225 {'' : 'You cannot abort part of a synchronous job execution '
showardc92da832009-04-07 18:14:34 +0000226 '(%d/%s), %d included, %d expected'
showard2bab8f42008-11-12 18:15:22 +0000227 % (queue_entry.job.id, queue_entry.execution_subdir,
showard01746192008-11-13 21:18:14 +0000228 execution_count, queue_entry.job.synch_count)})
showard8fbae652009-01-20 23:23:10 +0000229
230
showardc92da832009-04-07 18:14:34 +0000231def check_atomic_group_create_job(synch_count, host_objects, metahost_objects,
232 dependencies, atomic_group, labels_by_name):
233 """
234 Attempt to reject create_job requests with an atomic group that
235 will be impossible to schedule. The checks are not perfect but
236 should catch the most obvious issues.
237
238 @param synch_count - The job's minimum synch count.
239 @param host_objects - A list of models.Host instances.
240 @param metahost_objects - A list of models.Label instances.
241 @param dependencies - A list of job dependency label names.
242 @param atomic_group - The models.AtomicGroup instance.
243 @param labels_by_name - A dictionary mapping label names to models.Label
244 instance. Used to look up instances for dependencies.
245
246 @raises model_logic.ValidationError - When an issue is found.
247 """
248 # If specific host objects were supplied with an atomic group, verify
249 # that there are enough to satisfy the synch_count.
250 minimum_required = synch_count or 1
251 if (host_objects and not metahost_objects and
252 len(host_objects) < minimum_required):
253 raise model_logic.ValidationError(
254 {'hosts':
255 'only %d hosts provided for job with synch_count = %d' %
256 (len(host_objects), synch_count)})
257
258 # Check that the atomic group has a hope of running this job
259 # given any supplied metahosts and dependancies that may limit.
260
261 # Get a set of hostnames in the atomic group.
262 possible_hosts = set()
263 for label in atomic_group.label_set.all():
264 possible_hosts.update(h.hostname for h in label.host_set.all())
265
266 # Filter out hosts that don't match all of the job dependency labels.
267 for label_name in set(dependencies):
268 label = labels_by_name[label_name]
269 hosts_in_label = (h.hostname for h in label.host_set.all())
270 possible_hosts.intersection_update(hosts_in_label)
271
272 host_set = set(host.hostname for host in host_objects)
273 unusable_host_set = host_set.difference(possible_hosts)
274 if unusable_host_set:
275 raise model_logic.ValidationError(
276 {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' %
277 (', '.join(sorted(unusable_host_set)), atomic_group.name)})
278
279 # Lookup hosts provided by each meta host and merge them into the
280 # host_set for final counting.
281 for meta_host in metahost_objects:
282 meta_possible = possible_hosts.copy()
283 hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all())
284 meta_possible.intersection_update(hosts_in_meta_host)
285
286 # Count all hosts that this meta_host will provide.
287 host_set.update(meta_possible)
288
289 if len(host_set) < minimum_required:
290 raise model_logic.ValidationError(
291 {'atomic_group_name':
292 'Insufficient hosts in Atomic Group "%s" with the'
293 ' supplied dependencies and meta_hosts.' %
294 (atomic_group.name,)})
295
296
showard8fbae652009-01-20 23:23:10 +0000297def get_motd():
298 dirname = os.path.dirname(__file__)
299 filename = os.path.join(dirname, "..", "..", "motd.txt")
300 text = ''
301 try:
302 fp = open(filename, "r")
303 try:
304 text = fp.read()
305 finally:
306 fp.close()
307 except:
308 pass
309
310 return text