blob: c95f231c0d56344ecae7c78179ac5e27859f544b [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
mbligh93c80e62009-02-03 17:48:30 +000027See doctests/001_rpc_test.txt for (lots) more examples.
mblighe8819cd2008-02-15 16:48:40 +000028"""
29
30__author__ = 'showard@google.com (Steve Howard)'
31
showard29f7cd22009-04-29 21:16:24 +000032import datetime
showardff901382008-07-07 23:22:16 +000033from frontend import thread_local
showard09096d82008-07-07 23:20:49 +000034from frontend.afe import models, model_logic, control_file, rpc_utils
showard3bb499f2008-07-03 19:42:20 +000035from autotest_lib.client.common_lib import global_config
36
mblighe8819cd2008-02-15 16:48:40 +000037
38# labels
39
showard989f25d2008-10-01 11:38:11 +000040def add_label(name, kernel_config=None, platform=None, only_if_needed=None):
showardc92da832009-04-07 18:14:34 +000041 return models.Label.add_object(
42 name=name, kernel_config=kernel_config, platform=platform,
43 only_if_needed=only_if_needed).id
mblighe8819cd2008-02-15 16:48:40 +000044
45
46def modify_label(id, **data):
jadmanski0afbb632008-06-06 21:10:57 +000047 models.Label.smart_get(id).update_object(data)
mblighe8819cd2008-02-15 16:48:40 +000048
49
50def delete_label(id):
jadmanski0afbb632008-06-06 21:10:57 +000051 models.Label.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +000052
53
showardbbabf502008-06-06 00:02:02 +000054def label_add_hosts(id, hosts):
showardbe3ec042008-11-12 18:16:07 +000055 host_objs = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +000056 models.Label.smart_get(id).host_set.add(*host_objs)
showardbbabf502008-06-06 00:02:02 +000057
58
59def label_remove_hosts(id, hosts):
showardbe3ec042008-11-12 18:16:07 +000060 host_objs = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +000061 models.Label.smart_get(id).host_set.remove(*host_objs)
showardbbabf502008-06-06 00:02:02 +000062
63
mblighe8819cd2008-02-15 16:48:40 +000064def get_labels(**filter_data):
showardc92da832009-04-07 18:14:34 +000065 """\
66 @returns A sequence of nested dictionaries of label information.
67 """
68 return rpc_utils.prepare_rows_as_nested_dicts(
69 models.Label.query_objects(filter_data),
70 ('atomic_group',))
71
72
73# atomic groups
74
75def add_atomic_group(name, max_number_of_machines, description=None):
76 return models.AtomicGroup.add_object(
77 name=name, max_number_of_machines=max_number_of_machines,
78 description=description).id
79
80
81def modify_atomic_group(id, **data):
82 models.AtomicGroup.smart_get(id).update_object(data)
83
84
85def delete_atomic_group(id):
86 models.AtomicGroup.smart_get(id).delete()
87
88
89def atomic_group_add_labels(id, labels):
90 label_objs = models.Label.smart_get_bulk(labels)
91 models.AtomicGroup.smart_get(id).label_set.add(*label_objs)
92
93
94def atomic_group_remove_labels(id, labels):
95 label_objs = models.Label.smart_get_bulk(labels)
96 models.AtomicGroup.smart_get(id).label_set.remove(*label_objs)
97
98
99def get_atomic_groups(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000100 return rpc_utils.prepare_for_serialization(
showardc92da832009-04-07 18:14:34 +0000101 models.AtomicGroup.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000102
103
104# hosts
105
showarddf062562008-07-03 19:56:37 +0000106def add_host(hostname, status=None, locked=None, protection=None):
jadmanski0afbb632008-06-06 21:10:57 +0000107 return models.Host.add_object(hostname=hostname, status=status,
showarddf062562008-07-03 19:56:37 +0000108 locked=locked, protection=protection).id
mblighe8819cd2008-02-15 16:48:40 +0000109
110
111def modify_host(id, **data):
jadmanski0afbb632008-06-06 21:10:57 +0000112 models.Host.smart_get(id).update_object(data)
mblighe8819cd2008-02-15 16:48:40 +0000113
114
115def host_add_labels(id, labels):
showardbe3ec042008-11-12 18:16:07 +0000116 labels = models.Label.smart_get_bulk(labels)
jadmanski0afbb632008-06-06 21:10:57 +0000117 models.Host.smart_get(id).labels.add(*labels)
mblighe8819cd2008-02-15 16:48:40 +0000118
119
120def host_remove_labels(id, labels):
showardbe3ec042008-11-12 18:16:07 +0000121 labels = models.Label.smart_get_bulk(labels)
jadmanski0afbb632008-06-06 21:10:57 +0000122 models.Host.smart_get(id).labels.remove(*labels)
mblighe8819cd2008-02-15 16:48:40 +0000123
124
showard0957a842009-05-11 19:25:08 +0000125def set_host_attribute(attribute, value, **host_filter_data):
126 """
127 @param attribute string name of attribute
128 @param value string, or None to delete an attribute
129 @param host_filter_data filter data to apply to Hosts to choose hosts to act
130 upon
131 """
132 assert host_filter_data # disallow accidental actions on all hosts
133 hosts = models.Host.query_objects(host_filter_data)
134 models.AclGroup.check_for_acl_violation_hosts(hosts)
135
136 for host in hosts:
137 if value is None:
138 host.delete_attribute(attribute)
139 else:
140 host.set_attribute(attribute, value)
141
142
mblighe8819cd2008-02-15 16:48:40 +0000143def delete_host(id):
jadmanski0afbb632008-06-06 21:10:57 +0000144 models.Host.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000145
146
showard43a3d262008-11-12 18:17:05 +0000147def get_hosts(multiple_labels=[], exclude_only_if_needed_labels=False,
148 **filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000149 """\
150 multiple_labels: match hosts in all of the labels given. Should be a
151 list of label names.
showard43a3d262008-11-12 18:17:05 +0000152 exclude_only_if_needed_labels: exclude hosts with at least one
153 "only_if_needed" label applied.
jadmanski0afbb632008-06-06 21:10:57 +0000154 """
showard43a3d262008-11-12 18:17:05 +0000155 hosts = rpc_utils.get_host_query(multiple_labels,
156 exclude_only_if_needed_labels,
157 filter_data)
showard0957a842009-05-11 19:25:08 +0000158 hosts = list(hosts)
159 models.Host.objects.populate_relationships(hosts, models.Label,
160 'label_list')
161 models.Host.objects.populate_relationships(hosts, models.AclGroup,
162 'acl_list')
163 models.Host.objects.populate_relationships(hosts, models.HostAttribute,
164 'attribute_list')
showard43a3d262008-11-12 18:17:05 +0000165 host_dicts = []
166 for host_obj in hosts:
167 host_dict = host_obj.get_object_dict()
showard0957a842009-05-11 19:25:08 +0000168 host_dict['labels'] = [label.name for label in host_obj.label_list]
169 host_dict['platform'] = rpc_utils.find_platform(host_obj)
170 host_dict['acls'] = [acl.name for acl in host_obj.acl_list]
171 host_dict['attributes'] = dict((attribute.attribute, attribute.value)
172 for attribute in host_obj.attribute_list)
showard43a3d262008-11-12 18:17:05 +0000173 host_dicts.append(host_dict)
174 return rpc_utils.prepare_for_serialization(host_dicts)
mblighe8819cd2008-02-15 16:48:40 +0000175
176
showard43a3d262008-11-12 18:17:05 +0000177def get_num_hosts(multiple_labels=[], exclude_only_if_needed_labels=False,
178 **filter_data):
179 hosts = rpc_utils.get_host_query(multiple_labels,
180 exclude_only_if_needed_labels,
181 filter_data)
182 return hosts.count()
showard1385b162008-03-13 15:59:40 +0000183
mblighe8819cd2008-02-15 16:48:40 +0000184
185# tests
186
showard909c7a62008-07-15 21:52:38 +0000187def add_test(name, test_type, path, author=None, dependencies=None,
showard3d9899a2008-07-31 02:11:58 +0000188 experimental=True, run_verify=None, test_class=None,
showard909c7a62008-07-15 21:52:38 +0000189 test_time=None, test_category=None, description=None,
190 sync_count=1):
jadmanski0afbb632008-06-06 21:10:57 +0000191 return models.Test.add_object(name=name, test_type=test_type, path=path,
showard909c7a62008-07-15 21:52:38 +0000192 author=author, dependencies=dependencies,
193 experimental=experimental,
194 run_verify=run_verify, test_time=test_time,
195 test_category=test_category,
196 sync_count=sync_count,
jadmanski0afbb632008-06-06 21:10:57 +0000197 test_class=test_class,
198 description=description).id
mblighe8819cd2008-02-15 16:48:40 +0000199
200
201def modify_test(id, **data):
jadmanski0afbb632008-06-06 21:10:57 +0000202 models.Test.smart_get(id).update_object(data)
mblighe8819cd2008-02-15 16:48:40 +0000203
204
205def delete_test(id):
jadmanski0afbb632008-06-06 21:10:57 +0000206 models.Test.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000207
208
209def get_tests(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000210 return rpc_utils.prepare_for_serialization(
211 models.Test.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000212
213
showard2b9a88b2008-06-13 20:55:03 +0000214# profilers
215
216def add_profiler(name, description=None):
217 return models.Profiler.add_object(name=name, description=description).id
218
219
220def modify_profiler(id, **data):
221 models.Profiler.smart_get(id).update_object(data)
222
223
224def delete_profiler(id):
225 models.Profiler.smart_get(id).delete()
226
227
228def get_profilers(**filter_data):
229 return rpc_utils.prepare_for_serialization(
230 models.Profiler.list_objects(filter_data))
231
232
mblighe8819cd2008-02-15 16:48:40 +0000233# users
234
235def add_user(login, access_level=None):
jadmanski0afbb632008-06-06 21:10:57 +0000236 return models.User.add_object(login=login, access_level=access_level).id
mblighe8819cd2008-02-15 16:48:40 +0000237
238
239def modify_user(id, **data):
jadmanski0afbb632008-06-06 21:10:57 +0000240 models.User.smart_get(id).update_object(data)
mblighe8819cd2008-02-15 16:48:40 +0000241
242
243def delete_user(id):
jadmanski0afbb632008-06-06 21:10:57 +0000244 models.User.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000245
246
247def get_users(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000248 return rpc_utils.prepare_for_serialization(
249 models.User.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000250
251
252# acl groups
253
254def add_acl_group(name, description=None):
showard04f2cd82008-07-25 20:53:31 +0000255 group = models.AclGroup.add_object(name=name, description=description)
256 group.users.add(thread_local.get_user())
257 return group.id
mblighe8819cd2008-02-15 16:48:40 +0000258
259
260def modify_acl_group(id, **data):
showard04f2cd82008-07-25 20:53:31 +0000261 group = models.AclGroup.smart_get(id)
262 group.check_for_acl_violation_acl_group()
263 group.update_object(data)
264 group.add_current_user_if_empty()
mblighe8819cd2008-02-15 16:48:40 +0000265
266
267def acl_group_add_users(id, users):
jadmanski0afbb632008-06-06 21:10:57 +0000268 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000269 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000270 users = models.User.smart_get_bulk(users)
jadmanski0afbb632008-06-06 21:10:57 +0000271 group.users.add(*users)
mblighe8819cd2008-02-15 16:48:40 +0000272
273
274def acl_group_remove_users(id, users):
jadmanski0afbb632008-06-06 21:10:57 +0000275 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000276 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000277 users = models.User.smart_get_bulk(users)
jadmanski0afbb632008-06-06 21:10:57 +0000278 group.users.remove(*users)
showard04f2cd82008-07-25 20:53:31 +0000279 group.add_current_user_if_empty()
mblighe8819cd2008-02-15 16:48:40 +0000280
281
282def acl_group_add_hosts(id, hosts):
jadmanski0afbb632008-06-06 21:10:57 +0000283 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000284 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000285 hosts = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +0000286 group.hosts.add(*hosts)
showard08f981b2008-06-24 21:59:03 +0000287 group.on_host_membership_change()
mblighe8819cd2008-02-15 16:48:40 +0000288
289
290def acl_group_remove_hosts(id, hosts):
jadmanski0afbb632008-06-06 21:10:57 +0000291 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000292 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000293 hosts = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +0000294 group.hosts.remove(*hosts)
showard08f981b2008-06-24 21:59:03 +0000295 group.on_host_membership_change()
mblighe8819cd2008-02-15 16:48:40 +0000296
297
298def delete_acl_group(id):
jadmanski0afbb632008-06-06 21:10:57 +0000299 models.AclGroup.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000300
301
302def get_acl_groups(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000303 acl_groups = models.AclGroup.list_objects(filter_data)
304 for acl_group in acl_groups:
305 acl_group_obj = models.AclGroup.objects.get(id=acl_group['id'])
306 acl_group['users'] = [user.login
307 for user in acl_group_obj.users.all()]
308 acl_group['hosts'] = [host.hostname
309 for host in acl_group_obj.hosts.all()]
310 return rpc_utils.prepare_for_serialization(acl_groups)
mblighe8819cd2008-02-15 16:48:40 +0000311
312
313# jobs
314
mbligh120351e2009-01-24 01:40:45 +0000315def generate_control_file(tests=(), kernel=None, label=None, profilers=(),
316 client_control_file='', use_container=False):
jadmanski0afbb632008-06-06 21:10:57 +0000317 """
mbligh120351e2009-01-24 01:40:45 +0000318 Generates a client-side control file to load a kernel and run tests.
319
320 @param tests List of tests to run.
321 @param kernel Kernel to install in generated control file.
322 @param label Name of label to grab kernel config from.
323 @param profilers List of profilers to activate during the job.
324 @param client_control_file The contents of a client-side control file to
325 run at the end of all tests. If this is supplied, all tests must be
326 client side.
327 TODO: in the future we should support server control files directly
328 to wrap with a kernel. That'll require changing the parameter
329 name and adding a boolean to indicate if it is a client or server
330 control file.
331 @param use_container unused argument today. TODO: Enable containers
332 on the host during a client side test.
333
334 @returns a dict with the following keys:
335 control_file: str, The control file text.
336 is_server: bool, is the control file a server-side control file?
337 synch_count: How many machines the job uses per autoserv execution.
338 synch_count == 1 means the job is asynchronous.
339 dependencies: A list of the names of labels on which the job depends.
340 """
341 if not tests and not control_file:
showard2bab8f42008-11-12 18:15:22 +0000342 return dict(control_file='', is_server=False, synch_count=1,
showard989f25d2008-10-01 11:38:11 +0000343 dependencies=[])
mblighe8819cd2008-02-15 16:48:40 +0000344
showard989f25d2008-10-01 11:38:11 +0000345 cf_info, test_objects, profiler_objects, label = (
showard2b9a88b2008-06-13 20:55:03 +0000346 rpc_utils.prepare_generate_control_file(tests, kernel, label,
347 profilers))
showard989f25d2008-10-01 11:38:11 +0000348 cf_info['control_file'] = control_file.generate_control(
349 tests=test_objects, kernel=kernel, platform=label,
mbligh120351e2009-01-24 01:40:45 +0000350 profilers=profiler_objects, is_server=cf_info['is_server'],
351 client_control_file=client_control_file)
showard989f25d2008-10-01 11:38:11 +0000352 return cf_info
mblighe8819cd2008-02-15 16:48:40 +0000353
354
showard29f7cd22009-04-29 21:16:24 +0000355def create_job(name, priority, control_file, control_type, is_template=False,
356 timeout=None, synch_count=None, hosts=(), meta_hosts=(),
showardc92da832009-04-07 18:14:34 +0000357 run_verify=True, one_time_hosts=(), email_list='',
358 dependencies=(), reboot_before=None, reboot_after=None,
359 atomic_group_name=None):
jadmanski0afbb632008-06-06 21:10:57 +0000360 """\
361 Create and enqueue a job.
mblighe8819cd2008-02-15 16:48:40 +0000362
jadmanski0afbb632008-06-06 21:10:57 +0000363 priority: Low, Medium, High, Urgent
showardc92da832009-04-07 18:14:34 +0000364 control_file: String contents of the control file.
365 control_type: Type of control file, Client or Server.
showard29f7cd22009-04-29 21:16:24 +0000366 is_template: If true then create a template job.
showardc92da832009-04-07 18:14:34 +0000367 timeout: Hours after this call returns until the job times out.
368 synch_count: How many machines the job uses per autoserv execution.
369 synch_count == 1 means the job is asynchronous. If an
370 atomic group is given this value is treated as a minimum.
371 hosts: List of hosts to run job on.
372 meta_hosts: List where each entry is a label name, and for each entry
jadmanski0afbb632008-06-06 21:10:57 +0000373 one host will be chosen from that label to run the job
374 on.
showardc92da832009-04-07 18:14:34 +0000375 run_verify: Should the host be verified before running the test?
376 one_time_hosts: List of hosts not in the database to run the job on.
377 email_list: String containing emails to mail when the job is done
378 dependencies: List of label names on which this job depends
mbligh94ae6d62009-02-03 17:47:49 +0000379 reboot_before: Never, If dirty, or Always
380 reboot_after: Never, If all tests passed, or Always
showardc92da832009-04-07 18:14:34 +0000381 atomic_group_name: The name of an atomic group to schedule the job on.
382
383 @returns The created Job id number.
jadmanski0afbb632008-06-06 21:10:57 +0000384 """
showard3bb499f2008-07-03 19:42:20 +0000385
386 if timeout is None:
387 timeout=global_config.global_config.get_config_value(
388 'AUTOTEST_WEB', 'job_timeout_default')
389
showardff901382008-07-07 23:22:16 +0000390 owner = thread_local.get_user().login
jadmanski0afbb632008-06-06 21:10:57 +0000391 # input validation
showardc92da832009-04-07 18:14:34 +0000392 if not (hosts or meta_hosts or one_time_hosts or atomic_group_name):
mblighec5546d2008-06-16 16:51:28 +0000393 raise model_logic.ValidationError({
showardb8471e32008-07-03 19:51:08 +0000394 'arguments' : "You must pass at least one of 'hosts', "
showardc92da832009-04-07 18:14:34 +0000395 "'meta_hosts', 'one_time_hosts', "
396 "or 'atomic_group_name'"
jadmanski0afbb632008-06-06 21:10:57 +0000397 })
mblighe8819cd2008-02-15 16:48:40 +0000398
showardc92da832009-04-07 18:14:34 +0000399 # Create and sanity check an AtomicGroup object if requested.
400 if atomic_group_name:
401 if one_time_hosts:
402 raise model_logic.ValidationError(
403 {'one_time_hosts':
404 'One time hosts cannot be used with an Atomic Group.'})
405 atomic_group = models.AtomicGroup.smart_get(atomic_group_name)
406 if synch_count and synch_count > atomic_group.max_number_of_machines:
407 raise model_logic.ValidationError(
408 {'atomic_group_name' :
409 'You have requested a synch_count (%d) greater than the '
410 'maximum machines in the requested Atomic Group (%d).' %
411 (synch_count, atomic_group.max_number_of_machines)})
412 else:
413 atomic_group = None
414
showard989f25d2008-10-01 11:38:11 +0000415 labels_by_name = dict((label.name, label)
416 for label in models.Label.objects.all())
showardba872902008-06-28 00:51:08 +0000417
jadmanski0afbb632008-06-06 21:10:57 +0000418 # convert hostnames & meta hosts to host/label objects
showardc92da832009-04-07 18:14:34 +0000419 host_objects = models.Host.smart_get_bulk(hosts)
showard989f25d2008-10-01 11:38:11 +0000420 metahost_objects = []
jadmanski0afbb632008-06-06 21:10:57 +0000421 for label in meta_hosts or []:
showard25087ac2008-11-24 22:12:03 +0000422 if label not in labels_by_name:
423 raise model_logic.ValidationError(
424 {'meta_hosts' : 'Label "%s" not found' % label})
showard989f25d2008-10-01 11:38:11 +0000425 this_label = labels_by_name[label]
426 metahost_objects.append(this_label)
showardb8471e32008-07-03 19:51:08 +0000427 for host in one_time_hosts or []:
428 this_host = models.Host.create_one_time_host(host)
429 host_objects.append(this_host)
showardba872902008-06-28 00:51:08 +0000430
showard29f7cd22009-04-29 21:16:24 +0000431 return rpc_utils.create_new_job(owner=owner,
432 host_objects=host_objects,
433 metahost_objects=metahost_objects,
434 name=name,
435 priority=priority,
436 control_file=control_file,
437 control_type=control_type,
438 is_template=is_template,
439 synch_count=synch_count,
440 timeout=timeout,
441 run_verify=run_verify,
442 email_list=email_list,
443 dependencies=dependencies,
444 reboot_before=reboot_before,
445 reboot_after=reboot_after,
446 atomic_group=atomic_group)
mblighe8819cd2008-02-15 16:48:40 +0000447
448
showard9dbdcda2008-10-14 17:34:36 +0000449def abort_host_queue_entries(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000450 """\
showard9dbdcda2008-10-14 17:34:36 +0000451 Abort a set of host queue entries.
jadmanski0afbb632008-06-06 21:10:57 +0000452 """
showard9dbdcda2008-10-14 17:34:36 +0000453 query = models.HostQueueEntry.query_objects(filter_data)
showard0c185192009-01-16 03:07:57 +0000454 query = query.filter(complete=False)
showarddc817512008-11-12 18:16:41 +0000455 models.AclGroup.check_abort_permissions(query)
showard9dbdcda2008-10-14 17:34:36 +0000456 host_queue_entries = list(query.select_related())
showard2bab8f42008-11-12 18:15:22 +0000457 rpc_utils.check_abort_synchronous_jobs(host_queue_entries)
mblighe8819cd2008-02-15 16:48:40 +0000458
showard9dbdcda2008-10-14 17:34:36 +0000459 user = thread_local.get_user()
460 for queue_entry in host_queue_entries:
461 queue_entry.abort(user)
showard9d821ab2008-07-11 16:54:29 +0000462
463
mblighe8819cd2008-02-15 16:48:40 +0000464def get_jobs(not_yet_run=False, running=False, finished=False, **filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000465 """\
466 Extra filter args for get_jobs:
467 -not_yet_run: Include only jobs that have not yet started running.
468 -running: Include only jobs that have start running but for which not
469 all hosts have completed.
470 -finished: Include only jobs for which all hosts have completed (or
471 aborted).
472 At most one of these three fields should be specified.
473 """
474 filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run,
475 running,
476 finished)
showard0957a842009-05-11 19:25:08 +0000477 job_dicts = []
478 jobs = list(models.Job.query_objects(filter_data))
479 models.Job.objects.populate_relationships(jobs, models.Label,
480 'dependencies')
481 for job in jobs:
482 job_dict = job.get_object_dict()
483 job_dict['dependencies'] = ','.join(label.name
484 for label in job.dependencies)
485 job_dicts.append(job_dict)
486 return rpc_utils.prepare_for_serialization(job_dicts)
mblighe8819cd2008-02-15 16:48:40 +0000487
488
489def get_num_jobs(not_yet_run=False, running=False, finished=False,
jadmanski0afbb632008-06-06 21:10:57 +0000490 **filter_data):
491 """\
492 See get_jobs() for documentation of extra filter parameters.
493 """
494 filter_data['extra_args'] = rpc_utils.extra_job_filters(not_yet_run,
495 running,
496 finished)
497 return models.Job.query_count(filter_data)
mblighe8819cd2008-02-15 16:48:40 +0000498
499
mblighe8819cd2008-02-15 16:48:40 +0000500def get_jobs_summary(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000501 """\
showarda8709c52008-07-03 19:44:54 +0000502 Like get_jobs(), but adds a 'status_counts' field, which is a dictionary
jadmanski0afbb632008-06-06 21:10:57 +0000503 mapping status strings to the number of hosts currently with that
504 status, i.e. {'Queued' : 4, 'Running' : 2}.
505 """
506 jobs = get_jobs(**filter_data)
507 ids = [job['id'] for job in jobs]
508 all_status_counts = models.Job.objects.get_status_counts(ids)
509 for job in jobs:
510 job['status_counts'] = all_status_counts[job['id']]
511 return rpc_utils.prepare_for_serialization(jobs)
mblighe8819cd2008-02-15 16:48:40 +0000512
513
showard4d077562009-05-08 18:24:36 +0000514def get_info_for_clone(id, preserve_metahosts, queue_entry_ids=None):
showarda8709c52008-07-03 19:44:54 +0000515 """\
516 Retrieves all the information needed to clone a job.
517 """
showarda8709c52008-07-03 19:44:54 +0000518 job = models.Job.objects.get(id=id)
showard29f7cd22009-04-29 21:16:24 +0000519 job_info = rpc_utils.get_job_info(job,
showard4d077562009-05-08 18:24:36 +0000520 preserve_metahosts=preserve_metahosts,
521 queue_entry_ids=queue_entry_ids)
showard945072f2008-09-03 20:34:59 +0000522
showardd9992fe2008-07-31 02:15:03 +0000523 host_dicts = []
showard29f7cd22009-04-29 21:16:24 +0000524 for host in job_info['hosts']:
525 host_dict = get_hosts(id=host.id)[0]
526 other_labels = host_dict['labels']
527 if host_dict['platform']:
528 other_labels.remove(host_dict['platform'])
529 host_dict['other_labels'] = ', '.join(other_labels)
showardd9992fe2008-07-31 02:15:03 +0000530 host_dicts.append(host_dict)
showarda8709c52008-07-03 19:44:54 +0000531
showard29f7cd22009-04-29 21:16:24 +0000532 for host in job_info['one_time_hosts']:
533 host_dict = dict(hostname=host.hostname,
534 id=host.id,
535 platform='(one-time host)',
536 locked_text='')
537 host_dicts.append(host_dict)
showarda8709c52008-07-03 19:44:54 +0000538
showard4d077562009-05-08 18:24:36 +0000539 # convert keys from Label objects to strings (names of labels)
showard29f7cd22009-04-29 21:16:24 +0000540 meta_host_counts = dict((meta_host.name, count) for meta_host, count
showard4d077562009-05-08 18:24:36 +0000541 in job_info['meta_host_counts'].iteritems())
showard29f7cd22009-04-29 21:16:24 +0000542
543 info = dict(job=job.get_object_dict(),
544 meta_host_counts=meta_host_counts,
545 hosts=host_dicts)
546 info['job']['dependencies'] = job_info['dependencies']
547 if job_info['atomic_group']:
548 info['atomic_group_name'] = (job_info['atomic_group']).name
549 else:
550 info['atomic_group_name'] = None
showarda8709c52008-07-03 19:44:54 +0000551
552 return rpc_utils.prepare_for_serialization(info)
553
554
showard34dc5fa2008-04-24 20:58:40 +0000555# host queue entries
556
557def get_host_queue_entries(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000558 """\
showardc92da832009-04-07 18:14:34 +0000559 @returns A sequence of nested dictionaries of host and job information.
jadmanski0afbb632008-06-06 21:10:57 +0000560 """
showardc92da832009-04-07 18:14:34 +0000561 return rpc_utils.prepare_rows_as_nested_dicts(
562 models.HostQueueEntry.query_objects(filter_data),
563 ('host', 'atomic_group', 'job'))
showard34dc5fa2008-04-24 20:58:40 +0000564
565
566def get_num_host_queue_entries(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000567 """\
568 Get the number of host queue entries associated with this job.
569 """
570 return models.HostQueueEntry.query_count(filter_data)
showard34dc5fa2008-04-24 20:58:40 +0000571
572
showard1e935f12008-07-11 00:11:36 +0000573def get_hqe_percentage_complete(**filter_data):
574 """
showardc92da832009-04-07 18:14:34 +0000575 Computes the fraction of host queue entries matching the given filter data
showard1e935f12008-07-11 00:11:36 +0000576 that are complete.
577 """
578 query = models.HostQueueEntry.query_objects(filter_data)
579 complete_count = query.filter(complete=True).count()
580 total_count = query.count()
581 if total_count == 0:
582 return 1
583 return float(complete_count) / total_count
584
585
showard29f7cd22009-04-29 21:16:24 +0000586# recurring run
587
588def get_recurring(**filter_data):
589 return rpc_utils.prepare_rows_as_nested_dicts(
590 models.RecurringRun.query_objects(filter_data),
591 ('job', 'owner'))
592
593
594def get_num_recurring(**filter_data):
595 return models.RecurringRun.query_count(filter_data)
596
597
598def delete_recurring_runs(**filter_data):
599 to_delete = models.RecurringRun.query_objects(filter_data)
600 to_delete.delete()
601
602
603def create_recurring_run(job_id, start_date, loop_period, loop_count):
604 owner = thread_local.get_user().login
605 job = models.Job.objects.get(id=job_id)
606 return job.create_recurring_job(start_date=start_date,
607 loop_period=loop_period,
608 loop_count=loop_count,
609 owner=owner)
610
611
mblighe8819cd2008-02-15 16:48:40 +0000612# other
613
showarde0b63622008-08-04 20:58:47 +0000614def echo(data=""):
615 """\
616 Returns a passed in string. For doing a basic test to see if RPC calls
617 can successfully be made.
618 """
619 return data
620
621
showardb7a52fd2009-04-27 20:10:56 +0000622def get_motd():
623 """\
624 Returns the message of the day as a string.
625 """
626 return rpc_utils.get_motd()
627
628
mblighe8819cd2008-02-15 16:48:40 +0000629def get_static_data():
jadmanski0afbb632008-06-06 21:10:57 +0000630 """\
631 Returns a dictionary containing a bunch of data that shouldn't change
632 often and is otherwise inaccessible. This includes:
showardc92da832009-04-07 18:14:34 +0000633
634 priorities: List of job priority choices.
635 default_priority: Default priority value for new jobs.
636 users: Sorted list of all users.
637 labels: Sorted list of all labels.
638 atomic_groups: Sorted list of all atomic groups.
639 tests: Sorted list of all tests.
640 profilers: Sorted list of all profilers.
641 current_user: Logged-in username.
642 host_statuses: Sorted list of possible Host statuses.
643 job_statuses: Sorted list of possible HostQueueEntry statuses.
644 job_timeout_default: The default job timeout length in hours.
645 reboot_before_options: A list of valid RebootBefore string enums.
646 reboot_after_options: A list of valid RebootAfter string enums.
647 motd: Server's message of the day.
648 status_dictionary: A mapping from one word job status names to a more
649 informative description.
jadmanski0afbb632008-06-06 21:10:57 +0000650 """
showard21baa452008-10-21 00:08:39 +0000651
652 job_fields = models.Job.get_field_dict()
653
jadmanski0afbb632008-06-06 21:10:57 +0000654 result = {}
655 result['priorities'] = models.Job.Priority.choices()
showard21baa452008-10-21 00:08:39 +0000656 default_priority = job_fields['priority'].default
jadmanski0afbb632008-06-06 21:10:57 +0000657 default_string = models.Job.Priority.get_string(default_priority)
658 result['default_priority'] = default_string
659 result['users'] = get_users(sort_by=['login'])
660 result['labels'] = get_labels(sort_by=['-platform', 'name'])
showardc92da832009-04-07 18:14:34 +0000661 result['atomic_groups'] = get_atomic_groups(sort_by=['name'])
jadmanski0afbb632008-06-06 21:10:57 +0000662 result['tests'] = get_tests(sort_by=['name'])
showard2b9a88b2008-06-13 20:55:03 +0000663 result['profilers'] = get_profilers(sort_by=['name'])
showard0fc38302008-10-23 00:44:07 +0000664 result['current_user'] = rpc_utils.prepare_for_serialization(
665 thread_local.get_user().get_object_dict())
showard2b9a88b2008-06-13 20:55:03 +0000666 result['host_statuses'] = sorted(models.Host.Status.names)
mbligh5a198b92008-12-11 19:33:29 +0000667 result['job_statuses'] = sorted(models.HostQueueEntry.Status.names)
showardb1e51872008-10-07 11:08:18 +0000668 result['job_timeout_default'] = models.Job.DEFAULT_TIMEOUT
showard0fc38302008-10-23 00:44:07 +0000669 result['reboot_before_options'] = models.RebootBefore.names
670 result['reboot_after_options'] = models.RebootAfter.names
showard8fbae652009-01-20 23:23:10 +0000671 result['motd'] = rpc_utils.get_motd()
showard8ac29b42008-07-17 17:01:55 +0000672
showardd3dc1992009-04-22 21:01:40 +0000673 result['status_dictionary'] = {"Aborted": "Aborted",
showard8ac29b42008-07-17 17:01:55 +0000674 "Verifying": "Verifying Host",
675 "Pending": "Waiting on other hosts",
676 "Running": "Running autoserv",
677 "Completed": "Autoserv completed",
678 "Failed": "Failed to complete",
showardd823b362008-07-24 16:35:46 +0000679 "Queued": "Queued",
showard5deb6772008-11-04 21:54:33 +0000680 "Starting": "Next in host's queue",
681 "Stopped": "Other host(s) failed verify",
showardd3dc1992009-04-22 21:01:40 +0000682 "Parsing": "Awaiting parse of final results",
showard29f7cd22009-04-29 21:16:24 +0000683 "Gathering": "Gathering log files",
684 "Template": "Template job for recurring run"}
685
jadmanski0afbb632008-06-06 21:10:57 +0000686 return result
showard29f7cd22009-04-29 21:16:24 +0000687
688
689def get_server_time():
690 return datetime.datetime.now().strftime("%Y-%m-%d %H:%M")