blob: 6834b1bde1a01fbe72c7fe5ac324fe819d279b94 [file] [log] [blame]
Colin Crossb72c9092020-02-10 11:23:49 -08001// 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 (
Colin Cross46b0c752023-10-27 14:56:12 -070018 "bytes"
Colin Crossb72c9092020-02-10 11:23:49 -080019 "io/ioutil"
Colin Cross46b0c752023-10-27 14:56:12 -070020 "os"
Colin Crossb72c9092020-02-10 11:23:49 -080021 "runtime"
Colin Cross46b0c752023-10-27 14:56:12 -070022 "strconv"
23 "time"
Colin Crossb72c9092020-02-10 11:23:49 -080024
Chris Parsons715b08f2022-03-22 19:23:40 -040025 "github.com/google/blueprint/metrics"
Dan Willemsen4591b642021-05-24 14:24:12 -070026 "google.golang.org/protobuf/proto"
Colin Crossb72c9092020-02-10 11:23:49 -080027
28 soong_metrics_proto "android/soong/ui/metrics/metrics_proto"
29)
30
31var soongMetricsOnceKey = NewOnceKey("soong metrics")
32
Colin Cross46b0c752023-10-27 14:56:12 -070033type soongMetrics struct {
34 modules int
35 variants int
36 perfCollector perfCollector
Colin Crossb72c9092020-02-10 11:23:49 -080037}
38
Colin Cross46b0c752023-10-27 14:56:12 -070039type perfCollector struct {
40 events []*soong_metrics_proto.PerfCounters
41 stop chan<- bool
42}
43
44func getSoongMetrics(config Config) *soongMetrics {
45 return config.Once(soongMetricsOnceKey, func() interface{} {
46 return &soongMetrics{}
47 }).(*soongMetrics)
Colin Crossb72c9092020-02-10 11:23:49 -080048}
49
50func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000051 RegisterParallelSingletonType("soong_metrics", soongMetricsSingletonFactory)
Colin Crossb72c9092020-02-10 11:23:49 -080052}
53
54func soongMetricsSingletonFactory() Singleton { return soongMetricsSingleton{} }
55
56type soongMetricsSingleton struct{}
57
58func (soongMetricsSingleton) GenerateBuildActions(ctx SingletonContext) {
Colin Cross46b0c752023-10-27 14:56:12 -070059 metrics := getSoongMetrics(ctx.Config())
Colin Crossb72c9092020-02-10 11:23:49 -080060 ctx.VisitAllModules(func(m Module) {
61 if ctx.PrimaryModule(m) == m {
Colin Cross46b0c752023-10-27 14:56:12 -070062 metrics.modules++
Colin Crossb72c9092020-02-10 11:23:49 -080063 }
Colin Cross46b0c752023-10-27 14:56:12 -070064 metrics.variants++
Colin Crossb72c9092020-02-10 11:23:49 -080065 })
66}
67
Paul Duffin780a1852022-11-05 10:17:12 +000068func collectMetrics(config Config, eventHandler *metrics.EventHandler) *soong_metrics_proto.SoongBuildMetrics {
Colin Crossb72c9092020-02-10 11:23:49 -080069 metrics := &soong_metrics_proto.SoongBuildMetrics{}
70
Colin Cross46b0c752023-10-27 14:56:12 -070071 soongMetrics := getSoongMetrics(config)
72 if soongMetrics.modules > 0 {
73 metrics.Modules = proto.Uint32(uint32(soongMetrics.modules))
74 metrics.Variants = proto.Uint32(uint32(soongMetrics.variants))
Joe Onorato2e5e4012022-06-07 17:16:08 -070075 }
Colin Crossb72c9092020-02-10 11:23:49 -080076
Colin Cross46b0c752023-10-27 14:56:12 -070077 soongMetrics.perfCollector.stop <- true
78 metrics.PerfCounters = soongMetrics.perfCollector.events
79
Colin Crossb72c9092020-02-10 11:23:49 -080080 memStats := runtime.MemStats{}
81 runtime.ReadMemStats(&memStats)
82 metrics.MaxHeapSize = proto.Uint64(memStats.HeapSys)
83 metrics.TotalAllocCount = proto.Uint64(memStats.Mallocs)
84 metrics.TotalAllocSize = proto.Uint64(memStats.TotalAlloc)
85
Chris Parsons715b08f2022-03-22 19:23:40 -040086 for _, event := range eventHandler.CompletedEvents() {
87 perfInfo := soong_metrics_proto.PerfInfo{
88 Description: proto.String(event.Id),
89 Name: proto.String("soong_build"),
90 StartTime: proto.Uint64(uint64(event.Start.UnixNano())),
91 RealTime: proto.Uint64(event.RuntimeNanoseconds()),
92 }
93 metrics.Events = append(metrics.Events, &perfInfo)
94 }
95
Colin Crossb72c9092020-02-10 11:23:49 -080096 return metrics
97}
98
Colin Cross46b0c752023-10-27 14:56:12 -070099func StartBackgroundMetrics(config Config) {
100 perfCollector := &getSoongMetrics(config).perfCollector
101 stop := make(chan bool)
102 perfCollector.stop = stop
103
104 previousTime := time.Now()
105 previousCpuTime := readCpuTime()
106
107 ticker := time.NewTicker(time.Second)
108
109 go func() {
110 for {
111 select {
112 case <-stop:
113 ticker.Stop()
114 return
115 case <-ticker.C:
116 // carry on
117 }
118
119 currentTime := time.Now()
120
121 var memStats runtime.MemStats
122 runtime.ReadMemStats(&memStats)
123
124 currentCpuTime := readCpuTime()
125
126 interval := currentTime.Sub(previousTime)
127 intervalCpuTime := currentCpuTime - previousCpuTime
128 intervalCpuPercent := intervalCpuTime * 100 / interval
129
130 // heapAlloc is the memory that has been allocated on the heap but not yet GC'd. It may be referenced,
131 // or unrefenced but not yet GC'd.
132 heapAlloc := memStats.HeapAlloc
133 // heapUnused is the memory that was previously used by the heap, but is currently not used. It does not
134 // count memory that was used and then returned to the OS.
135 heapUnused := memStats.HeapIdle - memStats.HeapReleased
136 // heapOverhead is the memory used by the allocator and GC
137 heapOverhead := memStats.MSpanSys + memStats.MCacheSys + memStats.GCSys
138 // otherMem is the memory used outside of the heap.
139 otherMem := memStats.Sys - memStats.HeapSys - heapOverhead
140
141 perfCollector.events = append(perfCollector.events, &soong_metrics_proto.PerfCounters{
142 Time: proto.Uint64(uint64(currentTime.UnixNano())),
143 Groups: []*soong_metrics_proto.PerfCounterGroup{
144 {
145 Name: proto.String("cpu"),
146 Counters: []*soong_metrics_proto.PerfCounter{
147 {Name: proto.String("cpu_percent"), Value: proto.Int64(int64(intervalCpuPercent))},
148 },
149 }, {
150 Name: proto.String("memory"),
151 Counters: []*soong_metrics_proto.PerfCounter{
152 {Name: proto.String("heap_alloc"), Value: proto.Int64(int64(heapAlloc))},
153 {Name: proto.String("heap_unused"), Value: proto.Int64(int64(heapUnused))},
154 {Name: proto.String("heap_overhead"), Value: proto.Int64(int64(heapOverhead))},
155 {Name: proto.String("other"), Value: proto.Int64(int64(otherMem))},
156 },
157 },
158 },
159 })
160
161 previousTime = currentTime
162 previousCpuTime = currentCpuTime
163 }
164 }()
165}
166
167func readCpuTime() time.Duration {
168 if runtime.GOOS != "linux" {
169 return 0
170 }
171
172 stat, err := os.ReadFile("/proc/self/stat")
173 if err != nil {
174 return 0
175 }
176
177 endOfComm := bytes.LastIndexByte(stat, ')')
178 if endOfComm < 0 || endOfComm > len(stat)-2 {
179 return 0
180 }
181
182 stat = stat[endOfComm+2:]
183
184 statFields := bytes.Split(stat, []byte{' '})
185 // This should come from sysconf(_SC_CLK_TCK), but there's no way to call that from Go. Assume it's 100,
186 // which is the value for all platforms we support.
187 const HZ = 100
188 const MS_PER_HZ = 1e3 / HZ * time.Millisecond
189
190 const STAT_UTIME_FIELD = 14 - 2
191 const STAT_STIME_FIELD = 15 - 2
192 if len(statFields) < STAT_STIME_FIELD {
193 return 0
194 }
195 userCpuTicks, err := strconv.ParseUint(string(statFields[STAT_UTIME_FIELD]), 10, 64)
196 if err != nil {
197 return 0
198 }
199 kernelCpuTicks, _ := strconv.ParseUint(string(statFields[STAT_STIME_FIELD]), 10, 64)
200 if err != nil {
201 return 0
202 }
203 return time.Duration(userCpuTicks+kernelCpuTicks) * MS_PER_HZ
204}
205
Paul Duffin780a1852022-11-05 10:17:12 +0000206func WriteMetrics(config Config, eventHandler *metrics.EventHandler, metricsFile string) error {
Chris Parsons715b08f2022-03-22 19:23:40 -0400207 metrics := collectMetrics(config, eventHandler)
Colin Crossb72c9092020-02-10 11:23:49 -0800208
209 buf, err := proto.Marshal(metrics)
210 if err != nil {
211 return err
212 }
213 err = ioutil.WriteFile(absolutePath(metricsFile), buf, 0666)
214 if err != nil {
215 return err
216 }
217
218 return nil
219}