blob: 46a0f36ea8dbf09fb09acd4ac225d7ef3320212b [file] [log] [blame]
mblighe8819cd2008-02-15 16:48:40 +00001"""\
2Functions to expose over the RPC interface.
3
4For all modify* and delete* functions that ask for an 'id' parameter to
5identify the object to operate on, the id may be either
6 * the database row ID
7 * the name of the object (label name, hostname, user login, etc.)
8 * a dictionary containing uniquely identifying field (this option should seldom
9 be used)
10
11When specifying foreign key fields (i.e. adding hosts to a label, or adding
12users to an ACL group), the given value may be either the database row ID or the
13name of the object.
14
15All get* functions return lists of dictionaries. Each dictionary represents one
16object and maps field names to values.
17
18Some examples:
19modify_host(2, hostname='myhost') # modify hostname of host with database ID 2
20modify_host('ipaj2', hostname='myhost') # modify hostname of host 'ipaj2'
21modify_test('sleeptest', test_type='Client', params=', seconds=60')
22delete_acl_group(1) # delete by ID
23delete_acl_group('Everyone') # delete by name
24acl_group_add_users('Everyone', ['mbligh', 'showard'])
25get_jobs(owner='showard', status='Queued')
26
27See doctests/rpc_test.txt for (lots) more examples.
28"""
29
30__author__ = 'showard@google.com (Steve Howard)'
31
showard1385b162008-03-13 15:59:40 +000032import itertools
mblighe8819cd2008-02-15 16:48:40 +000033import models, control_file, rpc_utils
34
35# labels
36
37def add_label(name, kernel_config=None, platform=None):
38 return models.Label.add_object(name=name, kernel_config=kernel_config,
39 platform=platform).id
40
41
42def modify_label(id, **data):
43 models.Label.smart_get(id).update_object(data)
44
45
46def delete_label(id):
47 models.Label.smart_get(id).delete()
48
49
50def get_labels(**filter_data):
51 return rpc_utils.prepare_for_serialization(
52 models.Label.list_objects(filter_data))
53
54
55# hosts
56
57def add_host(hostname, status=None, locked=None):
58 return models.Host.add_object(hostname=hostname, status=status,
59 locked=locked).id
60
61
62def modify_host(id, **data):
63 models.Host.smart_get(id).update_object(data)
64
65
66def host_add_labels(id, labels):
67 labels = [models.Label.smart_get(label) for label in labels]
68 models.Host.smart_get(id).labels.add(*labels)
69
70
71def host_remove_labels(id, labels):
72 labels = [models.Label.smart_get(label) for label in labels]
73 models.Host.smart_get(id).labels.remove(*labels)
74
75
76def delete_host(id):
77 models.Host.smart_get(id).delete()
78
79
80def get_hosts(**filter_data):
81 hosts = models.Host.list_objects(filter_data)
82 for host in hosts:
83 host_obj = models.Host.objects.get(id=host['id'])
84 host['labels'] = [label.name
85 for label in host_obj.labels.all()]
86 platform = host_obj.platform()
87 host['platform'] = platform and platform.name or None
88 return rpc_utils.prepare_for_serialization(hosts)
89
90
showard1385b162008-03-13 15:59:40 +000091def get_hosts_acld_to(user, **filter_data):
92 """\
93 Like get_hosts(), but only return hosts to which the given user has
94 ACL access.
95 """
96 user = models.User.smart_get(user)
97 # get hosts for each ACL group to which this user belongs
98 host_groups = [get_hosts(acl_group=acl_group, **filter_data)
99 for acl_group in user.aclgroup_set.all()]
100 # consolidate into unique hosts
101 hosts = rpc_utils.gather_unique_dicts(itertools.chain(*host_groups))
102 return hosts
103
mblighe8819cd2008-02-15 16:48:40 +0000104
105# tests
106
107def add_test(name, test_type, path, test_class=None, description=None):
108 return models.Test.add_object(name=name, test_type=test_type, path=path,
109 test_class=test_class,
110 description=description).id
111
112
113def modify_test(id, **data):
114 models.Test.smart_get(id).update_object(data)
115
116
117def delete_test(id):
118 models.Test.smart_get(id).delete()
119
120
121def get_tests(**filter_data):
122 return rpc_utils.prepare_for_serialization(
123 models.Test.list_objects(filter_data))
124
125
126# users
127
128def add_user(login, access_level=None):
129 return models.User.add_object(login=login, access_level=access_level).id
130
131
132def modify_user(id, **data):
133 models.User.smart_get(id).update_object(data)
134
135
136def delete_user(id):
137 models.User.smart_get(id).delete()
138
139
140def get_users(**filter_data):
141 return rpc_utils.prepare_for_serialization(
142 models.User.list_objects(filter_data))
143
144
145# acl groups
146
147def add_acl_group(name, description=None):
148 return models.AclGroup.add_object(name=name, description=description).id
149
150
151def modify_acl_group(id, **data):
152 models.AclGroup.smart_get(id).update_object(data)
153
154
155def acl_group_add_users(id, users):
156 users = [models.User.smart_get(user) for user in users]
157 models.AclGroup.smart_get(id).users.add(*users)
158
159
160def acl_group_remove_users(id, users):
161 users = [models.User.smart_get(user) for user in users]
162 models.AclGroup.smart_get(id).users.remove(*users)
163
164
165def acl_group_add_hosts(id, hosts):
166 hosts = [models.Host.smart_get(host) for host in hosts]
167 models.AclGroup.smart_get(id).hosts.add(*hosts)
168
169
170def acl_group_remove_hosts(id, hosts):
171 hosts = [models.Host.smart_get(host) for host in hosts]
172 models.AclGroup.smart_get(id).hosts.remove(*hosts)
173
174
175def delete_acl_group(id):
176 models.AclGroup.smart_get(id).delete()
177
178
179def get_acl_groups(**filter_data):
180 acl_groups = models.AclGroup.list_objects(filter_data)
181 for acl_group in acl_groups:
182 acl_group_obj = models.AclGroup.objects.get(id=acl_group['id'])
183 acl_group['users'] = [user.login
184 for user in acl_group_obj.users.all()]
185 acl_group['hosts'] = [host.hostname
186 for host in acl_group_obj.hosts.all()]
187 return rpc_utils.prepare_for_serialization(acl_groups)
188
189
190# jobs
191
192def generate_control_file(tests, kernel=None, label=None):
193 """\
194 Generates a client-side control file to load a kernel and run a set of
showard8fd58242008-03-10 21:29:07 +0000195 tests. Returns a tuple (control_file, is_server, is_synchronous):
196 control_file - the control file text
197 is_server - is the control file a server-side control file?
198 is_synchronous - should the control file be run synchronously?
mblighe8819cd2008-02-15 16:48:40 +0000199
200 tests: list of tests to run
201 kernel: kernel to install in generated control file
202 label: name of label to grab kernel config from
mblighe8819cd2008-02-15 16:48:40 +0000203 """
204 if not tests:
showard8fd58242008-03-10 21:29:07 +0000205 return '', False, False
mblighe8819cd2008-02-15 16:48:40 +0000206
showard8fd58242008-03-10 21:29:07 +0000207 is_server, is_synchronous, test_objects, label = (
mblighe8819cd2008-02-15 16:48:40 +0000208 rpc_utils.prepare_generate_control_file(tests, kernel, label))
showard1d445e92008-03-12 21:33:31 +0000209 cf_text = control_file.generate_control(test_objects, kernel, label,
210 is_server)
showard8fd58242008-03-10 21:29:07 +0000211 return cf_text, is_server, is_synchronous
mblighe8819cd2008-02-15 16:48:40 +0000212
213
214def create_job(name, priority, control_file, control_type, is_synchronous=None,
215 hosts=None, meta_hosts=None):
216 """\
217 Create and enqueue a job.
218
219 priority: Low, Medium, High, Urgent
220 control_file: contents of control file
221 control_type: type of control file, Client or Server
222 is_synchronous: boolean indicating if a job is synchronous
223 hosts: list of hosts to run job on
224 meta_hosts: list where each entry is a label name, and for each entry
225 one host will be chosen from that label to run the job
226 on.
227 """
228 owner = rpc_utils.get_user().login
229 # input validation
230 if not hosts and not meta_hosts:
231 raise models.ValidationError({
232 'arguments' : "You must pass at least one of 'hosts' or "
233 "'meta_hosts'"
234 })
235
236 # convert hostnames & meta hosts to host/label objects
237 host_objects = []
238 for host in hosts or []:
239 this_host = models.Host.smart_get(host)
240 host_objects.append(this_host)
241 for label in meta_hosts or []:
242 this_label = models.Label.smart_get(label)
243 host_objects.append(this_label)
244
245 # default is_synchronous to some appropriate value
246 ControlType = models.Job.ControlType
247 control_type = ControlType.get_value(control_type)
248 if is_synchronous is None:
249 is_synchronous = (control_type == ControlType.SERVER)
250 # convert the synch flag to an actual type
251 if is_synchronous:
showard8fd58242008-03-10 21:29:07 +0000252 synch_type = models.Test.SynchType.SYNCHRONOUS
mblighe8819cd2008-02-15 16:48:40 +0000253 else:
showard8fd58242008-03-10 21:29:07 +0000254 synch_type = models.Test.SynchType.ASYNCHRONOUS
mblighe8819cd2008-02-15 16:48:40 +0000255
256 job = models.Job.create(owner=owner, name=name, priority=priority,
257 control_file=control_file,
258 control_type=control_type,
259 synch_type=synch_type,
260 hosts=host_objects)
261 job.queue(host_objects)
262 return job.id
263
264
mbligh3cab4a72008-03-05 23:19:09 +0000265def requeue_job(id):
266 """\
267 Create and enqueue a copy of the given job.
268 """
269 job = models.Job.objects.get(id=id)
270 new_job = job.requeue(rpc_utils.get_user().login)
271 return new_job.id
272
273
mblighe8819cd2008-02-15 16:48:40 +0000274def abort_job(id):
275 """\
276 Abort the job with the given id number.
277 """
278 job = models.Job.objects.get(id=id)
279 job.abort()
280
281
282def get_jobs(not_yet_run=False, running=False, finished=False, **filter_data):
283 """\
284 Extra filter args for get_jobs:
285 -not_yet_run: Include only jobs that have not yet started running.
286 -running: Include only jobs that have start running but for which not
287 all hosts have completed.
288 -finished: Include only jobs for which all hosts have completed (or
289 aborted).
290 At most one of these fields should be specified.
291 """
292 filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run,
293 running,
294 finished)
295 return rpc_utils.prepare_for_serialization(
296 models.Job.list_objects(filter_data))
297
298
299def get_num_jobs(not_yet_run=False, running=False, finished=False,
300 **filter_data):
301 """\
302 Get the number of jobs matching the given filters. query_start and
303 query_limit parameters are ignored. See get_jobs() for documentation of
304 extra filter parameters.
305 """
306 filter_data.pop('query_start', None)
307 filter_data.pop('query_limit', None)
308 filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run,
309 running,
310 finished)
311 return models.Job.query_objects(filter_data).count()
312
313
314def job_status(id):
315 """\
316 Get status of job with the given id number. Returns a dictionary
317 mapping hostnames to dictionaries with two keys each:
318 * 'status' : the job status for that host
319 * 'meta_count' : For meta host entires, gives a count of how many
320 entries there are for this label (the hostname is
321 then a label name). For real host entries,
322 meta_count is None.
323 """
324 job = models.Job.objects.get(id=id)
325 hosts_status = {}
326 for queue_entry in job.hostqueueentry_set.all():
327 is_meta = queue_entry.is_meta_host_entry()
328 if is_meta:
329 name = queue_entry.meta_host.name
330 hosts_status.setdefault(name, {'meta_count': 0})
331 hosts_status[name]['meta_count'] += 1
332 else:
333 name = queue_entry.host.hostname
334 hosts_status[name] = {'meta_count': None}
335 hosts_status[name]['status'] = queue_entry.status
336 return hosts_status
337
338
339def get_jobs_summary(**filter_data):
340 """\
341 Like get_jobs(), but adds a 'stauts_counts' field, which is a dictionary
342 mapping status strings to the number of hosts currently with that
343 status, i.e. {'Queued' : 4, 'Running' : 2}.
344 """
345 jobs = get_jobs(**filter_data)
346 ids = [job['id'] for job in jobs]
347 all_status_counts = models.Job.objects.get_status_counts(ids)
348 for job in jobs:
349 job['status_counts'] = all_status_counts[job['id']]
350 return rpc_utils.prepare_for_serialization(jobs)
351
352
353# other
354
355def get_static_data():
356 """\
357 Returns a dictionary containing a bunch of data that shouldn't change
358 often. This includes:
359 priorities: list of job priority choices
360 default_priority: default priority value for new jobs
361 users: sorted list of all usernames
362 labels: sorted list of all label names
363 tests: sorted list of all test names
showard1385b162008-03-13 15:59:40 +0000364 user_login: logged-in username
mblighe8819cd2008-02-15 16:48:40 +0000365 """
366 result = {}
367 result['priorities'] = models.Job.Priority.choices()
368 default_priority = models.Job.get_field_dict()['priority'].default
369 default_string = models.Job.Priority.get_string(default_priority)
370 result['default_priority'] = default_string
371 result['users'] = [user.login for user in
372 models.User.objects.all().order_by('login')]
373 result['labels'] = [label.name for label in
374 models.Label.objects.all().order_by('name')]
375 result['tests'] = get_tests(sort_by='name')
376 result['user_login'] = rpc_utils.get_user().login
377 return result