Collect metrics from inside soong_build

Collect the number of modules and variants and some basic statistics
on memory usage inside soong_build by writing out a proto that is
read back in by soong_ui.

Test: examine soong.log
Change-Id: I6926876377a4f6229cf41fdbf166ae03c885ea55
diff --git a/ui/build/soong.go b/ui/build/soong.go
index afbc073..9b8d648 100644
--- a/ui/build/soong.go
+++ b/ui/build/soong.go
@@ -15,11 +15,15 @@
 package build
 
 import (
+	"io/ioutil"
 	"os"
 	"path/filepath"
 	"strconv"
 	"strings"
 
+	soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
+
+	"github.com/golang/protobuf/proto"
 	"github.com/google/blueprint/microfactory"
 
 	"android/soong/ui/metrics"
@@ -126,4 +130,35 @@
 
 	ninja("minibootstrap", ".minibootstrap/build.ninja")
 	ninja("bootstrap", ".bootstrap/build.ninja")
+
+	soongBuildMetrics := loadSoongBuildMetrics(ctx, config)
+	logSoongBuildMetrics(ctx, soongBuildMetrics)
+
+	if ctx.Metrics != nil {
+		ctx.Metrics.SetSoongBuildMetrics(soongBuildMetrics)
+	}
+}
+
+func loadSoongBuildMetrics(ctx Context, config Config) *soong_metrics_proto.SoongBuildMetrics {
+	soongBuildMetricsFile := filepath.Join(config.OutDir(), "soong", "soong_build_metrics.pb")
+	buf, err := ioutil.ReadFile(soongBuildMetricsFile)
+	if err != nil {
+		ctx.Fatalf("Failed to load %s: %s", soongBuildMetricsFile, err)
+	}
+	soongBuildMetrics := &soong_metrics_proto.SoongBuildMetrics{}
+	err = proto.Unmarshal(buf, soongBuildMetrics)
+	if err != nil {
+		ctx.Fatalf("Failed to unmarshal %s: %s", soongBuildMetricsFile, err)
+	}
+	return soongBuildMetrics
+}
+
+func logSoongBuildMetrics(ctx Context, metrics *soong_metrics_proto.SoongBuildMetrics) {
+	ctx.Verbosef("soong_build metrics:")
+	ctx.Verbosef(" modules: %v", metrics.GetModules())
+	ctx.Verbosef(" variants: %v", metrics.GetVariants())
+	ctx.Verbosef(" max heap size: %v MB", metrics.GetMaxHeapSize()/1e6)
+	ctx.Verbosef(" total allocation count: %v", metrics.GetTotalAllocCount())
+	ctx.Verbosef(" total allocation size: %v MB", metrics.GetTotalAllocSize()/1e6)
+
 }