blob: 22701f2fdf1ec4123cca97a71a4f2000d0b045cd [file] [log] [blame]
mbligh96cf0512008-04-17 15:25:38 +00001#!/usr/bin/python -u
mblighc2514542008-02-19 15:54:26 +00002
Aviv Keshet687d2dc2016-10-20 15:41:16 -07003import collections
Fang Deng49822682014-10-21 16:29:22 -07004import datetime
Aviv Keshet687d2dc2016-10-20 15:41:16 -07005import errno
6import fcntl
Simran Basi1e10e922015-04-16 15:09:56 -07007import json
Aviv Keshet687d2dc2016-10-20 15:41:16 -07008import optparse
9import os
10import socket
Shuqian Zhao31425d52016-12-07 09:35:03 -080011import subprocess
Aviv Keshet687d2dc2016-10-20 15:41:16 -070012import sys
Dan Shi11e35062017-11-03 10:09:05 -070013import time
Aviv Keshet687d2dc2016-10-20 15:41:16 -070014import traceback
mblighbb7b8912006-10-08 03:59:02 +000015
mbligh96cf0512008-04-17 15:25:38 +000016import common
Dan Shi4f8c0242017-07-07 15:34:49 -070017from autotest_lib.client.bin.result_tools import utils as result_utils
18from autotest_lib.client.bin.result_tools import utils_lib as result_utils_lib
19from autotest_lib.client.bin.result_tools import runner as result_runner
20from autotest_lib.client.common_lib import control_data
Benny Peakefeb775c2017-02-08 15:14:14 -080021from autotest_lib.client.common_lib import global_config
jadmanskidb4f9b52008-12-03 22:52:53 +000022from autotest_lib.client.common_lib import mail, pidfile
Fang Deng49822682014-10-21 16:29:22 -070023from autotest_lib.client.common_lib import utils
Fang Deng49822682014-10-21 16:29:22 -070024from autotest_lib.frontend import setup_django_environment
Fang Deng9ec66802014-04-28 19:04:33 +000025from autotest_lib.frontend.tko import models as tko_models
Shuqian Zhao19e62fb2017-01-09 10:10:14 -080026from autotest_lib.server import site_utils
Fang Deng49822682014-10-21 16:29:22 -070027from autotest_lib.server.cros.dynamic_suite import constants
Benny Peaked322d3d2017-02-08 15:39:28 -080028from autotest_lib.site_utils.sponge_lib import sponge_utils
Dennis Jeffreyf9bef6c2013-08-05 11:01:27 -070029from autotest_lib.tko import db as tko_db, utils as tko_utils
Luigi Semenzatoe7064812017-02-03 14:47:59 -080030from autotest_lib.tko import models, parser_lib
Dennis Jeffreyf9bef6c2013-08-05 11:01:27 -070031from autotest_lib.tko.perf_upload import perf_uploader
mbligh74fc0462007-11-05 20:24:17 +000032
Dan Shib0af6212017-07-17 14:40:02 -070033try:
34 from chromite.lib import metrics
35except ImportError:
36 metrics = utils.metrics_mock
37
38
Aviv Keshet687d2dc2016-10-20 15:41:16 -070039_ParseOptions = collections.namedtuple(
Shuqian Zhao19e62fb2017-01-09 10:10:14 -080040 'ParseOptions', ['reparse', 'mail_on_failure', 'dry_run', 'suite_report',
41 'datastore_creds', 'export_to_gcloud_path'])
Aviv Keshet687d2dc2016-10-20 15:41:16 -070042
mbligh96cf0512008-04-17 15:25:38 +000043def parse_args():
Fang Deng49822682014-10-21 16:29:22 -070044 """Parse args."""
jadmanski0afbb632008-06-06 21:10:57 +000045 # build up our options parser and parse sys.argv
46 parser = optparse.OptionParser()
47 parser.add_option("-m", help="Send mail for FAILED tests",
48 dest="mailit", action="store_true")
49 parser.add_option("-r", help="Reparse the results of a job",
50 dest="reparse", action="store_true")
51 parser.add_option("-o", help="Parse a single results directory",
52 dest="singledir", action="store_true")
53 parser.add_option("-l", help=("Levels of subdirectories to include "
54 "in the job name"),
55 type="int", dest="level", default=1)
56 parser.add_option("-n", help="No blocking on an existing parse",
57 dest="noblock", action="store_true")
58 parser.add_option("-s", help="Database server hostname",
59 dest="db_host", action="store")
60 parser.add_option("-u", help="Database username", dest="db_user",
61 action="store")
62 parser.add_option("-p", help="Database password", dest="db_pass",
63 action="store")
64 parser.add_option("-d", help="Database name", dest="db_name",
65 action="store")
Aviv Keshet0b7bab02016-10-20 17:17:36 -070066 parser.add_option("--dry-run", help="Do not actually commit any results.",
67 dest="dry_run", action="store_true", default=False)
Prathmesh Prabhu3e319da2017-08-30 19:13:03 -070068 parser.add_option(
69 "--detach", action="store_true",
70 help="Detach parsing process from the caller process. Used by "
71 "monitor_db to safely restart without affecting parsing.",
72 default=False)
jadmanskid5ab8c52008-12-03 16:27:07 +000073 parser.add_option("--write-pidfile",
74 help="write pidfile (.parser_execute)",
75 dest="write_pidfile", action="store_true",
76 default=False)
Fang Deng49822682014-10-21 16:29:22 -070077 parser.add_option("--record-duration",
Prathmesh Prabhu77769452018-04-17 13:30:50 -070078 help="[DEPRECATED] Record timing to metadata db",
Fang Deng49822682014-10-21 16:29:22 -070079 dest="record_duration", action="store_true",
80 default=False)
Shuqian Zhao31425d52016-12-07 09:35:03 -080081 parser.add_option("--suite-report",
82 help=("Allows parsing job to attempt to create a suite "
Shuqian Zhao19e62fb2017-01-09 10:10:14 -080083 "timeline report, if it detects that the job being "
Shuqian Zhao31425d52016-12-07 09:35:03 -080084 "parsed is a suite job."),
85 dest="suite_report", action="store_true",
86 default=False)
Shuqian Zhao19e62fb2017-01-09 10:10:14 -080087 parser.add_option("--datastore-creds",
88 help=("The path to gcloud datastore credentials file, "
89 "which will be used to upload suite timeline "
90 "report to gcloud. If not specified, the one "
91 "defined in shadow_config will be used."),
92 dest="datastore_creds", action="store", default=None)
93 parser.add_option("--export-to-gcloud-path",
94 help=("The path to export_to_gcloud script. Please find "
95 "chromite path on your server. The script is under "
96 "chromite/bin/."),
97 dest="export_to_gcloud_path", action="store",
98 default=None)
jadmanski0afbb632008-06-06 21:10:57 +000099 options, args = parser.parse_args()
mbligh74fc0462007-11-05 20:24:17 +0000100
jadmanski0afbb632008-06-06 21:10:57 +0000101 # we need a results directory
102 if len(args) == 0:
103 tko_utils.dprint("ERROR: at least one results directory must "
104 "be provided")
105 parser.print_help()
106 sys.exit(1)
mbligh74fc0462007-11-05 20:24:17 +0000107
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800108 if not options.datastore_creds:
109 gcloud_creds = global_config.global_config.get_config_value(
110 'GCLOUD', 'cidb_datastore_writer_creds', default=None)
111 options.datastore_creds = (site_utils.get_creds_abspath(gcloud_creds)
112 if gcloud_creds else None)
113
114 if not options.export_to_gcloud_path:
115 export_script = 'chromiumos/chromite/bin/export_to_gcloud'
116 # If it is a lab server, the script is under ~chromeos-test/
117 if os.path.exists(os.path.expanduser('~chromeos-test/%s' %
118 export_script)):
119 path = os.path.expanduser('~chromeos-test/%s' % export_script)
120 # If it is a local workstation, it is probably under ~/
121 elif os.path.exists(os.path.expanduser('~/%s' % export_script)):
122 path = os.path.expanduser('~/%s' % export_script)
123 # If it is not found anywhere, the default will be set to None.
124 else:
125 path = None
126 options.export_to_gcloud_path = path
127
jadmanski0afbb632008-06-06 21:10:57 +0000128 # pass the options back
129 return options, args
mbligh74fc0462007-11-05 20:24:17 +0000130
131
mbligh96cf0512008-04-17 15:25:38 +0000132def format_failure_message(jobname, kernel, testname, status, reason):
Fang Deng49822682014-10-21 16:29:22 -0700133 """Format failure message with the given information.
134
135 @param jobname: String representing the job name.
136 @param kernel: String representing the kernel.
137 @param testname: String representing the test name.
138 @param status: String representing the test status.
139 @param reason: String representing the reason.
140
141 @return: Failure message as a string.
142 """
jadmanski0afbb632008-06-06 21:10:57 +0000143 format_string = "%-12s %-20s %-12s %-10s %s"
144 return format_string % (jobname, kernel, testname, status, reason)
mblighb85e6b02006-10-08 17:20:56 +0000145
mblighbb7b8912006-10-08 03:59:02 +0000146
mbligh96cf0512008-04-17 15:25:38 +0000147def mailfailure(jobname, job, message):
Fang Deng49822682014-10-21 16:29:22 -0700148 """Send an email about the failure.
149
150 @param jobname: String representing the job name.
151 @param job: A job object.
152 @param message: The message to mail.
153 """
jadmanski0afbb632008-06-06 21:10:57 +0000154 message_lines = [""]
155 message_lines.append("The following tests FAILED for this job")
156 message_lines.append("http://%s/results/%s" %
157 (socket.gethostname(), jobname))
158 message_lines.append("")
159 message_lines.append(format_failure_message("Job name", "Kernel",
160 "Test name", "FAIL/WARN",
161 "Failure reason"))
162 message_lines.append(format_failure_message("=" * 8, "=" * 6, "=" * 8,
163 "=" * 8, "=" * 14))
164 message_header = "\n".join(message_lines)
mbligh96cf0512008-04-17 15:25:38 +0000165
jadmanski0afbb632008-06-06 21:10:57 +0000166 subject = "AUTOTEST: FAILED tests from job %s" % jobname
167 mail.send("", job.user, "", subject, message_header + message)
mbligh006f2302007-09-13 20:46:46 +0000168
169
Fang Deng9ec66802014-04-28 19:04:33 +0000170def _invalidate_original_tests(orig_job_idx, retry_job_idx):
171 """Retry tests invalidates original tests.
172
173 Whenever a retry job is complete, we want to invalidate the original
174 job's test results, such that the consumers of the tko database
175 (e.g. tko frontend, wmatrix) could figure out which results are the latest.
176
177 When a retry job is parsed, we retrieve the original job's afe_job_id
178 from the retry job's keyvals, which is then converted to tko job_idx and
179 passed into this method as |orig_job_idx|.
180
181 In this method, we are going to invalidate the rows in tko_tests that are
182 associated with the original job by flipping their 'invalid' bit to True.
183 In addition, in tko_tests, we also maintain a pointer from the retry results
184 to the original results, so that later we can always know which rows in
185 tko_tests are retries and which are the corresponding original results.
186 This is done by setting the field 'invalidates_test_idx' of the tests
187 associated with the retry job.
188
189 For example, assume Job(job_idx=105) are retried by Job(job_idx=108), after
190 this method is run, their tko_tests rows will look like:
191 __________________________________________________________________________
192 test_idx| job_idx | test | ... | invalid | invalidates_test_idx
193 10 | 105 | dummy_Fail.Error| ... | 1 | NULL
194 11 | 105 | dummy_Fail.Fail | ... | 1 | NULL
195 ...
196 20 | 108 | dummy_Fail.Error| ... | 0 | 10
197 21 | 108 | dummy_Fail.Fail | ... | 0 | 11
198 __________________________________________________________________________
199 Note the invalid bits of the rows for Job(job_idx=105) are set to '1'.
200 And the 'invalidates_test_idx' fields of the rows for Job(job_idx=108)
201 are set to 10 and 11 (the test_idx of the rows for the original job).
202
203 @param orig_job_idx: An integer representing the original job's
204 tko job_idx. Tests associated with this job will
205 be marked as 'invalid'.
206 @param retry_job_idx: An integer representing the retry job's
207 tko job_idx. The field 'invalidates_test_idx'
208 of the tests associated with this job will be updated.
209
210 """
211 msg = 'orig_job_idx: %s, retry_job_idx: %s' % (orig_job_idx, retry_job_idx)
212 if not orig_job_idx or not retry_job_idx:
213 tko_utils.dprint('ERROR: Could not invalidate tests: ' + msg)
214 # Using django models here makes things easier, but make sure that
215 # before this method is called, all other relevant transactions have been
216 # committed to avoid race condition. In the long run, we might consider
217 # to make the rest of parser use django models.
218 orig_tests = tko_models.Test.objects.filter(job__job_idx=orig_job_idx)
219 retry_tests = tko_models.Test.objects.filter(job__job_idx=retry_job_idx)
220
221 # Invalidate original tests.
222 orig_tests.update(invalid=True)
223
224 # Maintain a dictionary that maps (test, subdir) to original tests.
225 # Note that within the scope of a job, (test, subdir) uniquelly
226 # identifies a test run, but 'test' does not.
227 # In a control file, one could run the same test with different
228 # 'subdir_tag', for example,
229 # job.run_test('dummy_Fail', tag='Error', subdir_tag='subdir_1')
230 # job.run_test('dummy_Fail', tag='Error', subdir_tag='subdir_2')
231 # In tko, we will get
232 # (test='dummy_Fail.Error', subdir='dummy_Fail.Error.subdir_1')
233 # (test='dummy_Fail.Error', subdir='dummy_Fail.Error.subdir_2')
234 invalidated_tests = {(orig_test.test, orig_test.subdir): orig_test
235 for orig_test in orig_tests}
236 for retry in retry_tests:
237 # It is possible that (retry.test, retry.subdir) doesn't exist
238 # in invalidated_tests. This could happen when the original job
239 # didn't run some of its tests. For example, a dut goes offline
240 # since the beginning of the job, in which case invalidated_tests
241 # will only have one entry for 'SERVER_JOB'.
242 orig_test = invalidated_tests.get((retry.test, retry.subdir), None)
243 if orig_test:
244 retry.invalidates_test = orig_test
245 retry.save()
246 tko_utils.dprint('DEBUG: Invalidated tests associated to job: ' + msg)
247
248
Dan Shi4f8c0242017-07-07 15:34:49 -0700249def _throttle_result_size(path):
250 """Limit the total size of test results for the given path.
251
252 @param path: Path of the result directory.
253 """
254 if not result_runner.ENABLE_RESULT_THROTTLING:
255 tko_utils.dprint(
256 'Result throttling is not enabled. Skipping throttling %s' %
257 path)
258 return
259
260 max_result_size_KB = control_data.DEFAULT_MAX_RESULT_SIZE_KB
Prathmesh Prabhu7e976822018-08-10 12:37:08 -0700261 hardcoded_control_file_names = (
262 # client side test control, as saved in old Autotest paths.
263 'control',
264 # server side test control, as saved in old Autotest paths.
265 'control.srv',
266 # All control files, as saved in skylab.
267 'control.from_control_name',
268 )
269 for control_file in hardcoded_control_file_names:
Dan Shi4f8c0242017-07-07 15:34:49 -0700270 control = os.path.join(path, control_file)
271 try:
272 max_result_size_KB = control_data.parse_control(
273 control, raise_warnings=False).max_result_size_KB
274 # Any value different from the default is considered to be the one
275 # set in the test control file.
276 if max_result_size_KB != control_data.DEFAULT_MAX_RESULT_SIZE_KB:
277 break
278 except IOError as e:
279 tko_utils.dprint(
280 'Failed to access %s. Error: %s\nDetails %s' %
281 (control, e, traceback.format_exc()))
282 except control_data.ControlVariableException as e:
283 tko_utils.dprint(
284 'Failed to parse %s. Error: %s\nDetails %s' %
285 (control, e, traceback.format_exc()))
286
287 try:
288 result_utils.execute(path, max_result_size_KB)
289 except:
290 tko_utils.dprint(
291 'Failed to throttle result size of %s.\nDetails %s' %
292 (path, traceback.format_exc()))
293
294
Michael Tangc89efa72017-08-03 14:27:10 -0700295def export_tko_job_to_file(job, jobname, filename):
296 """Exports the tko job to disk file.
297
298 @param job: database object.
299 @param jobname: the job name as string.
300 @param filename: The path to the results to be parsed.
301 """
302 try:
303 from autotest_lib.tko import job_serializer
304
305 serializer = job_serializer.JobSerializer()
306 serializer.serialize_to_binary(job, jobname, filename)
307 except ImportError:
308 tko_utils.dprint("WARNING: tko_pb2.py doesn't exist. Create by "
309 "compiling tko/tko.proto.")
310
311
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700312def parse_one(db, pid_file_manager, jobname, path, parse_options):
Fang Deng49822682014-10-21 16:29:22 -0700313 """Parse a single job. Optionally send email on failure.
314
315 @param db: database object.
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700316 @param pid_file_manager: pidfile.PidFileManager object.
Fang Deng49822682014-10-21 16:29:22 -0700317 @param jobname: the tag used to search for existing job in db,
318 e.g. '1234-chromeos-test/host1'
319 @param path: The path to the results to be parsed.
Aviv Keshet687d2dc2016-10-20 15:41:16 -0700320 @param parse_options: _ParseOptions instance.
jadmanski0afbb632008-06-06 21:10:57 +0000321 """
Aviv Keshet687d2dc2016-10-20 15:41:16 -0700322 reparse = parse_options.reparse
323 mail_on_failure = parse_options.mail_on_failure
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700324 dry_run = parse_options.dry_run
Shuqian Zhao31425d52016-12-07 09:35:03 -0800325 suite_report = parse_options.suite_report
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800326 datastore_creds = parse_options.datastore_creds
327 export_to_gcloud_path = parse_options.export_to_gcloud_path
Aviv Keshet687d2dc2016-10-20 15:41:16 -0700328
jadmanski0afbb632008-06-06 21:10:57 +0000329 tko_utils.dprint("\nScanning %s (%s)" % (jobname, path))
jadmanski9b6babf2009-04-21 17:57:40 +0000330 old_job_idx = db.find_job(jobname)
Prathmesh Prabhuedac1ee2018-04-18 19:16:34 -0700331 if old_job_idx is not None and not reparse:
332 tko_utils.dprint("! Job is already parsed, done")
333 return
mbligh96cf0512008-04-17 15:25:38 +0000334
jadmanski0afbb632008-06-06 21:10:57 +0000335 # look up the status version
jadmanskidb4f9b52008-12-03 22:52:53 +0000336 job_keyval = models.job.read_keyval(path)
337 status_version = job_keyval.get("status_version", 0)
jadmanski6e8bf752008-05-14 00:17:48 +0000338
Luigi Semenzatoe7064812017-02-03 14:47:59 -0800339 parser = parser_lib.parser(status_version)
jadmanski0afbb632008-06-06 21:10:57 +0000340 job = parser.make_job(path)
Prathmesh Prabhue06c49b2018-04-18 19:01:23 -0700341 tko_utils.dprint("+ Parsing dir=%s, jobname=%s" % (path, jobname))
342 status_log_path = _find_status_log_path(path)
343 if not status_log_path:
jadmanski0afbb632008-06-06 21:10:57 +0000344 tko_utils.dprint("! Unable to parse job, no status file")
345 return
Prathmesh Prabhue06c49b2018-04-18 19:01:23 -0700346 _parse_status_log(parser, job, status_log_path)
jadmanski9b6babf2009-04-21 17:57:40 +0000347
Prathmesh Prabhuedac1ee2018-04-18 19:16:34 -0700348 if old_job_idx is not None:
349 job.job_idx = old_job_idx
350 unmatched_tests = _match_existing_tests(db, job)
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700351 if not dry_run:
Prathmesh Prabhuedac1ee2018-04-18 19:16:34 -0700352 _delete_tests_from_db(db, unmatched_tests)
mbligh96cf0512008-04-17 15:25:38 +0000353
Prathmesh Prabhu30dee862018-04-18 20:24:20 -0700354 job.afe_job_id = tko_utils.get_afe_job_id(jobname)
Prathmesh Prabhu17905882018-04-18 22:09:08 -0700355 job.skylab_task_id = tko_utils.get_skylab_task_id(jobname)
Prathmesh Prabhud25f15a2018-05-03 13:49:58 -0700356 job.afe_parent_job_id = job_keyval.get(constants.PARENT_JOB_ID)
357 job.skylab_parent_task_id = job_keyval.get(constants.PARENT_JOB_ID)
Benny Peakefeb775c2017-02-08 15:14:14 -0800358 job.build = None
359 job.board = None
360 job.build_version = None
361 job.suite = None
362 if job.label:
363 label_info = site_utils.parse_job_name(job.label)
364 if label_info:
365 job.build = label_info.get('build', None)
366 job.build_version = label_info.get('build_version', None)
367 job.board = label_info.get('board', None)
368 job.suite = label_info.get('suite', None)
369
Dan Shi4f8c0242017-07-07 15:34:49 -0700370 result_utils_lib.LOG = tko_utils.dprint
371 _throttle_result_size(path)
372
Dan Shiffd5b822017-07-14 11:16:23 -0700373 # Record test result size to job_keyvals
Dan Shi11e35062017-11-03 10:09:05 -0700374 start_time = time.time()
Dan Shiffd5b822017-07-14 11:16:23 -0700375 result_size_info = site_utils.collect_result_sizes(
376 path, log=tko_utils.dprint)
Dan Shi11e35062017-11-03 10:09:05 -0700377 tko_utils.dprint('Finished collecting result sizes after %s seconds' %
378 (time.time()-start_time))
Dan Shiffd5b822017-07-14 11:16:23 -0700379 job.keyval_dict.update(result_size_info.__dict__)
380
Dan Shiffd5b822017-07-14 11:16:23 -0700381 # TODO(dshi): Update sizes with sponge_invocation.xml and throttle it.
Dan Shi96c3bdc2017-05-24 11:34:30 -0700382
jadmanski0afbb632008-06-06 21:10:57 +0000383 # check for failures
384 message_lines = [""]
Simran Basi1e10e922015-04-16 15:09:56 -0700385 job_successful = True
jadmanski0afbb632008-06-06 21:10:57 +0000386 for test in job.tests:
387 if not test.subdir:
388 continue
Sida Liuafe550a2017-09-03 19:03:40 -0700389 tko_utils.dprint("* testname, subdir, status, reason: %s %s %s %s"
390 % (test.testname, test.subdir, test.status,
391 test.reason))
Simran Basi1e10e922015-04-16 15:09:56 -0700392 if test.status != 'GOOD':
393 job_successful = False
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700394 pid_file_manager.num_tests_failed += 1
jadmanski0afbb632008-06-06 21:10:57 +0000395 message_lines.append(format_failure_message(
396 jobname, test.kernel.base, test.subdir,
397 test.status, test.reason))
Simran Basi59ca5ac2016-09-22 16:57:56 -0700398 try:
399 message = "\n".join(message_lines)
Simran Basi1e10e922015-04-16 15:09:56 -0700400
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700401 if not dry_run:
402 # send out a email report of failure
403 if len(message) > 2 and mail_on_failure:
404 tko_utils.dprint("Sending email report of failure on %s to %s"
405 % (jobname, job.user))
406 mailfailure(jobname, job, message)
mbligh96cf0512008-04-17 15:25:38 +0000407
Dan Shie5d063f2017-09-29 15:37:34 -0700408 # Upload perf values to the perf dashboard, if applicable.
409 for test in job.tests:
410 perf_uploader.upload_test(job, test, jobname)
411
412 # Upload job details to Sponge.
413 sponge_url = sponge_utils.upload_results(job, log=tko_utils.dprint)
414 if sponge_url:
415 job.keyval_dict['sponge_url'] = sponge_url
416
Prathmesh Prabhu30dee862018-04-18 20:24:20 -0700417 _write_job_to_db(db, jobname, job)
mbligh96cf0512008-04-17 15:25:38 +0000418
Dan Shib0af6212017-07-17 14:40:02 -0700419 # Verify the job data is written to the database.
420 if job.tests:
Prathmesh Prabhuc2a8a6a2018-04-19 16:23:32 -0700421 tests_in_db = db.find_tests(job.job_idx)
Dan Shib0af6212017-07-17 14:40:02 -0700422 tests_in_db_count = len(tests_in_db) if tests_in_db else 0
423 if tests_in_db_count != len(job.tests):
424 tko_utils.dprint(
425 'Failed to find enough tests for job_idx: %d. The '
426 'job should have %d tests, only found %d tests.' %
Prathmesh Prabhuc2a8a6a2018-04-19 16:23:32 -0700427 (job.job_idx, len(job.tests), tests_in_db_count))
Dan Shib0af6212017-07-17 14:40:02 -0700428 metrics.Counter(
429 'chromeos/autotest/result/db_save_failure',
430 description='The number of times parse failed to '
431 'save job to TKO database.').increment()
432
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700433 # Although the cursor has autocommit, we still need to force it to
434 # commit existing changes before we can use django models, otherwise
435 # it will go into deadlock when django models try to start a new
436 # trasaction while the current one has not finished yet.
437 db.commit()
Dennis Jeffreyf9bef6c2013-08-05 11:01:27 -0700438
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700439 # Handle retry job.
440 orig_afe_job_id = job_keyval.get(constants.RETRY_ORIGINAL_JOB_ID,
441 None)
442 if orig_afe_job_id:
443 orig_job_idx = tko_models.Job.objects.get(
444 afe_job_id=orig_afe_job_id).job_idx
Prathmesh Prabhuc2a8a6a2018-04-19 16:23:32 -0700445 _invalidate_original_tests(orig_job_idx, job.job_idx)
Simran Basi59ca5ac2016-09-22 16:57:56 -0700446 except Exception as e:
Simran Basi59ca5ac2016-09-22 16:57:56 -0700447 tko_utils.dprint("Hit exception while uploading to tko db:\n%s" %
448 traceback.format_exc())
Simran Basi59ca5ac2016-09-22 16:57:56 -0700449 raise e
Fang Deng9ec66802014-04-28 19:04:33 +0000450
jamesren7a522042010-06-10 22:53:55 +0000451 # Serializing job into a binary file
Michael Tangc89efa72017-08-03 14:27:10 -0700452 export_tko_to_file = global_config.global_config.get_config_value(
453 'AUTOSERV', 'export_tko_job_to_file', type=bool, default=False)
Michael Tang8303a372017-08-11 11:03:50 -0700454
455 binary_file_name = os.path.join(path, "job.serialize")
Michael Tangc89efa72017-08-03 14:27:10 -0700456 if export_tko_to_file:
Michael Tangc89efa72017-08-03 14:27:10 -0700457 export_tko_job_to_file(job, jobname, binary_file_name)
jamesren4826cc42010-06-15 20:33:22 +0000458
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700459 if not dry_run:
460 db.commit()
mbligh26b992b2008-02-19 15:46:21 +0000461
Shuqian Zhao31425d52016-12-07 09:35:03 -0800462 # Generate a suite report.
463 # Check whether this is a suite job, a suite job will be a hostless job, its
464 # jobname will be <JOB_ID>-<USERNAME>/hostless, the suite field will not be
Shuqian Zhaoa42bba12017-03-10 14:20:11 -0800465 # NULL. Only generate timeline report when datastore_parent_key is given.
Shuqian Zhao31425d52016-12-07 09:35:03 -0800466 try:
Shuqian Zhaoa42bba12017-03-10 14:20:11 -0800467 datastore_parent_key = job_keyval.get('datastore_parent_key', None)
Ningning Xiabbba11f2018-03-16 13:35:24 -0700468 provision_job_id = job_keyval.get('provision_job_id', None)
Shuqian Zhaoa42bba12017-03-10 14:20:11 -0800469 if (suite_report and jobname.endswith('/hostless')
Prathmesh Prabhu6d4d8b62018-04-18 18:24:54 -0700470 and job.suite and datastore_parent_key):
Shuqian Zhao31425d52016-12-07 09:35:03 -0800471 tko_utils.dprint('Start dumping suite timing report...')
472 timing_log = os.path.join(path, 'suite_timing.log')
473 dump_cmd = ("%s/site_utils/dump_suite_report.py %s "
474 "--output='%s' --debug" %
Prathmesh Prabhu6d4d8b62018-04-18 18:24:54 -0700475 (common.autotest_dir, job.afe_job_id,
Shuqian Zhao31425d52016-12-07 09:35:03 -0800476 timing_log))
Ningning Xiabbba11f2018-03-16 13:35:24 -0700477
478 if provision_job_id is not None:
479 dump_cmd += " --provision_job_id=%d" % int(provision_job_id)
480
Shuqian Zhao31425d52016-12-07 09:35:03 -0800481 subprocess.check_output(dump_cmd, shell=True)
482 tko_utils.dprint('Successfully finish dumping suite timing report')
483
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800484 if (datastore_creds and export_to_gcloud_path
485 and os.path.exists(export_to_gcloud_path)):
Shuqian Zhaoa42bba12017-03-10 14:20:11 -0800486 upload_cmd = [export_to_gcloud_path, datastore_creds,
487 timing_log, '--parent_key',
Shuqian Zhao4ff74732017-03-30 16:20:10 -0700488 datastore_parent_key]
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800489 tko_utils.dprint('Start exporting timeline report to gcloud')
Shuqian Zhaoa42bba12017-03-10 14:20:11 -0800490 subprocess.check_output(upload_cmd)
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800491 tko_utils.dprint('Successfully export timeline report to '
492 'gcloud')
493 else:
494 tko_utils.dprint('DEBUG: skip exporting suite timeline to '
495 'gcloud, because either gcloud creds or '
496 'export_to_gcloud script is not found.')
Shuqian Zhao31425d52016-12-07 09:35:03 -0800497 except Exception as e:
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800498 tko_utils.dprint("WARNING: fail to dump/export suite report. "
499 "Error:\n%s" % e)
Shuqian Zhao31425d52016-12-07 09:35:03 -0800500
Dan Shi5f626332016-01-27 15:25:58 -0800501 # Mark GS_OFFLOADER_NO_OFFLOAD in gs_offloader_instructions at the end of
502 # the function, so any failure, e.g., db connection error, will stop
503 # gs_offloader_instructions being updated, and logs can be uploaded for
504 # troubleshooting.
505 if job_successful:
506 # Check if we should not offload this test's results.
507 if job_keyval.get(constants.JOB_OFFLOAD_FAILURES_KEY, False):
508 # Update the gs_offloader_instructions json file.
509 gs_instructions_file = os.path.join(
510 path, constants.GS_OFFLOADER_INSTRUCTIONS)
511 gs_offloader_instructions = {}
512 if os.path.exists(gs_instructions_file):
513 with open(gs_instructions_file, 'r') as f:
514 gs_offloader_instructions = json.load(f)
515
516 gs_offloader_instructions[constants.GS_OFFLOADER_NO_OFFLOAD] = True
517 with open(gs_instructions_file, 'w') as f:
518 json.dump(gs_offloader_instructions, f)
519
520
Prathmesh Prabhu30dee862018-04-18 20:24:20 -0700521def _write_job_to_db(db, jobname, job):
Prathmesh Prabhu8957a342018-04-18 18:29:09 -0700522 """Write all TKO data associated with a job to DB.
523
524 This updates the job object as a side effect.
525
526 @param db: tko.db.db_sql object.
527 @param jobname: Name of the job to write.
528 @param job: tko.models.job object.
529 """
530 db.insert_or_update_machine(job)
Prathmesh Prabhu30dee862018-04-18 20:24:20 -0700531 db.insert_job(jobname, job)
Prathmesh Prabhu17905882018-04-18 22:09:08 -0700532 db.insert_or_update_task_reference(
533 job,
534 'skylab' if tko_utils.is_skylab_task(jobname) else 'afe',
535 )
Prathmesh Prabhu8957a342018-04-18 18:29:09 -0700536 db.update_job_keyvals(job)
537 for test in job.tests:
538 db.insert_test(job, test)
539
540
Prathmesh Prabhu42a2bb42018-04-18 18:56:16 -0700541def _find_status_log_path(path):
542 if os.path.exists(os.path.join(path, "status.log")):
543 return os.path.join(path, "status.log")
544 if os.path.exists(os.path.join(path, "status")):
545 return os.path.join(path, "status")
546 return ""
547
548
Prathmesh Prabhue06c49b2018-04-18 19:01:23 -0700549def _parse_status_log(parser, job, status_log_path):
550 status_lines = open(status_log_path).readlines()
551 parser.start(job)
552 tests = parser.end(status_lines)
553
554 # parser.end can return the same object multiple times, so filter out dups
555 job.tests = []
556 already_added = set()
557 for test in tests:
558 if test not in already_added:
559 already_added.add(test)
560 job.tests.append(test)
561
562
Prathmesh Prabhuedac1ee2018-04-18 19:16:34 -0700563def _match_existing_tests(db, job):
564 """Find entries in the DB corresponding to the job's tests, update job.
565
566 @return: Any unmatched tests in the db.
567 """
568 old_job_idx = job.job_idx
569 raw_old_tests = db.select("test_idx,subdir,test", "tko_tests",
570 {"job_idx": old_job_idx})
571 if raw_old_tests:
572 old_tests = dict(((test, subdir), test_idx)
573 for test_idx, subdir, test in raw_old_tests)
574 else:
575 old_tests = {}
576
577 for test in job.tests:
578 test_idx = old_tests.pop((test.testname, test.subdir), None)
579 if test_idx is not None:
580 test.test_idx = test_idx
581 else:
582 tko_utils.dprint("! Reparse returned new test "
583 "testname=%r subdir=%r" %
584 (test.testname, test.subdir))
585 return old_tests
586
587
588def _delete_tests_from_db(db, tests):
589 for test_idx in tests.itervalues():
590 where = {'test_idx' : test_idx}
591 db.delete('tko_iteration_result', where)
592 db.delete('tko_iteration_perf_value', where)
593 db.delete('tko_iteration_attributes', where)
594 db.delete('tko_test_attributes', where)
595 db.delete('tko_test_labels_tests', {'test_id': test_idx})
596 db.delete('tko_tests', where)
597
598
jadmanski8e9c2572008-11-11 00:29:02 +0000599def _get_job_subdirs(path):
600 """
601 Returns a list of job subdirectories at path. Returns None if the test
602 is itself a job directory. Does not recurse into the subdirs.
603 """
604 # if there's a .machines file, use it to get the subdirs
jadmanski0afbb632008-06-06 21:10:57 +0000605 machine_list = os.path.join(path, ".machines")
606 if os.path.exists(machine_list):
jadmanski42fbd072009-01-30 15:07:05 +0000607 subdirs = set(line.strip() for line in file(machine_list))
608 existing_subdirs = set(subdir for subdir in subdirs
609 if os.path.exists(os.path.join(path, subdir)))
610 if len(existing_subdirs) != 0:
611 return existing_subdirs
jadmanski8e9c2572008-11-11 00:29:02 +0000612
613 # if this dir contains ONLY subdirectories, return them
614 contents = set(os.listdir(path))
615 contents.discard(".parse.lock")
616 subdirs = set(sub for sub in contents if
617 os.path.isdir(os.path.join(path, sub)))
618 if len(contents) == len(subdirs) != 0:
619 return subdirs
620
621 # this is a job directory, or something else we don't understand
622 return None
623
624
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700625def parse_leaf_path(db, pid_file_manager, path, level, parse_options):
Fang Deng49822682014-10-21 16:29:22 -0700626 """Parse a leaf path.
627
628 @param db: database handle.
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700629 @param pid_file_manager: pidfile.PidFileManager object.
Fang Deng49822682014-10-21 16:29:22 -0700630 @param path: The path to the results to be parsed.
631 @param level: Integer, level of subdirectories to include in the job name.
Aviv Keshet687d2dc2016-10-20 15:41:16 -0700632 @param parse_options: _ParseOptions instance.
Fang Deng49822682014-10-21 16:29:22 -0700633
634 @returns: The job name of the parsed job, e.g. '123-chromeos-test/host1'
635 """
mbligha48eeb22009-03-11 16:44:43 +0000636 job_elements = path.split("/")[-level:]
637 jobname = "/".join(job_elements)
638 try:
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700639 db.run_with_retry(parse_one, db, pid_file_manager, jobname, path,
640 parse_options)
Simran Basi8de306c2016-12-21 12:04:21 -0800641 except Exception as e:
642 tko_utils.dprint("Error parsing leaf path: %s\nException:\n%s\n%s" %
643 (path, e, traceback.format_exc()))
Fang Deng49822682014-10-21 16:29:22 -0700644 return jobname
mbligha48eeb22009-03-11 16:44:43 +0000645
646
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700647def parse_path(db, pid_file_manager, path, level, parse_options):
Fang Deng49822682014-10-21 16:29:22 -0700648 """Parse a path
649
650 @param db: database handle.
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700651 @param pid_file_manager: pidfile.PidFileManager object.
Fang Deng49822682014-10-21 16:29:22 -0700652 @param path: The path to the results to be parsed.
653 @param level: Integer, level of subdirectories to include in the job name.
Aviv Keshet687d2dc2016-10-20 15:41:16 -0700654 @param parse_options: _ParseOptions instance.
Fang Deng49822682014-10-21 16:29:22 -0700655
656 @returns: A set of job names of the parsed jobs.
657 set(['123-chromeos-test/host1', '123-chromeos-test/host2'])
658 """
659 processed_jobs = set()
jadmanski8e9c2572008-11-11 00:29:02 +0000660 job_subdirs = _get_job_subdirs(path)
661 if job_subdirs is not None:
mbligha48eeb22009-03-11 16:44:43 +0000662 # parse status.log in current directory, if it exists. multi-machine
663 # synchronous server side tests record output in this directory. without
664 # this check, we do not parse these results.
665 if os.path.exists(os.path.join(path, 'status.log')):
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700666 new_job = parse_leaf_path(db, pid_file_manager, path, level,
667 parse_options)
Fang Deng49822682014-10-21 16:29:22 -0700668 processed_jobs.add(new_job)
jadmanski0afbb632008-06-06 21:10:57 +0000669 # multi-machine job
jadmanski8e9c2572008-11-11 00:29:02 +0000670 for subdir in job_subdirs:
671 jobpath = os.path.join(path, subdir)
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700672 new_jobs = parse_path(db, pid_file_manager, jobpath, level + 1,
673 parse_options)
Fang Deng49822682014-10-21 16:29:22 -0700674 processed_jobs.update(new_jobs)
jadmanski0afbb632008-06-06 21:10:57 +0000675 else:
676 # single machine job
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700677 new_job = parse_leaf_path(db, pid_file_manager, path, level,
678 parse_options)
Fang Deng49822682014-10-21 16:29:22 -0700679 processed_jobs.add(new_job)
680 return processed_jobs
681
682
Prathmesh Prabhu3e319da2017-08-30 19:13:03 -0700683def _detach_from_parent_process():
684 """Allow reparenting the parse process away from caller.
685
686 When monitor_db is run via upstart, restarting the job sends SIGTERM to
687 the whole process group. This makes us immune from that.
688 """
689 if os.getpid() != os.getpgid(0):
690 os.setsid()
mblighbb7b8912006-10-08 03:59:02 +0000691
Aviv Keshet6469b532018-07-17 16:44:39 -0700692
mbligh96cf0512008-04-17 15:25:38 +0000693def main():
Aviv Keshet6469b532018-07-17 16:44:39 -0700694 """tko_parse entry point."""
695 options, args = parse_args()
696
697 # We are obliged to use indirect=False, not use the SetupTsMonGlobalState
698 # context manager, and add a manual flush, because tko/parse is expected to
699 # be a very short lived (<1 min) script when working effectively, and we
700 # can't afford to either a) wait for up to 1min for metrics to flush at the
701 # end or b) drop metrics that were sent within the last minute of execution.
702 site_utils.SetupTsMonGlobalState('tko_parse', indirect=False,
703 short_lived=True)
704 try:
705 with metrics.SuccessCounter('chromeos/autotest/tko_parse/runs'):
706 _main_with_options(options, args)
707 finally:
708 metrics.Flush()
709
710
711def _main_with_options(options, args):
712 """Entry point with options parsed and metrics already set up."""
Fang Deng49822682014-10-21 16:29:22 -0700713 start_time = datetime.datetime.now()
714 # Record the processed jobs so that
715 # we can send the duration of parsing to metadata db.
716 processed_jobs = set()
717
Prathmesh Prabhu3e319da2017-08-30 19:13:03 -0700718 if options.detach:
719 _detach_from_parent_process()
720
Aviv Keshet0b7bab02016-10-20 17:17:36 -0700721 parse_options = _ParseOptions(options.reparse, options.mailit,
Shuqian Zhao19e62fb2017-01-09 10:10:14 -0800722 options.dry_run, options.suite_report,
723 options.datastore_creds,
724 options.export_to_gcloud_path)
jadmanski0afbb632008-06-06 21:10:57 +0000725 results_dir = os.path.abspath(args[0])
726 assert os.path.exists(results_dir)
mbligh96cf0512008-04-17 15:25:38 +0000727
jadmanskid5ab8c52008-12-03 16:27:07 +0000728 pid_file_manager = pidfile.PidFileManager("parser", results_dir)
mbligh96cf0512008-04-17 15:25:38 +0000729
jadmanskid5ab8c52008-12-03 16:27:07 +0000730 if options.write_pidfile:
731 pid_file_manager.open_file()
mbligh96cf0512008-04-17 15:25:38 +0000732
jadmanskid5ab8c52008-12-03 16:27:07 +0000733 try:
734 # build up the list of job dirs to parse
735 if options.singledir:
736 jobs_list = [results_dir]
737 else:
738 jobs_list = [os.path.join(results_dir, subdir)
739 for subdir in os.listdir(results_dir)]
740
741 # build up the database
742 db = tko_db.db(autocommit=False, host=options.db_host,
743 user=options.db_user, password=options.db_pass,
744 database=options.db_name)
745
746 # parse all the jobs
747 for path in jobs_list:
748 lockfile = open(os.path.join(path, ".parse.lock"), "w")
749 flags = fcntl.LOCK_EX
750 if options.noblock:
mblighdb18b0e2009-01-30 00:34:32 +0000751 flags |= fcntl.LOCK_NB
jadmanskid5ab8c52008-12-03 16:27:07 +0000752 try:
753 fcntl.flock(lockfile, flags)
754 except IOError, e:
mblighdb18b0e2009-01-30 00:34:32 +0000755 # lock is not available and nonblock has been requested
jadmanskid5ab8c52008-12-03 16:27:07 +0000756 if e.errno == errno.EWOULDBLOCK:
757 lockfile.close()
758 continue
759 else:
760 raise # something unexpected happened
761 try:
Prathmesh Prabhub1241d12018-04-19 18:09:43 -0700762 new_jobs = parse_path(db, pid_file_manager, path, options.level,
763 parse_options)
Fang Deng49822682014-10-21 16:29:22 -0700764 processed_jobs.update(new_jobs)
mbligh9e936402009-05-13 20:42:17 +0000765
jadmanskid5ab8c52008-12-03 16:27:07 +0000766 finally:
767 fcntl.flock(lockfile, fcntl.LOCK_UN)
jadmanski0afbb632008-06-06 21:10:57 +0000768 lockfile.close()
mblighe97e0e62009-05-21 01:41:58 +0000769
Dan Shib7a36ea2017-02-28 21:52:20 -0800770 except Exception as e:
jadmanskid5ab8c52008-12-03 16:27:07 +0000771 pid_file_manager.close_file(1)
772 raise
773 else:
774 pid_file_manager.close_file(0)
Fang Deng49822682014-10-21 16:29:22 -0700775 duration_secs = (datetime.datetime.now() - start_time).total_seconds()
mbligh71d340d2008-03-05 15:51:16 +0000776
mbligh532cb272007-11-26 18:54:20 +0000777
mbligh96cf0512008-04-17 15:25:38 +0000778if __name__ == "__main__":
Aviv Keshet6469b532018-07-17 16:44:39 -0700779 main()