blob: 296000bf6a524f52f8103ffa770b5eceb3f94668 [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 (
18 "bytes"
19 "context"
20 "flag"
21 "fmt"
Dan Willemsenf624fb92017-05-19 16:39:04 -070022 "io/ioutil"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080023 "os"
24 "path/filepath"
25 "runtime"
26 "strings"
27 "sync"
Steven Moreland552432e2017-03-29 19:26:09 -070028 "time"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080029
30 "android/soong/ui/build"
31 "android/soong/ui/logger"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070032 "android/soong/ui/tracer"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080033)
34
35// We default to number of cpus / 4, which seems to be the sweet spot for my
36// system. I suspect this is mostly due to memory or disk bandwidth though, and
37// may depend on the size ofthe source tree, so this probably isn't a great
38// default.
39func detectNumJobs() int {
40 if runtime.NumCPU() < 4 {
41 return 1
42 }
43 return runtime.NumCPU() / 4
44}
45
46var numJobs = flag.Int("j", detectNumJobs(), "number of parallel kati jobs")
47
48var keep = flag.Bool("keep", false, "keep successful output files")
49
50var outDir = flag.String("out", "", "path to store output directories (defaults to tmpdir under $OUT when empty)")
Dan Willemsenf624fb92017-05-19 16:39:04 -070051var alternateResultDir = flag.Bool("dist", false, "write select results to $DIST_DIR (or <out>/dist when empty)")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080052
53var onlyConfig = flag.Bool("only-config", false, "Only run product config (not Soong or Kati)")
54var onlySoong = flag.Bool("only-soong", false, "Only run product config and Soong (not Kati)")
55
Dan Willemsen5ed900b2017-05-07 11:40:30 -070056var buildVariant = flag.String("variant", "eng", "build variant to use")
57
Dan Willemsen9957b9c2017-10-06 15:05:05 -070058var skipProducts = flag.String("skip-products", "", "comma-separated list of products to skip (known failures, etc)")
59
Dan Willemsenf624fb92017-05-19 16:39:04 -070060const errorLeadingLines = 20
61const errorTrailingLines = 20
62
Dan Willemsenc2af0be2017-01-20 14:10:01 -080063type Product struct {
Dan Willemsenf624fb92017-05-19 16:39:04 -070064 ctx build.Context
65 config build.Config
66 logFile string
Dan Willemsenc2af0be2017-01-20 14:10:01 -080067}
68
Dan Willemsena4e43a72017-05-06 16:58:26 -070069type Status struct {
70 cur int
71 total int
72 failed int
73
74 ctx build.Context
75 haveBlankLine bool
76 smartTerminal bool
77
78 lock sync.Mutex
79}
80
81func NewStatus(ctx build.Context) *Status {
82 return &Status{
83 ctx: ctx,
84 haveBlankLine: true,
85 smartTerminal: ctx.IsTerminal(),
86 }
87}
88
89func (s *Status) SetTotal(total int) {
90 s.total = total
91}
92
Dan Willemsenf624fb92017-05-19 16:39:04 -070093func (s *Status) Fail(product string, err error, logFile string) {
Dan Willemsena4e43a72017-05-06 16:58:26 -070094 s.Finish(product)
95
96 s.lock.Lock()
97 defer s.lock.Unlock()
98
99 if s.smartTerminal && !s.haveBlankLine {
100 fmt.Fprintln(s.ctx.Stdout())
101 s.haveBlankLine = true
102 }
103
104 s.failed++
105 fmt.Fprintln(s.ctx.Stderr(), "FAILED:", product)
106 s.ctx.Verboseln("FAILED:", product)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700107
108 if logFile != "" {
109 data, err := ioutil.ReadFile(logFile)
110 if err == nil {
111 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
112 if len(lines) > errorLeadingLines+errorTrailingLines+1 {
113 lines[errorLeadingLines] = fmt.Sprintf("... skipping %d lines ...",
114 len(lines)-errorLeadingLines-errorTrailingLines)
115
116 lines = append(lines[:errorLeadingLines+1],
117 lines[len(lines)-errorTrailingLines:]...)
118 }
119 for _, line := range lines {
120 fmt.Fprintln(s.ctx.Stderr(), "> ", line)
121 s.ctx.Verboseln(line)
122 }
123 }
124 }
125
126 s.ctx.Print(err)
Dan Willemsena4e43a72017-05-06 16:58:26 -0700127}
128
129func (s *Status) Finish(product string) {
130 s.lock.Lock()
131 defer s.lock.Unlock()
132
133 s.cur++
134 line := fmt.Sprintf("[%d/%d] %s", s.cur, s.total, product)
135
136 if s.smartTerminal {
137 if max, ok := s.ctx.TermWidth(); ok {
138 if len(line) > max {
139 line = line[:max]
140 }
141 }
142
143 fmt.Fprint(s.ctx.Stdout(), "\r", line, "\x1b[K")
144 s.haveBlankLine = false
145 } else {
146 s.ctx.Println(line)
147 }
148}
149
150func (s *Status) Finished() int {
151 s.lock.Lock()
152 defer s.lock.Unlock()
153
154 if !s.haveBlankLine {
155 fmt.Fprintln(s.ctx.Stdout())
156 s.haveBlankLine = true
157 }
158 return s.failed
159}
160
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800161func main() {
162 log := logger.New(os.Stderr)
163 defer log.Cleanup()
164
165 flag.Parse()
166
167 ctx, cancel := context.WithCancel(context.Background())
168 defer cancel()
169
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700170 trace := tracer.New(log)
171 defer trace.Close()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800172
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700173 build.SetupSignals(log, cancel, func() {
174 trace.Close()
175 log.Cleanup()
176 })
177
178 buildCtx := build.Context{&build.ContextImpl{
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800179 Context: ctx,
180 Logger: log,
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700181 Tracer: trace,
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800182 StdioInterface: build.StdioImpl{},
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700183 }}
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800184
Dan Willemsena4e43a72017-05-06 16:58:26 -0700185 status := NewStatus(buildCtx)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800186
187 config := build.NewConfig(buildCtx)
188 if *outDir == "" {
Steven Moreland552432e2017-03-29 19:26:09 -0700189 name := "multiproduct-" + time.Now().Format("20060102150405")
190
191 *outDir = filepath.Join(config.OutDir(), name)
192
Dan Willemsenf624fb92017-05-19 16:39:04 -0700193 // Ensure the empty files exist in the output directory
194 // containing our output directory too. This is mostly for
195 // safety, but also triggers the ninja_build file so that our
196 // build servers know that they can parse the output as if it
197 // was ninja output.
198 build.SetupOutDir(buildCtx, config)
199
Steven Moreland552432e2017-03-29 19:26:09 -0700200 if err := os.MkdirAll(*outDir, 0777); err != nil {
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800201 log.Fatalf("Failed to create tempdir: %v", err)
202 }
203
204 if !*keep {
205 defer func() {
Dan Willemsena4e43a72017-05-06 16:58:26 -0700206 if status.Finished() == 0 {
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800207 os.RemoveAll(*outDir)
208 }
209 }()
210 }
211 }
212 config.Environment().Set("OUT_DIR", *outDir)
213 log.Println("Output directory:", *outDir)
214
215 build.SetupOutDir(buildCtx, config)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700216 if *alternateResultDir {
217 logsDir := filepath.Join(config.DistDir(), "logs")
218 os.MkdirAll(logsDir, 0777)
219 log.SetOutput(filepath.Join(logsDir, "soong.log"))
220 trace.SetOutput(filepath.Join(logsDir, "build.trace"))
221 } else {
222 log.SetOutput(filepath.Join(config.OutDir(), "soong.log"))
223 trace.SetOutput(filepath.Join(config.OutDir(), "build.trace"))
224 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800225
226 vars, err := build.DumpMakeVars(buildCtx, config, nil, nil, []string{"all_named_products"})
227 if err != nil {
228 log.Fatal(err)
229 }
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700230 productsList := strings.Fields(vars["all_named_products"])
231
232 products := make([]string, 0, len(productsList))
233 skipList := strings.Split(*skipProducts, ",")
234 skipProduct := func(p string) bool {
235 for _, s := range skipList {
236 if p == s {
237 return true
238 }
239 }
240 return false
241 }
242 for _, product := range productsList {
243 if !skipProduct(product) {
244 products = append(products, product)
245 } else {
246 log.Verbose("Skipping: ", product)
247 }
248 }
249
250 log.Verbose("Got product list: ", products)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800251
Dan Willemsena4e43a72017-05-06 16:58:26 -0700252 status.SetTotal(len(products))
253
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800254 var wg sync.WaitGroup
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800255 productConfigs := make(chan Product, len(products))
256
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700257 finder := build.NewSourceFinder(buildCtx, config)
258 defer finder.Shutdown()
259
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800260 // Run the product config for every product in parallel
261 for _, product := range products {
262 wg.Add(1)
263 go func(product string) {
Dan Willemsenf624fb92017-05-19 16:39:04 -0700264 var stdLog string
265
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800266 defer wg.Done()
267 defer logger.Recover(func(err error) {
Dan Willemsenf624fb92017-05-19 16:39:04 -0700268 status.Fail(product, err, stdLog)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800269 })
270
271 productOutDir := filepath.Join(config.OutDir(), product)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700272 productLogDir := productOutDir
273 if *alternateResultDir {
274 productLogDir = filepath.Join(config.DistDir(), product)
275 if err := os.MkdirAll(productLogDir, 0777); err != nil {
276 log.Fatalf("Error creating log directory: %v", err)
277 }
278 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800279
280 if err := os.MkdirAll(productOutDir, 0777); err != nil {
281 log.Fatalf("Error creating out directory: %v", err)
282 }
283
Dan Willemsenf624fb92017-05-19 16:39:04 -0700284 stdLog = filepath.Join(productLogDir, "std.log")
285 f, err := os.Create(stdLog)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800286 if err != nil {
287 log.Fatalf("Error creating std.log: %v", err)
288 }
289
290 productLog := logger.New(&bytes.Buffer{})
Dan Willemsenf624fb92017-05-19 16:39:04 -0700291 productLog.SetOutput(filepath.Join(productLogDir, "soong.log"))
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800292
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700293 productCtx := build.Context{&build.ContextImpl{
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800294 Context: ctx,
295 Logger: productLog,
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700296 Tracer: trace,
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800297 StdioInterface: build.NewCustomStdio(nil, f, f),
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700298 Thread: trace.NewThread(product),
299 }}
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800300
301 productConfig := build.NewConfig(productCtx)
302 productConfig.Environment().Set("OUT_DIR", productOutDir)
Jeff Gaston743e29e2017-08-17 14:09:23 -0700303 build.FindSources(productCtx, productConfig, finder)
Dan Willemsen5ed900b2017-05-07 11:40:30 -0700304 productConfig.Lunch(productCtx, product, *buildVariant)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800305
306 build.Build(productCtx, productConfig, build.BuildProductConfig)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700307 productConfigs <- Product{productCtx, productConfig, stdLog}
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800308 }(product)
309 }
310 go func() {
311 defer close(productConfigs)
312 wg.Wait()
313 }()
314
315 var wg2 sync.WaitGroup
316 // Then run up to numJobs worth of Soong and Kati
317 for i := 0; i < *numJobs; i++ {
318 wg2.Add(1)
319 go func() {
320 defer wg2.Done()
321 for product := range productConfigs {
322 func() {
323 defer logger.Recover(func(err error) {
Dan Willemsenf624fb92017-05-19 16:39:04 -0700324 status.Fail(product.config.TargetProduct(), err, product.logFile)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800325 })
326
327 buildWhat := 0
328 if !*onlyConfig {
329 buildWhat |= build.BuildSoong
330 if !*onlySoong {
331 buildWhat |= build.BuildKati
332 }
333 }
334 build.Build(product.ctx, product.config, buildWhat)
335 if !*keep {
Dan Willemsenc38d3662017-02-24 10:53:23 -0800336 os.RemoveAll(product.config.OutDir())
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800337 }
Dan Willemsena4e43a72017-05-06 16:58:26 -0700338 status.Finish(product.config.TargetProduct())
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800339 }()
340 }
341 }()
342 }
Dan Willemsena4e43a72017-05-06 16:58:26 -0700343 wg2.Wait()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800344
Dan Willemsena4e43a72017-05-06 16:58:26 -0700345 if count := status.Finished(); count > 0 {
346 log.Fatalln(count, "products failed")
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800347 }
348}