metrics: Wait until upload is complete on bots.

Otherwise, when the step completes, it won't be able to close
files used for stdout/stderr, since the metrics process is still
running.

Bug: 1206429
Change-Id: Id88578cbd9dab070e07f92e545ec137245566d16
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2877608
Auto-Submit: Edward Lesmes <ehmaldonado@chromium.org>
Commit-Queue: Jamie Madill <jmadill@chromium.org>
Reviewed-by: Jamie Madill <jmadill@chromium.org>
diff --git a/metrics.py b/metrics.py
index 902a228..5e3a935 100644
--- a/metrics.py
+++ b/metrics.py
@@ -203,11 +203,14 @@
 
   def _upload_metrics_data(self):
     """Upload the metrics data to the AppEngine app."""
+    p = subprocess2.Popen(['vpython3', UPLOAD_SCRIPT], stdin=subprocess2.PIPE)
     # We invoke a subprocess, and use stdin.write instead of communicate(),
     # so that we are able to return immediately, leaving the upload running in
     # the background.
-    p = subprocess2.Popen(['vpython3', UPLOAD_SCRIPT], stdin=subprocess2.PIPE)
     p.stdin.write(json.dumps(self._reported_metrics).encode('utf-8'))
+    # ... but if we're running on a bot, wait until upload has completed.
+    if metrics_utils.REPORT_BUILD:
+      p.communicate()
 
   def _collect_metrics(self, func, command_name, *args, **kwargs):
     # If we're already collecting metrics, just execute the function.