blob: 237d384ccdd3bf70efb6e02ad50d0fd0f63f9a87 [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 (
Dan Willemsenc2af0be2017-01-20 14:10:01 -080018 "context"
19 "flag"
20 "fmt"
Dan Willemsenf624fb92017-05-19 16:39:04 -070021 "io/ioutil"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080022 "os"
23 "path/filepath"
24 "runtime"
25 "strings"
26 "sync"
Dan Willemsen22de2162017-12-11 14:35:23 -080027 "syscall"
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 Willemsenb82471a2018-05-17 16:37:09 -070032 "android/soong/ui/status"
33 "android/soong/ui/terminal"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070034 "android/soong/ui/tracer"
Dan Willemsene3480762017-11-07 11:23:27 -080035 "android/soong/zip"
Dan Willemsenc2af0be2017-01-20 14:10:01 -080036)
37
38// We default to number of cpus / 4, which seems to be the sweet spot for my
39// system. I suspect this is mostly due to memory or disk bandwidth though, and
40// may depend on the size ofthe source tree, so this probably isn't a great
41// default.
42func detectNumJobs() int {
43 if runtime.NumCPU() < 4 {
44 return 1
45 }
46 return runtime.NumCPU() / 4
47}
48
49var numJobs = flag.Int("j", detectNumJobs(), "number of parallel kati jobs")
50
Dan Willemsene3480762017-11-07 11:23:27 -080051var keepArtifacts = flag.Bool("keep", false, "keep archives of artifacts")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080052
53var outDir = flag.String("out", "", "path to store output directories (defaults to tmpdir under $OUT when empty)")
Dan Willemsenf624fb92017-05-19 16:39:04 -070054var alternateResultDir = flag.Bool("dist", false, "write select results to $DIST_DIR (or <out>/dist when empty)")
Dan Willemsenc2af0be2017-01-20 14:10:01 -080055
56var onlyConfig = flag.Bool("only-config", false, "Only run product config (not Soong or Kati)")
57var onlySoong = flag.Bool("only-soong", false, "Only run product config and Soong (not Kati)")
58
Dan Willemsen5ed900b2017-05-07 11:40:30 -070059var buildVariant = flag.String("variant", "eng", "build variant to use")
60
Dan Willemsen9957b9c2017-10-06 15:05:05 -070061var skipProducts = flag.String("skip-products", "", "comma-separated list of products to skip (known failures, etc)")
Jeff Gastonb61e3f72017-10-25 15:02:45 -070062var includeProducts = flag.String("products", "", "comma-separated list of products to build")
Dan Willemsen9957b9c2017-10-06 15:05:05 -070063
Dan Willemsenf624fb92017-05-19 16:39:04 -070064const errorLeadingLines = 20
65const errorTrailingLines = 20
66
Dan Willemsenc2af0be2017-01-20 14:10:01 -080067type Product struct {
Dan Willemsenf624fb92017-05-19 16:39:04 -070068 ctx build.Context
69 config build.Config
70 logFile string
Dan Willemsenb82471a2018-05-17 16:37:09 -070071 action *status.Action
Dan Willemsenc2af0be2017-01-20 14:10:01 -080072}
73
Dan Willemsenb82471a2018-05-17 16:37:09 -070074func errMsgFromLog(filename string) string {
75 if filename == "" {
76 return ""
Dan Willemsena4e43a72017-05-06 16:58:26 -070077 }
78
Dan Willemsenb82471a2018-05-17 16:37:09 -070079 data, err := ioutil.ReadFile(filename)
80 if err != nil {
81 return ""
Dan Willemsenf624fb92017-05-19 16:39:04 -070082 }
83
Dan Willemsenb82471a2018-05-17 16:37:09 -070084 lines := strings.Split(strings.TrimSpace(string(data)), "\n")
85 if len(lines) > errorLeadingLines+errorTrailingLines+1 {
86 lines[errorLeadingLines] = fmt.Sprintf("... skipping %d lines ...",
87 len(lines)-errorLeadingLines-errorTrailingLines)
Dan Willemsena4e43a72017-05-06 16:58:26 -070088
Dan Willemsenb82471a2018-05-17 16:37:09 -070089 lines = append(lines[:errorLeadingLines+1],
90 lines[len(lines)-errorTrailingLines:]...)
Dan Willemsena4e43a72017-05-06 16:58:26 -070091 }
Dan Willemsenb82471a2018-05-17 16:37:09 -070092 var buf strings.Builder
93 for _, line := range lines {
94 buf.WriteString("> ")
95 buf.WriteString(line)
96 buf.WriteString("\n")
Dan Willemsena4e43a72017-05-06 16:58:26 -070097 }
Dan Willemsenb82471a2018-05-17 16:37:09 -070098 return buf.String()
Dan Willemsena4e43a72017-05-06 16:58:26 -070099}
100
Dan Willemsen22de2162017-12-11 14:35:23 -0800101// TODO(b/70370883): This tool uses a lot of open files -- over the default
102// soft limit of 1024 on some systems. So bump up to the hard limit until I fix
103// the algorithm.
104func setMaxFiles(log logger.Logger) {
105 var limits syscall.Rlimit
106
107 err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limits)
108 if err != nil {
109 log.Println("Failed to get file limit:", err)
110 return
111 }
112
113 log.Verbosef("Current file limits: %d soft, %d hard", limits.Cur, limits.Max)
114 if limits.Cur == limits.Max {
115 return
116 }
117
118 limits.Cur = limits.Max
119 err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limits)
120 if err != nil {
121 log.Println("Failed to increase file limit:", err)
122 }
123}
124
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700125func inList(str string, list []string) bool {
126 for _, other := range list {
127 if str == other {
128 return true
129 }
130 }
131 return false
132}
133
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800134func main() {
Dan Willemsenb82471a2018-05-17 16:37:09 -0700135 writer := terminal.NewWriter(terminal.StdioImpl{})
136 defer writer.Finish()
137
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800138 log := logger.New(os.Stderr)
139 defer log.Cleanup()
140
141 flag.Parse()
142
143 ctx, cancel := context.WithCancel(context.Background())
144 defer cancel()
145
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700146 trace := tracer.New(log)
147 defer trace.Close()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800148
Dan Willemsenb82471a2018-05-17 16:37:09 -0700149 stat := &status.Status{}
150 defer stat.Finish()
151 stat.AddOutput(terminal.NewStatusOutput(writer, ""))
152
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700153 build.SetupSignals(log, cancel, func() {
154 trace.Close()
155 log.Cleanup()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700156 stat.Finish()
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700157 })
158
159 buildCtx := build.Context{&build.ContextImpl{
Dan Willemsenb82471a2018-05-17 16:37:09 -0700160 Context: ctx,
161 Logger: log,
162 Tracer: trace,
163 Writer: writer,
164 Status: stat,
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700165 }}
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800166
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800167 config := build.NewConfig(buildCtx)
168 if *outDir == "" {
Steven Moreland552432e2017-03-29 19:26:09 -0700169 name := "multiproduct-" + time.Now().Format("20060102150405")
170
171 *outDir = filepath.Join(config.OutDir(), name)
172
Dan Willemsenf624fb92017-05-19 16:39:04 -0700173 // Ensure the empty files exist in the output directory
174 // containing our output directory too. This is mostly for
175 // safety, but also triggers the ninja_build file so that our
176 // build servers know that they can parse the output as if it
177 // was ninja output.
178 build.SetupOutDir(buildCtx, config)
179
Steven Moreland552432e2017-03-29 19:26:09 -0700180 if err := os.MkdirAll(*outDir, 0777); err != nil {
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800181 log.Fatalf("Failed to create tempdir: %v", err)
182 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800183 }
184 config.Environment().Set("OUT_DIR", *outDir)
185 log.Println("Output directory:", *outDir)
186
Dan Willemsene3480762017-11-07 11:23:27 -0800187 logsDir := filepath.Join(config.OutDir(), "logs")
188 os.MkdirAll(logsDir, 0777)
189
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800190 build.SetupOutDir(buildCtx, config)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700191 if *alternateResultDir {
Dan Willemsene3480762017-11-07 11:23:27 -0800192 distLogsDir := filepath.Join(config.DistDir(), "logs")
193 os.MkdirAll(distLogsDir, 0777)
194 log.SetOutput(filepath.Join(distLogsDir, "soong.log"))
195 trace.SetOutput(filepath.Join(distLogsDir, "build.trace"))
Dan Willemsenf624fb92017-05-19 16:39:04 -0700196 } else {
197 log.SetOutput(filepath.Join(config.OutDir(), "soong.log"))
198 trace.SetOutput(filepath.Join(config.OutDir(), "build.trace"))
199 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800200
Dan Willemsen22de2162017-12-11 14:35:23 -0800201 setMaxFiles(log)
202
Dan Willemsen04d76ef2018-05-15 00:52:29 -0700203 finder := build.NewSourceFinder(buildCtx, config)
204 defer finder.Shutdown()
205
206 build.FindSources(buildCtx, config, finder)
207
Dan Willemsenb2e6c2e2017-07-13 17:24:44 -0700208 vars, err := build.DumpMakeVars(buildCtx, config, nil, []string{"all_named_products"})
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800209 if err != nil {
210 log.Fatal(err)
211 }
Jeff Gastonb61e3f72017-10-25 15:02:45 -0700212 var productsList []string
213 allProducts := strings.Fields(vars["all_named_products"])
214
215 if *includeProducts != "" {
216 missingProducts := []string{}
217 for _, product := range strings.Split(*includeProducts, ",") {
218 if inList(product, allProducts) {
219 productsList = append(productsList, product)
220 } else {
221 missingProducts = append(missingProducts, product)
222 }
223 }
224 if len(missingProducts) > 0 {
225 log.Fatalf("Products don't exist: %s\n", missingProducts)
226 }
227 } else {
228 productsList = allProducts
229 }
Dan Willemsen9957b9c2017-10-06 15:05:05 -0700230
231 products := make([]string, 0, len(productsList))
232 skipList := strings.Split(*skipProducts, ",")
233 skipProduct := func(p string) bool {
234 for _, s := range skipList {
235 if p == s {
236 return true
237 }
238 }
239 return false
240 }
241 for _, product := range productsList {
242 if !skipProduct(product) {
243 products = append(products, product)
244 } else {
245 log.Verbose("Skipping: ", product)
246 }
247 }
248
249 log.Verbose("Got product list: ", products)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800250
Dan Willemsenb82471a2018-05-17 16:37:09 -0700251 s := buildCtx.Status.StartTool()
252 s.SetTotalActions(len(products))
Dan Willemsena4e43a72017-05-06 16:58:26 -0700253
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
257 // Run the product config for every product in parallel
258 for _, product := range products {
259 wg.Add(1)
260 go func(product string) {
Dan Willemsenf624fb92017-05-19 16:39:04 -0700261 var stdLog string
262
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800263 defer wg.Done()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700264
265 action := &status.Action{
266 Description: product,
267 Outputs: []string{product},
268 }
269 s.StartAction(action)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800270 defer logger.Recover(func(err error) {
Dan Willemsenb82471a2018-05-17 16:37:09 -0700271 s.FinishAction(status.ActionResult{
272 Action: action,
273 Error: err,
274 Output: errMsgFromLog(stdLog),
275 })
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800276 })
277
278 productOutDir := filepath.Join(config.OutDir(), product)
Dan Willemsene3480762017-11-07 11:23:27 -0800279 productLogDir := filepath.Join(logsDir, product)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800280
281 if err := os.MkdirAll(productOutDir, 0777); err != nil {
282 log.Fatalf("Error creating out directory: %v", err)
283 }
Dan Willemsene3480762017-11-07 11:23:27 -0800284 if err := os.MkdirAll(productLogDir, 0777); err != nil {
285 log.Fatalf("Error creating log directory: %v", err)
286 }
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800287
Dan Willemsenf624fb92017-05-19 16:39:04 -0700288 stdLog = filepath.Join(productLogDir, "std.log")
289 f, err := os.Create(stdLog)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800290 if err != nil {
291 log.Fatalf("Error creating std.log: %v", err)
292 }
293
Dan Willemsenf1963962017-11-11 15:44:51 -0800294 productLog := logger.New(f)
Dan Willemsenf624fb92017-05-19 16:39:04 -0700295 productLog.SetOutput(filepath.Join(productLogDir, "soong.log"))
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800296
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700297 productCtx := build.Context{&build.ContextImpl{
Dan Willemsenb82471a2018-05-17 16:37:09 -0700298 Context: ctx,
299 Logger: productLog,
300 Tracer: trace,
301 Writer: terminal.NewWriter(terminal.NewCustomStdio(nil, f, f)),
302 Thread: trace.NewThread(product),
303 Status: &status.Status{},
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700304 }}
Dan Willemsenb82471a2018-05-17 16:37:09 -0700305 productCtx.Status.AddOutput(terminal.NewStatusOutput(productCtx.Writer, ""))
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800306
307 productConfig := build.NewConfig(productCtx)
308 productConfig.Environment().Set("OUT_DIR", productOutDir)
Jeff Gaston743e29e2017-08-17 14:09:23 -0700309 build.FindSources(productCtx, productConfig, finder)
Dan Willemsen5ed900b2017-05-07 11:40:30 -0700310 productConfig.Lunch(productCtx, product, *buildVariant)
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800311
312 build.Build(productCtx, productConfig, build.BuildProductConfig)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700313 productConfigs <- Product{productCtx, productConfig, stdLog, action}
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800314 }(product)
315 }
316 go func() {
317 defer close(productConfigs)
318 wg.Wait()
319 }()
320
321 var wg2 sync.WaitGroup
322 // Then run up to numJobs worth of Soong and Kati
323 for i := 0; i < *numJobs; i++ {
324 wg2.Add(1)
325 go func() {
326 defer wg2.Done()
327 for product := range productConfigs {
328 func() {
329 defer logger.Recover(func(err error) {
Dan Willemsenb82471a2018-05-17 16:37:09 -0700330 s.FinishAction(status.ActionResult{
331 Action: product.action,
332 Error: err,
333 Output: errMsgFromLog(product.logFile),
334 })
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800335 })
336
Dan Willemsene3480762017-11-07 11:23:27 -0800337 defer func() {
338 if *keepArtifacts {
339 args := zip.ZipArgs{
340 FileArgs: []zip.FileArg{
341 {
342 GlobDir: product.config.OutDir(),
343 SourcePrefixToStrip: product.config.OutDir(),
344 },
345 },
346 OutputFilePath: filepath.Join(config.OutDir(), product.config.TargetProduct()+".zip"),
347 NumParallelJobs: runtime.NumCPU(),
348 CompressionLevel: 5,
349 }
350 if err := zip.Run(args); err != nil {
351 log.Fatalf("Error zipping artifacts: %v", err)
352 }
353 }
354 os.RemoveAll(product.config.OutDir())
355 }()
356
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800357 buildWhat := 0
358 if !*onlyConfig {
359 buildWhat |= build.BuildSoong
360 if !*onlySoong {
361 buildWhat |= build.BuildKati
362 }
363 }
364 build.Build(product.ctx, product.config, buildWhat)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700365 s.FinishAction(status.ActionResult{
366 Action: product.action,
367 })
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800368 }()
369 }
370 }()
371 }
Dan Willemsena4e43a72017-05-06 16:58:26 -0700372 wg2.Wait()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800373
Dan Willemsene3480762017-11-07 11:23:27 -0800374 if *alternateResultDir {
375 args := zip.ZipArgs{
376 FileArgs: []zip.FileArg{
377 {GlobDir: logsDir, SourcePrefixToStrip: logsDir},
378 },
379 OutputFilePath: filepath.Join(config.DistDir(), "logs.zip"),
380 NumParallelJobs: runtime.NumCPU(),
381 CompressionLevel: 5,
382 }
383 if err := zip.Run(args); err != nil {
384 log.Fatalf("Error zipping logs: %v", err)
385 }
386 }
387
Dan Willemsenb82471a2018-05-17 16:37:09 -0700388 s.Finish()
Dan Willemsenc2af0be2017-01-20 14:10:01 -0800389}