blob: fa63b465dd536ca768514d004ace7c2965ae49cf [file] [log] [blame]
Dan Willemsenc2af0be2017-01-20 14:10:01 -08001// Copyright 2017 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 main
16
17import (
Lukacs T. Berkicef87b62021-08-10 15:01:13 +020018 "bufio"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080019 "context"
20 "flag"
21 "fmt"
Dan Willemsen41538382018-08-31 19:51:35 -070022 "io"
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +020023 "io/ioutil"
Lukacs T. Berkicef87b62021-08-10 15:01:13 +020024 "log"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080025 "os"
Lukacs T. Berkicef87b62021-08-10 15:01:13 +020026 "os/exec"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080027 "path/filepath"
Lukacs T. Berki2c405692021-08-11 09:19:27 +020028 "regexp"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080029 "runtime"
30 "strings"
31 "sync"
Dan Willemsen22de2162017-12-11 14:35:23 -080032 "syscall"
Steven Moreland552432e2017-03-29 19:26:09 -070033 "time"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080034
Dan Willemsenc2af0be2017-01-20 14:10:01 -080035 "android/soong/ui/logger"
Lukacs T. Berkif656b842021-08-11 11:10:28 +020036 "android/soong/ui/signal"
Dan Willemsenb82471a2018-05-17 16:37:09 -070037 "android/soong/ui/status"
38 "android/soong/ui/terminal"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070039 "android/soong/ui/tracer"
Dan Willemsene3480762017-11-07 11:23:27 -080040 "android/soong/zip"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080041)
42
Dan Willemsen1bdbdec2019-12-27 09:54:11 -080043var numJobs = flag.Int("j", 0, "number of parallel jobs [0=autodetect]")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080044
Dan Willemsene3480762017-11-07 11:23:27 -080045var keepArtifacts = flag.Bool("keep", false, "keep archives of artifacts")
Dan Willemsen41538382018-08-31 19:51:35 -070046var incremental = flag.Bool("incremental", false, "run in incremental mode (saving intermediates)")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080047
48var outDir = flag.String("out", "", "path to store output directories (defaults to tmpdir under $OUT when empty)")
Dan Willemsenf624fb92017-05-19 16:39:04 -070049var alternateResultDir = flag.Bool("dist", false, "write select results to $DIST_DIR (or <out>/dist when empty)")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080050
51var onlyConfig = flag.Bool("only-config", false, "Only run product config (not Soong or Kati)")
52var onlySoong = flag.Bool("only-soong", false, "Only run product config and Soong (not Kati)")
53
Dan Willemsen5ed900b2017-05-07 11:40:30 -070054var buildVariant = flag.String("variant", "eng", "build variant to use")
55
Dan Willemsen9609ad92019-12-05 15:22:41 -080056var shardCount = flag.Int("shard-count", 1, "split the products into multiple shards (to spread the build onto multiple machines, etc)")
57var shard = flag.Int("shard", 1, "1-indexed shard to execute")
58
Colin Crossf2f3d312020-12-17 11:29:31 -080059var skipProducts multipleStringArg
60var includeProducts multipleStringArg
61
62func init() {
63 flag.Var(&skipProducts, "skip-products", "comma-separated list of products to skip (known failures, etc)")
64 flag.Var(&includeProducts, "products", "comma-separated list of products to build")
65}
66
67// multipleStringArg is a flag.Value that takes comma separated lists and converts them to a
68// []string. The argument can be passed multiple times to append more values.
69type multipleStringArg []string
70
71func (m *multipleStringArg) String() string {
72 return strings.Join(*m, `, `)
73}
74
75func (m *multipleStringArg) Set(s string) error {
76 *m = append(*m, strings.Split(s, ",")...)
77 return nil
78}
79
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +020080const errorLeadingLines = 20
81const errorTrailingLines = 20
82
83func errMsgFromLog(filename string) string {
84 if filename == "" {
85 return ""
86 }
87
88 data, err := ioutil.ReadFile(filename)
89 if err != nil {
90 return ""
91 }
92
93 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
94 if len(lines) > errorLeadingLines+errorTrailingLines+1 {
95 lines[errorLeadingLines] = fmt.Sprintf("... skipping %d lines ...",
96 len(lines)-errorLeadingLines-errorTrailingLines)
97
98 lines = append(lines[:errorLeadingLines+1],
99 lines[len(lines)-errorTrailingLines:]...)
100 }
101 var buf strings.Builder
102 for _, line := range lines {
103 buf.WriteString("> ")
104 buf.WriteString(line)
105 buf.WriteString("\n")
106 }
107 return buf.String()
108}
109
Dan Willemsen22de2162017-12-11 14:35:23 -0800110// TODO(b/70370883): This tool uses a lot of open files -- over the default
111// soft limit of 1024 on some systems. So bump up to the hard limit until I fix
112// the algorithm.
113func setMaxFiles(log logger.Logger) {
114 var limits syscall.Rlimit
115
116 err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limits)
117 if err != nil {
118 log.Println("Failed to get file limit:", err)
119 return
120 }
121
122 log.Verbosef("Current file limits: %d soft, %d hard", limits.Cur, limits.Max)
123 if limits.Cur == limits.Max {
124 return
125 }
126
127 limits.Cur = limits.Max
128 err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limits)
129 if err != nil {
130 log.Println("Failed to increase file limit:", err)
131 }
132}
133
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700134func inList(str string, list []string) bool {
135 for _, other := range list {
136 if str == other {
137 return true
138 }
139 }
140 return false
141}
142
Dan Willemsen41538382018-08-31 19:51:35 -0700143func copyFile(from, to string) error {
144 fromFile, err := os.Open(from)
145 if err != nil {
146 return err
147 }
148 defer fromFile.Close()
149
150 toFile, err := os.Create(to)
151 if err != nil {
152 return err
153 }
154 defer toFile.Close()
155
156 _, err = io.Copy(toFile, fromFile)
157 return err
158}
159
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700160type mpContext struct {
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200161 Logger logger.Logger
162 Status status.ToolStatus
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700163
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200164 SoongUi string
165 MainOutDir string
166 MainLogsDir string
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700167}
168
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200169func detectTotalRAM() uint64 {
170 var info syscall.Sysinfo_t
171 err := syscall.Sysinfo(&info)
172 if err != nil {
173 panic(err)
174 }
175 return info.Totalram * uint64(info.Unit)
176}
177
178func findNamedProducts(soongUi string, log logger.Logger) []string {
179 cmd := exec.Command(soongUi, "--dumpvars-mode", "--vars=all_named_products")
180 output, err := cmd.Output()
181 if err != nil {
182 log.Fatalf("Cannot determine named products: %v", err)
183 }
184
185 rx := regexp.MustCompile(`^all_named_products='(.*)'$`)
186 match := rx.FindStringSubmatch(strings.TrimSpace(string(output)))
187 return strings.Fields(match[1])
188}
189
190// ensureEmptyFileExists ensures that the containing directory exists, and the
191// specified file exists. If it doesn't exist, it will write an empty file.
192func ensureEmptyFileExists(file string, log logger.Logger) {
193 if _, err := os.Stat(file); os.IsNotExist(err) {
194 f, err := os.Create(file)
195 if err != nil {
196 log.Fatalf("Error creating %s: %q\n", file, err)
197 }
198 f.Close()
199 } else if err != nil {
200 log.Fatalf("Error checking %s: %q\n", file, err)
201 }
202}
203
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200204func outDirBase() string {
205 outDirBase := os.Getenv("OUT_DIR")
206 if outDirBase == "" {
207 return "out"
208 } else {
209 return outDirBase
210 }
211}
212
213func distDir(outDir string) string {
214 if distDir := os.Getenv("DIST_DIR"); distDir != "" {
215 return filepath.Clean(distDir)
216 } else {
217 return filepath.Join(outDir, "dist")
218 }
219}
220
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800221func main() {
Colin Cross097ed2a2019-06-08 21:48:58 -0700222 stdio := terminal.StdioImpl{}
Dan Willemsenb82471a2018-05-17 16:37:09 -0700223
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200224 output := terminal.NewStatusOutput(stdio.Stdout(), "", false, false)
Colin Crosse0df1a32019-06-09 19:40:08 -0700225 log := logger.New(output)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800226 defer log.Cleanup()
227
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200228 for _, v := range os.Environ() {
229 log.Println("Environment: " + v)
230 }
231
232 log.Printf("Argv: %v\n", os.Args)
233
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800234 flag.Parse()
235
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200236 _, cancel := context.WithCancel(context.Background())
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800237 defer cancel()
238
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700239 trace := tracer.New(log)
240 defer trace.Close()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800241
Dan Willemsenb82471a2018-05-17 16:37:09 -0700242 stat := &status.Status{}
243 defer stat.Finish()
Colin Crosse0df1a32019-06-09 19:40:08 -0700244 stat.AddOutput(output)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700245
Dan Willemsen34218ec2018-07-19 22:57:18 -0700246 var failures failureCount
247 stat.AddOutput(&failures)
248
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200249 signal.SetupSignals(log, cancel, func() {
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700250 trace.Close()
251 log.Cleanup()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700252 stat.Finish()
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700253 })
254
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200255 soongUi := "build/soong/soong_ui.bash"
256
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200257 var outputDir string
258 if *outDir != "" {
259 outputDir = *outDir
260 } else {
Dan Willemsen41538382018-08-31 19:51:35 -0700261 name := "multiproduct"
262 if !*incremental {
263 name += "-" + time.Now().Format("20060102150405")
264 }
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200265 outputDir = filepath.Join(outDirBase(), name)
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200266 }
267
268 log.Println("Output directory:", outputDir)
269
270 // The ninja_build file is used by our buildbots to understand that the output
271 // can be parsed as ninja output.
272 if err := os.MkdirAll(outputDir, 0777); err != nil {
273 log.Fatalf("Failed to create output directory: %v", err)
274 }
275 ensureEmptyFileExists(filepath.Join(outputDir, "ninja_build"), log)
276
277 logsDir := filepath.Join(outputDir, "logs")
Dan Willemsene3480762017-11-07 11:23:27 -0800278 os.MkdirAll(logsDir, 0777)
279
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200280 var configLogsDir string
281 if *alternateResultDir {
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200282 configLogsDir = filepath.Join(distDir(outDirBase()), "logs")
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200283 } else {
284 configLogsDir = outputDir
285 }
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000286
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200287 log.Println("Logs dir: " + configLogsDir)
288
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200289 os.MkdirAll(configLogsDir, 0777)
290 log.SetOutput(filepath.Join(configLogsDir, "soong.log"))
291 trace.SetOutput(filepath.Join(configLogsDir, "build.trace"))
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800292
Dan Willemsen1bdbdec2019-12-27 09:54:11 -0800293 var jobs = *numJobs
294 if jobs < 1 {
295 jobs = runtime.NumCPU() / 4
296
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200297 ramGb := int(detectTotalRAM() / (1024 * 1024 * 1024))
Colin Crossf04fe9a2021-01-26 14:03:21 -0800298 if ramJobs := ramGb / 25; ramGb > 0 && jobs > ramJobs {
Dan Willemsen1bdbdec2019-12-27 09:54:11 -0800299 jobs = ramJobs
300 }
301
302 if jobs < 1 {
303 jobs = 1
304 }
305 }
306 log.Verbosef("Using %d parallel jobs", jobs)
307
Dan Willemsen22de2162017-12-11 14:35:23 -0800308 setMaxFiles(log)
309
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200310 allProducts := findNamedProducts(soongUi, log)
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700311 var productsList []string
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700312
Colin Crossf2f3d312020-12-17 11:29:31 -0800313 if len(includeProducts) > 0 {
314 var missingProducts []string
315 for _, product := range includeProducts {
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700316 if inList(product, allProducts) {
317 productsList = append(productsList, product)
318 } else {
319 missingProducts = append(missingProducts, product)
320 }
321 }
322 if len(missingProducts) > 0 {
323 log.Fatalf("Products don't exist: %s\n", missingProducts)
324 }
325 } else {
326 productsList = allProducts
327 }
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700328
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700329 finalProductsList := make([]string, 0, len(productsList))
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700330 skipProduct := func(p string) bool {
Colin Crossf2f3d312020-12-17 11:29:31 -0800331 for _, s := range skipProducts {
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700332 if p == s {
333 return true
334 }
335 }
336 return false
337 }
338 for _, product := range productsList {
339 if !skipProduct(product) {
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700340 finalProductsList = append(finalProductsList, product)
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700341 } else {
342 log.Verbose("Skipping: ", product)
343 }
344 }
345
Dan Willemsen9609ad92019-12-05 15:22:41 -0800346 if *shard < 1 {
347 log.Fatalf("--shard value must be >= 1, not %d\n", *shard)
348 } else if *shardCount < 1 {
349 log.Fatalf("--shard-count value must be >= 1, not %d\n", *shardCount)
350 } else if *shard > *shardCount {
351 log.Fatalf("--shard (%d) must not be greater than --shard-count (%d)\n", *shard,
352 *shardCount)
353 } else if *shardCount > 1 {
354 finalProductsList = splitList(finalProductsList, *shardCount)[*shard-1]
355 }
356
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700357 log.Verbose("Got product list: ", finalProductsList)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800358
Lukacs T. Berki2c405692021-08-11 09:19:27 +0200359 s := stat.StartTool()
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700360 s.SetTotalActions(len(finalProductsList))
Dan Willemsena4e43a72017-05-06 16:58:26 -0700361
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700362 mpCtx := &mpContext{
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200363 Logger: log,
364 Status: s,
365 SoongUi: soongUi,
366 MainOutDir: outputDir,
367 MainLogsDir: logsDir,
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800368 }
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700369
370 products := make(chan string, len(productsList))
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800371 go func() {
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700372 defer close(products)
373 for _, product := range finalProductsList {
374 products <- product
375 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800376 }()
377
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700378 var wg sync.WaitGroup
Dan Willemsen1bdbdec2019-12-27 09:54:11 -0800379 for i := 0; i < jobs; i++ {
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700380 wg.Add(1)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800381 go func() {
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700382 defer wg.Done()
383 for {
384 select {
385 case product := <-products:
386 if product == "" {
387 return
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800388 }
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200389 runSoongUiForProduct(mpCtx, product)
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700390 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800391 }
392 }()
393 }
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700394 wg.Wait()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800395
Dan Willemsene3480762017-11-07 11:23:27 -0800396 if *alternateResultDir {
397 args := zip.ZipArgs{
398 FileArgs: []zip.FileArg{
399 {GlobDir: logsDir, SourcePrefixToStrip: logsDir},
400 },
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200401 OutputFilePath: filepath.Join(distDir(outDirBase()), "logs.zip"),
Dan Willemsene3480762017-11-07 11:23:27 -0800402 NumParallelJobs: runtime.NumCPU(),
403 CompressionLevel: 5,
404 }
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200405 log.Printf("Logs zip: %v\n", args.OutputFilePath)
Colin Cross05518bc2018-09-27 15:06:19 -0700406 if err := zip.Zip(args); err != nil {
Dan Willemsene3480762017-11-07 11:23:27 -0800407 log.Fatalf("Error zipping logs: %v", err)
408 }
409 }
410
Dan Willemsenb82471a2018-05-17 16:37:09 -0700411 s.Finish()
Dan Willemsen34218ec2018-07-19 22:57:18 -0700412
413 if failures == 1 {
414 log.Fatal("1 failure")
415 } else if failures > 1 {
416 log.Fatalf("%d failures", failures)
417 } else {
Colin Crosse0df1a32019-06-09 19:40:08 -0700418 fmt.Fprintln(output, "Success")
Dan Willemsen34218ec2018-07-19 22:57:18 -0700419 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800420}
Dan Willemsen34218ec2018-07-19 22:57:18 -0700421
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200422func cleanupAfterProduct(outDir, productZip string) {
423 if *keepArtifacts {
424 args := zip.ZipArgs{
425 FileArgs: []zip.FileArg{
426 {
427 GlobDir: outDir,
428 SourcePrefixToStrip: outDir,
429 },
430 },
431 OutputFilePath: productZip,
432 NumParallelJobs: runtime.NumCPU(),
433 CompressionLevel: 5,
434 }
435 if err := zip.Zip(args); err != nil {
436 log.Fatalf("Error zipping artifacts: %v", err)
437 }
438 }
439 if !*incremental {
440 os.RemoveAll(outDir)
441 }
442}
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700443
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200444func runSoongUiForProduct(mpctx *mpContext, product string) {
445 outDir := filepath.Join(mpctx.MainOutDir, product)
446 logsDir := filepath.Join(mpctx.MainLogsDir, product)
447 productZip := filepath.Join(mpctx.MainOutDir, product+".zip")
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200448 consoleLogPath := filepath.Join(logsDir, "std.log")
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700449
450 if err := os.MkdirAll(outDir, 0777); err != nil {
451 mpctx.Logger.Fatalf("Error creating out directory: %v", err)
452 }
453 if err := os.MkdirAll(logsDir, 0777); err != nil {
454 mpctx.Logger.Fatalf("Error creating log directory: %v", err)
455 }
456
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200457 consoleLogFile, err := os.Create(consoleLogPath)
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700458 if err != nil {
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200459 mpctx.Logger.Fatalf("Error creating console log file: %v", err)
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700460 }
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200461 defer consoleLogFile.Close()
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700462
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200463 consoleLogWriter := bufio.NewWriter(consoleLogFile)
464 defer consoleLogWriter.Flush()
465
466 args := []string{"--make-mode", "--skip-soong-tests", "--skip-ninja"}
467
468 if !*keepArtifacts {
469 args = append(args, "--empty-ninja-file")
470 }
471
472 if *onlyConfig {
473 args = append(args, "--config-only")
474 } else if *onlySoong {
475 args = append(args, "--soong-only")
476 }
477
Lukacs T. Berkif656b842021-08-11 11:10:28 +0200478 cmd := exec.Command(mpctx.SoongUi, args...)
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200479 cmd.Stdout = consoleLogWriter
480 cmd.Stderr = consoleLogWriter
481 cmd.Env = append(os.Environ(),
482 "OUT_DIR="+outDir,
483 "TARGET_PRODUCT="+product,
484 "TARGET_BUILD_VARIANT="+*buildVariant,
485 "TARGET_BUILD_TYPE=release",
486 "TARGET_BUILD_APPS=",
487 "TARGET_BUILD_UNBUNDLED=")
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700488
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200489 if *alternateResultDir {
490 cmd.Env = append(cmd.Env,
491 "DIST_DIR="+filepath.Join(distDir(outDirBase()), "products/"+product))
492 }
493
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700494 action := &status.Action{
495 Description: product,
496 Outputs: []string{product},
497 }
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200498
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700499 mpctx.Status.StartAction(action)
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200500 defer cleanupAfterProduct(outDir, productZip)
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700501
502 before := time.Now()
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200503 err = cmd.Run()
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700504
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200505 if !*onlyConfig && !*onlySoong {
506 katiBuildNinjaFile := filepath.Join(outDir, "build-"+product+".ninja")
507 if after, err := os.Stat(katiBuildNinjaFile); err == nil && after.ModTime().After(before) {
508 err := copyFile(consoleLogPath, filepath.Join(filepath.Dir(consoleLogPath), "std_full.log"))
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700509 if err != nil {
510 log.Fatalf("Error copying log file: %s", err)
511 }
512 }
513 }
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200514 var errOutput string
515 if err == nil {
516 errOutput = ""
517 } else {
518 errOutput = errMsgFromLog(consoleLogPath)
519 }
520
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700521 mpctx.Status.FinishAction(status.ActionResult{
522 Action: action,
Lukacs T. Berkicef87b62021-08-10 15:01:13 +0200523 Error: err,
Lukacs T. Berkibf5bdb22021-08-24 10:47:13 +0200524 Output: errOutput,
Dan Willemsenbcc1dbf2018-09-04 18:09:47 -0700525 })
526}
527
Dan Willemsen34218ec2018-07-19 22:57:18 -0700528type failureCount int
529
530func (f *failureCount) StartAction(action *status.Action, counts status.Counts) {}
531
532func (f *failureCount) FinishAction(result status.ActionResult, counts status.Counts) {
533 if result.Error != nil {
534 *f += 1
535 }
536}
537
538func (f *failureCount) Message(level status.MsgLevel, message string) {
539 if level >= status.ErrorLvl {
540 *f += 1
541 }
542}
543
544func (f *failureCount) Flush() {}
Colin Crosse0df1a32019-06-09 19:40:08 -0700545
546func (f *failureCount) Write(p []byte) (int, error) {
547 // discard writes
548 return len(p), nil
549}
Dan Willemsen9609ad92019-12-05 15:22:41 -0800550
551func splitList(list []string, shardCount int) (ret [][]string) {
552 each := len(list) / shardCount
553 extra := len(list) % shardCount
554 for i := 0; i < shardCount; i++ {
555 count := each
556 if extra > 0 {
557 count += 1
558 extra -= 1
559 }
560 ret = append(ret, list[:count])
561 list = list[count:]
562 }
563 return
564}