lab_inventory: Flush metrics even in case of errors

This ensures that we will not drop metrics on the floor when exceptions
happen.

BUG=chromium:835941
TEST=None

Change-Id: Icbcb5e52e48b3eed4e5122906aab3772b844932f
Reviewed-on: https://chromium-review.googlesource.com/1048607
Commit-Ready: Prathmesh Prabhu <pprabhu@chromium.org>
Tested-by: Prathmesh Prabhu <pprabhu@chromium.org>
Reviewed-by: Richard Barnette <jrbarnette@google.com>
diff --git a/site_utils/lab_inventory.py b/site_utils/lab_inventory.py
index 8060435..58b50b9 100755
--- a/site_utils/lab_inventory.py
+++ b/site_utils/lab_inventory.py
@@ -1322,18 +1322,19 @@
     else:
         metrics_file = None
 
-    try:
-        with site_utils.SetupTsMonGlobalState(
-                'lab_inventory', debug_file=metrics_file,
-                auto_flush=False):
+    with site_utils.SetupTsMonGlobalState(
+            'lab_inventory', debug_file=metrics_file,
+            auto_flush=False):
+        try:
             _perform_inventory_reports(arguments)
-        metrics.Flush()
-    except KeyboardInterrupt:
-        pass
-    except (EnvironmentError, Exception):
-        # Our cron setup doesn't preserve stderr, so drop extra breadcrumbs.
-        logging.exception('Error escaped main')
-        raise
+        except KeyboardInterrupt:
+            pass
+        except (EnvironmentError, Exception):
+            # Our cron setup doesn't preserve stderr, so drop extra breadcrumbs.
+            logging.exception('Error escaped main')
+            raise
+        finally:
+            metrics.Flush()
 
 
 def get_inventory(afe):