blob: bff180ba5ba8d9a88367cdee12012743594052af [file] [log] [blame]
mblighbe630eb2008-08-01 16:41:48 +00001#
2# Copyright 2008 Google Inc. All Rights Reserved.
3
4"""
5The job module contains the objects and methods used to
6manage jobs in Autotest.
7
8The valid actions are:
9list: lists job(s)
10create: create a job
11abort: abort job(s)
12stat: detailed listing of job(s)
13
14The common options are:
15
16See topic_common.py for a High Level Design and Algorithm.
17"""
18
19import getpass, os, pwd, re, socket, sys
20from autotest_lib.cli import topic_common, action_common
21
22
23class job(topic_common.atest):
24 """Job class
25 atest job [create|list|stat|abort] <options>"""
26 usage_action = '[create|list|stat|abort]'
27 topic = msg_topic = 'job'
28 msg_items = '<job_ids>'
29
30
31 def _convert_status(self, results):
32 for result in results:
mbligh10a47332008-08-11 19:37:46 +000033 total = sum(result['status_counts'].values())
34 status = ['%s:%s(%.1f%%)' % (key, val, 100.0*float(val)/total)
35 for key, val in result['status_counts'].iteritems()]
mblighbe630eb2008-08-01 16:41:48 +000036 status.sort()
37 result['status_counts'] = ', '.join(status)
38
39
40class job_help(job):
41 """Just here to get the atest logic working.
42 Usage is set by its parent"""
43 pass
44
45
46class job_list_stat(action_common.atest_list, job):
47 def __split_jobs_between_ids_names(self):
48 job_ids = []
49 job_names = []
50
51 # Sort between job IDs and names
52 for job_id in self.jobs:
53 if job_id.isdigit():
54 job_ids.append(job_id)
55 else:
56 job_names.append(job_id)
57 return (job_ids, job_names)
58
59
60 def execute_on_ids_and_names(self, op, filters={},
61 check_results={'id__in': 'id',
62 'name__in': 'id'},
63 tag_id='id__in', tag_name='name__in'):
64 if not self.jobs:
65 # Want everything
66 return super(job_list_stat, self).execute(op=op, filters=filters)
67
68 all_jobs = []
69 (job_ids, job_names) = self.__split_jobs_between_ids_names()
70
71 for items, tag in [(job_ids, tag_id),
72 (job_names, tag_name)]:
73 if items:
74 new_filters = filters.copy()
75 new_filters[tag] = items
76 jobs = super(job_list_stat,
77 self).execute(op=op,
78 filters=new_filters,
79 check_results=check_results)
80 all_jobs.extend(jobs)
81
82 return all_jobs
83
84
85class job_list(job_list_stat):
86 """atest job list [<jobs>] [--all] [--running] [--user <username>]"""
87 def __init__(self):
88 super(job_list, self).__init__()
89 self.parser.add_option('-a', '--all', help='List jobs for all '
90 'users.', action='store_true', default=False)
91 self.parser.add_option('-r', '--running', help='List only running '
92 'jobs', action='store_true')
93 self.parser.add_option('-u', '--user', help='List jobs for given '
94 'user', type='string')
95
96
97 def parse(self):
98 (options, leftover) = self.parse_with_flist([('jobs', '', '', True)],
99 None)
100 self.all = options.all
101 self.data['running'] = options.running
102 if options.user:
103 if options.all:
104 self.invalid_syntax('Only specify --all or --user, not both.')
105 else:
106 self.data['owner'] = options.user
107 elif not options.all and not self.jobs:
108 self.data['owner'] = getpass.getuser()
109
110 return (options, leftover)
111
112
113 def execute(self):
114 return self.execute_on_ids_and_names(op='get_jobs_summary',
115 filters=self.data)
116
117
118 def output(self, results):
119 keys = ['id', 'owner', 'name', 'status_counts']
120 if self.verbose:
121 keys.extend(['priority', 'control_type', 'created_on'])
122 self._convert_status(results)
123 super(job_list, self).output(results, keys)
124
125
126
127class job_stat(job_list_stat):
128 """atest job stat <job>"""
129 usage_action = 'stat'
130
131 def __init__(self):
132 super(job_stat, self).__init__()
133 self.parser.add_option('-f', '--control-file',
134 help='Display the control file',
135 action='store_true', default=False)
136
137
138 def parse(self):
139 (options, leftover) = self.parse_with_flist(flists=[('jobs', '', '',
140 True)],
141 req_items='jobs')
142 if not self.jobs:
143 self.invalid_syntax('Must specify at least one job.')
144
145 self.show_control_file = options.control_file
146
147 return (options, leftover)
148
149
150 def _merge_results(self, summary, qes):
151 hosts_status = {}
152 for qe in qes:
153 if qe['host']:
154 job_id = qe['job']['id']
155 hostname = qe['host']['hostname']
156 hosts_status.setdefault(job_id,
157 {}).setdefault(qe['status'],
158 []).append(hostname)
159
160 for job in summary:
161 job_id = job['id']
162 if hosts_status.has_key(job_id):
163 this_job = hosts_status[job_id]
164 host_per_status = ['%s:%s' %(status, ','.join(host))
165 for status, host in this_job.iteritems()]
166 job['hosts_status'] = ', '.join(host_per_status)
167 else:
168 job['hosts_status'] = ''
169 return summary
170
171
172 def execute(self):
173 summary = self.execute_on_ids_and_names(op='get_jobs_summary')
174
175 # Get the real hostnames
176 qes = self.execute_on_ids_and_names(op='get_host_queue_entries',
177 check_results={},
178 tag_id='job__in',
179 tag_name='job__name__in')
180
181 self._convert_status(summary)
182
183 return self._merge_results(summary, qes)
184
185
186 def output(self, results):
187 if not self.verbose:
188 keys = ['id', 'name', 'priority', 'status_counts', 'hosts_status']
189 else:
190 keys = ['id', 'name', 'priority', 'status_counts', 'hosts_status',
showard21baa452008-10-21 00:08:39 +0000191 'owner', 'control_type', 'synch_type', 'created_on',
192 'run_verify', 'reboot_before', 'reboot_after']
mblighbe630eb2008-08-01 16:41:48 +0000193
194 if self.show_control_file:
195 keys.append('control_file')
196
197 super(job_stat, self).output(results, keys)
198
199
200class job_create(action_common.atest_create, job):
201 """atest job create [--priority <Low|Medium|High|Urgent>]
202 [--is-synchronous] [--container] [--control-file </path/to/cfile>]
203 [--on-server] [--test <test1,test2>] [--kernel <http://kernel>]
204 [--mlist </path/to/machinelist>] [--machine <host1 host2 host3>]
showard21baa452008-10-21 00:08:39 +0000205 [--dependencies <list of dependency labels]
206 [--reboot_before <option>] [--reboot_after <option>]
mblighae64d3a2008-10-15 04:13:52 +0000207 job_name
208
209 Creating a job is rather different from the other create operations,
210 so it only uses the __init__() and output() from its superclass.
211 """
mblighbe630eb2008-08-01 16:41:48 +0000212 op_action = 'create'
213 msg_items = 'job_name'
mblighbe630eb2008-08-01 16:41:48 +0000214
215 def __init__(self):
216 super(job_create, self).__init__()
217 self.hosts = []
218 self.ctrl_file_data = {}
219 self.data_item_key = 'name'
220 self.parser.add_option('-p', '--priority', help='Job priority (low, '
221 'medium, high, urgent), default=medium',
222 type='choice', choices=('low', 'medium', 'high',
223 'urgent'), default='medium')
224 self.parser.add_option('-y', '--synchronous', action='store_true',
225 help='Make the job synchronous',
226 default=False)
227 self.parser.add_option('-c', '--container', help='Run this client job '
228 'in a container', action='store_true',
229 default=False)
230 self.parser.add_option('-f', '--control-file',
231 help='use this control file', metavar='FILE')
232 self.parser.add_option('-s', '--server',
233 help='This is server-side job',
234 action='store_true', default=False)
235 self.parser.add_option('-t', '--test',
mbligh51148c72008-08-11 20:23:58 +0000236 help='List of tests to run')
mblighbe630eb2008-08-01 16:41:48 +0000237 self.parser.add_option('-k', '--kernel', help='Install kernel from this'
238 ' URL before beginning job')
mbligh4eae22a2008-10-10 16:09:46 +0000239 self.parser.add_option('-d', '--dependencies', help='Comma separated '
240 'list of dependencies for this test.',
241 default='')
mblighbe630eb2008-08-01 16:41:48 +0000242 self.parser.add_option('-m', '--machine', help='List of machines to '
243 'run on')
244 self.parser.add_option('-M', '--mlist',
245 help='File listing machines to use',
246 type='string', metavar='MACHINE_FLIST')
mbligh6fee7fd2008-10-10 15:44:39 +0000247 self.parser.add_option('-e', '--email', help='A comma seperated list '
248 'of email addresses to notify of job completion',
249 default='')
showard21baa452008-10-21 00:08:39 +0000250 self.parser.add_option('-b', '--reboot_before',
251 help='Whether or not to reboot the machine '
252 'before the job (never/if dirty/always)',
253 type='choice',
254 choices=('never', 'if dirty', 'always'))
255 self.parser.add_option('-a', '--reboot_after',
256 help='Whether or not to reboot the machine '
257 'after the job (never/if all tests passed/'
258 'always)',
259 type='choice',
260 choices=('never', 'if all tests passed',
261 'always'))
mblighbe630eb2008-08-01 16:41:48 +0000262
263
264 def parse_hosts(self, args):
265 """ Parses the arguments to generate a list of hosts and meta_hosts
266 A host is a regular name, a meta_host is n*label or *label.
267 These can be mixed on the CLI, and separated by either commas or
268 spaces, e.g.: 5*Machine_Label host0 5*Machine_Label2,host2 """
269
270 hosts = []
271 meta_hosts = []
272
273 for arg in args:
274 for host in arg.split(','):
275 if re.match('^[0-9]+[*]', host):
276 num, host = host.split('*', 1)
277 meta_hosts += int(num) * [host]
278 elif re.match('^[*](\w*)', host):
279 meta_hosts += [re.match('^[*](\w*)', host).group(1)]
280 elif host != '':
281 # Real hostname
282 hosts.append(host)
283
284 return (hosts, meta_hosts)
285
286
287 def parse(self):
288 flists = [('hosts', 'mlist', 'machine', False),
289 ('jobname', '', '', True)]
290 (options, leftover) = self.parse_with_flist(flists,
291 req_items='jobname')
292 self.data = {}
293
294 if len(self.hosts) == 0:
295 self.invalid_syntax('Must specify at least one host')
296 if not options.control_file and not options.test:
297 self.invalid_syntax('Must specify either --test or --control-file'
298 ' to create a job.')
299 if options.control_file and options.test:
300 self.invalid_syntax('Can only specify one of --control-file or '
301 '--test, not both.')
302 if options.container and options.server:
303 self.invalid_syntax('Containers (--container) can only be added to'
304 ' client side jobs.')
305 if options.control_file:
306 if options.kernel:
307 self.invalid_syntax('Use --kernel only in conjunction with '
308 '--test, not --control-file.')
309 if options.container:
310 self.invalid_syntax('Containers (--container) can only be added'
311 ' with --test, not --control-file.')
mbligh4eae22a2008-10-10 16:09:46 +0000312 deps = options.dependencies.split(',')
313 deps = [dep.strip() for dep in deps if dep.strip()]
314 self.data['dependencies'] = deps
mblighbe630eb2008-08-01 16:41:48 +0000315 try:
316 self.data['control_file'] = open(options.control_file).read()
317 except IOError:
318 self.generic_error('Unable to read from specified '
319 'control-file: %s' % options.control_file)
mbligh4eae22a2008-10-10 16:09:46 +0000320 if options.test:
321 if options.server or options.synchronous or options.dependencies:
322 self.invalid_syntax('If you specify tests, the client/server, '
323 'synchronous, and dependency settings are '
324 'implicit and cannot be overriden.')
325 tests = [t.strip() for t in options.test.split(',') if t.strip()]
326 self.ctrl_file_data = {'tests': tests}
327 if options.kernel:
328 self.ctrl_file_data['kernel'] = options.kernel
329 self.ctrl_file_data['do_push_packages'] = True
330 self.ctrl_file_data['use_container'] = options.container
331
mblighbe630eb2008-08-01 16:41:48 +0000332
333 if options.priority:
334 self.data['priority'] = options.priority.capitalize()
showard21baa452008-10-21 00:08:39 +0000335 if options.reboot_before:
336 self.data['reboot_before'] = options.reboot_before.capitalize()
337 if options.reboot_after:
338 self.data['reboot_after'] = options.reboot_after.capitalize()
mblighbe630eb2008-08-01 16:41:48 +0000339
340 if len(self.jobname) > 1:
341 self.invalid_syntax('Too many arguments specified, only expected '
342 'to receive job name: %s' % self.jobname)
343 self.jobname = self.jobname[0]
344 self.data['name'] = self.jobname
345
346 (self.data['hosts'],
347 self.data['meta_hosts']) = self.parse_hosts(self.hosts)
348
349
mbligh6fee7fd2008-10-10 15:44:39 +0000350 self.data['email_list'] = options.email
mblighbe630eb2008-08-01 16:41:48 +0000351 self.data['is_synchronous'] = options.synchronous
352 if options.server:
353 self.data['control_type'] = 'Server'
354 else:
355 self.data['control_type'] = 'Client'
356
mblighbe630eb2008-08-01 16:41:48 +0000357 return (options, leftover)
358
359
360 def execute(self):
361 if self.ctrl_file_data:
362 if self.ctrl_file_data.has_key('kernel'):
363 socket.setdefaulttimeout(topic_common.UPLOAD_SOCKET_TIMEOUT)
364 print 'Uploading Kernel: this may take a while...',
365
showard989f25d2008-10-01 11:38:11 +0000366 cf_info = self.execute_rpc(op='generate_control_file',
367 item=self.jobname,
368 **self.ctrl_file_data)
mblighbe630eb2008-08-01 16:41:48 +0000369
370 if self.ctrl_file_data.has_key('kernel'):
371 print 'Done'
372 socket.setdefaulttimeout(topic_common.DEFAULT_SOCKET_TIMEOUT)
showard989f25d2008-10-01 11:38:11 +0000373 self.data['control_file'] = cf_info['control_file']
374 self.data['is_synchronous'] = cf_info['is_synchronous']
375 if cf_info['is_server']:
mblighbe630eb2008-08-01 16:41:48 +0000376 self.data['control_type'] = 'Server'
377 else:
378 self.data['control_type'] = 'Client'
mblighae64d3a2008-10-15 04:13:52 +0000379
showard989f25d2008-10-01 11:38:11 +0000380 self.data['dependencies'] = cf_info['dependencies']
mblighae64d3a2008-10-15 04:13:52 +0000381
382 job_id = self.execute_rpc(op='create_job', **self.data)
383 return ['%s (id %s)' % (self.jobname, job_id)]
mblighbe630eb2008-08-01 16:41:48 +0000384
385
386 def get_items(self):
387 return [self.jobname]
388
389
390class job_abort(job, action_common.atest_delete):
391 """atest job abort <job(s)>"""
392 usage_action = op_action = 'abort'
393 msg_done = 'Aborted'
394
395 def parse(self):
396 (options, leftover) = self.parse_with_flist([('jobids', '', '', True)],
397 req_items='jobids')
398
399
400 def get_items(self):
401 return self.jobids