• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package android
16
17import (
18	"io/ioutil"
19	"runtime"
20
21	"github.com/golang/protobuf/proto"
22
23	soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
24)
25
26var soongMetricsOnceKey = NewOnceKey("soong metrics")
27
28type SoongMetrics struct {
29	Modules  int
30	Variants int
31}
32
33func ReadSoongMetrics(config Config) SoongMetrics {
34	return config.Get(soongMetricsOnceKey).(SoongMetrics)
35}
36
37func init() {
38	RegisterSingletonType("soong_metrics", soongMetricsSingletonFactory)
39}
40
41func soongMetricsSingletonFactory() Singleton { return soongMetricsSingleton{} }
42
43type soongMetricsSingleton struct{}
44
45func (soongMetricsSingleton) GenerateBuildActions(ctx SingletonContext) {
46	metrics := SoongMetrics{}
47	ctx.VisitAllModules(func(m Module) {
48		if ctx.PrimaryModule(m) == m {
49			metrics.Modules++
50		}
51		metrics.Variants++
52	})
53	ctx.Config().Once(soongMetricsOnceKey, func() interface{} {
54		return metrics
55	})
56}
57
58func collectMetrics(config Config) *soong_metrics_proto.SoongBuildMetrics {
59	metrics := &soong_metrics_proto.SoongBuildMetrics{}
60
61	soongMetrics := ReadSoongMetrics(config)
62	metrics.Modules = proto.Uint32(uint32(soongMetrics.Modules))
63	metrics.Variants = proto.Uint32(uint32(soongMetrics.Variants))
64
65	memStats := runtime.MemStats{}
66	runtime.ReadMemStats(&memStats)
67	metrics.MaxHeapSize = proto.Uint64(memStats.HeapSys)
68	metrics.TotalAllocCount = proto.Uint64(memStats.Mallocs)
69	metrics.TotalAllocSize = proto.Uint64(memStats.TotalAlloc)
70
71	return metrics
72}
73
74func WriteMetrics(config Config, metricsFile string) error {
75	metrics := collectMetrics(config)
76
77	buf, err := proto.Marshal(metrics)
78	if err != nil {
79		return err
80	}
81	err = ioutil.WriteFile(absolutePath(metricsFile), buf, 0666)
82	if err != nil {
83		return err
84	}
85
86	return nil
87}
88