autotest: Hoist tko_jobs related updates out of insert_job

BUG=chromium:833988
TEST=None

Change-Id: I63cc1e279d9ad47457c940b330a8a6141f634b3e
Reviewed-on: https://chromium-review.googlesource.com/1018581
Commit-Ready: Prathmesh Prabhu <pprabhu@chromium.org>
Tested-by: Prathmesh Prabhu <pprabhu@chromium.org>
Reviewed-by: Prathmesh Prabhu <pprabhu@chromium.org>
Reviewed-by: Xixuan Wu <xixuan@chromium.org>
diff --git a/tko/db.py b/tko/db.py
index d59ba51..b682abe 100644
--- a/tko/db.py
+++ b/tko/db.py
@@ -443,7 +443,6 @@
 
         @return The dict of data inserted into the tko_jobs table.
         """
-        self.insert_or_update_machine(job, commit)
         afe_job_id = utils.get_afe_job_id(tag)
 
         data = {'tag':tag,
@@ -470,10 +469,6 @@
         else:
             self.insert('tko_jobs', data, commit=commit)
             job.index = self.get_last_autonumber_value()
-        self.update_job_keyvals(job, commit=commit)
-        for test in job.tests:
-            self.insert_test(job, test, commit=commit)
-
         data['job_idx'] = job.index
         return data
 
diff --git a/tko/parse.py b/tko/parse.py
index 7d4f9e2..993d149 100755
--- a/tko/parse.py
+++ b/tko/parse.py
@@ -444,9 +444,13 @@
                 job.keyval_dict['sponge_url'] = sponge_url
 
             # write the job into the database.
+            db.insert_or_update_machine(job)
             job_data = db.insert_job(
                 jobname, job,
                 parent_job_id=job_keyval.get(constants.PARENT_JOB_ID, None))
+            db.update_job_keyvals(job)
+            for test in job.tests:
+                db.insert_test(job, test)
 
             # Verify the job data is written to the database.
             if job.tests: