main.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. // 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. package main
  15. import (
  16. "context"
  17. "flag"
  18. "fmt"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "syscall"
  25. "time"
  26. "android/soong/shared"
  27. "android/soong/ui/build"
  28. "android/soong/ui/logger"
  29. "android/soong/ui/metrics"
  30. "android/soong/ui/signal"
  31. "android/soong/ui/status"
  32. "android/soong/ui/terminal"
  33. "android/soong/ui/tracer"
  34. )
  35. // A command represents an operation to be executed in the soong build
  36. // system.
  37. type command struct {
  38. // The flag name (must have double dashes).
  39. flag string
  40. // Description for the flag (to display when running help).
  41. description string
  42. // Stream the build status output into the simple terminal mode.
  43. simpleOutput bool
  44. // Sets a prefix string to use for filenames of log files.
  45. logsPrefix string
  46. // Creates the build configuration based on the args and build context.
  47. config func(ctx build.Context, args ...string) build.Config
  48. // Returns what type of IO redirection this Command requires.
  49. stdio func() terminal.StdioInterface
  50. // run the command
  51. run func(ctx build.Context, config build.Config, args []string)
  52. }
  53. // list of supported commands (flags) supported by soong ui
  54. var commands = []command{
  55. {
  56. flag: "--make-mode",
  57. description: "build the modules by the target name (i.e. soong_docs)",
  58. config: build.NewConfig,
  59. stdio: stdio,
  60. run: runMake,
  61. }, {
  62. flag: "--dumpvar-mode",
  63. description: "print the value of the legacy make variable VAR to stdout",
  64. simpleOutput: true,
  65. logsPrefix: "dumpvars-",
  66. config: dumpVarConfig,
  67. stdio: customStdio,
  68. run: dumpVar,
  69. }, {
  70. flag: "--dumpvars-mode",
  71. description: "dump the values of one or more legacy make variables, in shell syntax",
  72. simpleOutput: true,
  73. logsPrefix: "dumpvars-",
  74. config: dumpVarConfig,
  75. stdio: customStdio,
  76. run: dumpVars,
  77. }, {
  78. flag: "--build-mode",
  79. description: "build modules based on the specified build action",
  80. config: buildActionConfig,
  81. stdio: stdio,
  82. run: runMake,
  83. }, {
  84. flag: "--finalize-bazel-metrics",
  85. description: "finalize b metrics and upload",
  86. config: build.UploadOnlyConfig,
  87. stdio: stdio,
  88. // Finalize-bazel-metrics mode updates metrics files and calls the metrics
  89. // uploader. This marks the end of a b invocation.
  90. run: finalizeBazelMetrics,
  91. },
  92. }
  93. // indexList returns the index of first found s. -1 is return if s is not
  94. // found.
  95. func indexList(s string, list []string) int {
  96. for i, l := range list {
  97. if l == s {
  98. return i
  99. }
  100. }
  101. return -1
  102. }
  103. // inList returns true if one or more of s is in the list.
  104. func inList(s string, list []string) bool {
  105. return indexList(s, list) != -1
  106. }
  107. func deleteStaleMetrics(metricsFilePathSlice []string) error {
  108. for _, metricsFilePath := range metricsFilePathSlice {
  109. if err := os.Remove(metricsFilePath); err != nil && !os.IsNotExist(err) {
  110. return fmt.Errorf("Failed to remove %s\nError message: %w", metricsFilePath, err)
  111. }
  112. }
  113. return nil
  114. }
  115. // Main execution of soong_ui. The command format is as follows:
  116. //
  117. // soong_ui <command> [<arg 1> <arg 2> ... <arg n>]
  118. //
  119. // Command is the type of soong_ui execution. Only one type of
  120. // execution is specified. The args are specific to the command.
  121. func main() {
  122. shared.ReexecWithDelveMaybe(os.Getenv("SOONG_UI_DELVE"), shared.ResolveDelveBinary())
  123. buildStarted := time.Now()
  124. c, args, err := getCommand(os.Args)
  125. if err != nil {
  126. fmt.Fprintf(os.Stderr, "Error parsing `soong` args: %s.\n", err)
  127. os.Exit(1)
  128. }
  129. // Create a terminal output that mimics Ninja's.
  130. output := terminal.NewStatusOutput(c.stdio().Stdout(), os.Getenv("NINJA_STATUS"), c.simpleOutput,
  131. build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD"),
  132. build.OsEnvironment().IsEnvTrue("SOONG_UI_ANSI_OUTPUT"))
  133. // Create and start a new metric record.
  134. met := metrics.New()
  135. met.SetBuildDateTime(buildStarted)
  136. met.SetBuildCommand(os.Args)
  137. // Attach a new logger instance to the terminal output.
  138. log := logger.NewWithMetrics(output, met)
  139. defer log.Cleanup()
  140. // Create a context to simplify the program termination process.
  141. ctx, cancel := context.WithCancel(context.Background())
  142. defer cancel()
  143. // Create a new trace file writer, making it log events to the log instance.
  144. trace := tracer.New(log)
  145. defer trace.Close()
  146. // Create a new Status instance, which manages action counts and event output channels.
  147. stat := &status.Status{}
  148. // Hook up the terminal output and tracer to Status.
  149. stat.AddOutput(output)
  150. stat.AddOutput(trace.StatusTracer())
  151. // Set up a cleanup procedure in case the normal termination process doesn't work.
  152. signal.SetupSignals(log, cancel, func() {
  153. trace.Close()
  154. log.Cleanup()
  155. stat.Finish()
  156. })
  157. criticalPath := status.NewCriticalPath()
  158. buildCtx := build.Context{ContextImpl: &build.ContextImpl{
  159. Context: ctx,
  160. Logger: log,
  161. Metrics: met,
  162. Tracer: trace,
  163. Writer: output,
  164. Status: stat,
  165. CriticalPath: criticalPath,
  166. }}
  167. config := c.config(buildCtx, args...)
  168. config.SetLogsPrefix(c.logsPrefix)
  169. logsDir := config.LogsDir()
  170. buildStarted = config.BuildStartedTimeOrDefault(buildStarted)
  171. buildErrorFile := filepath.Join(logsDir, c.logsPrefix+"build_error")
  172. soongMetricsFile := filepath.Join(logsDir, c.logsPrefix+"soong_metrics")
  173. rbeMetricsFile := filepath.Join(logsDir, c.logsPrefix+"rbe_metrics.pb")
  174. bp2buildMetricsFile := filepath.Join(logsDir, c.logsPrefix+"bp2build_metrics.pb")
  175. bazelMetricsFile := filepath.Join(logsDir, c.logsPrefix+"bazel_metrics.pb")
  176. soongBuildMetricsFile := filepath.Join(logsDir, c.logsPrefix+"soong_build_metrics.pb")
  177. metricsFiles := []string{
  178. buildErrorFile, // build error strings
  179. rbeMetricsFile, // high level metrics related to remote build execution.
  180. bp2buildMetricsFile, // high level metrics related to bp2build.
  181. soongMetricsFile, // high level metrics related to this build system.
  182. bazelMetricsFile, // high level metrics related to bazel execution
  183. soongBuildMetricsFile, // high level metrics related to soong build(except bp2build)
  184. config.BazelMetricsDir(), // directory that contains a set of bazel metrics.
  185. }
  186. os.MkdirAll(logsDir, 0777)
  187. log.SetOutput(filepath.Join(logsDir, c.logsPrefix+"soong.log"))
  188. trace.SetOutput(filepath.Join(logsDir, c.logsPrefix+"build.trace"))
  189. defer func() {
  190. stat.Finish()
  191. criticalPath.WriteToMetrics(met)
  192. met.Dump(soongMetricsFile)
  193. if !config.SkipMetricsUpload() {
  194. build.UploadMetrics(buildCtx, config, c.simpleOutput, buildStarted, metricsFiles...)
  195. }
  196. }()
  197. c.run(buildCtx, config, args)
  198. }
  199. func logAndSymlinkSetup(buildCtx build.Context, config build.Config) {
  200. log := buildCtx.ContextImpl.Logger
  201. logsPrefix := config.GetLogsPrefix()
  202. build.SetupOutDir(buildCtx, config)
  203. logsDir := config.LogsDir()
  204. // Common list of metric file definition.
  205. buildErrorFile := filepath.Join(logsDir, logsPrefix+"build_error")
  206. rbeMetricsFile := filepath.Join(logsDir, logsPrefix+"rbe_metrics.pb")
  207. soongMetricsFile := filepath.Join(logsDir, logsPrefix+"soong_metrics")
  208. bp2buildMetricsFile := filepath.Join(logsDir, logsPrefix+"bp2build_metrics.pb")
  209. soongBuildMetricsFile := filepath.Join(logsDir, logsPrefix+"soong_build_metrics.pb")
  210. bazelMetricsFile := filepath.Join(logsDir, logsPrefix+"bazel_metrics.pb")
  211. //Delete the stale metrics files
  212. staleFileSlice := []string{buildErrorFile, rbeMetricsFile, soongMetricsFile, bp2buildMetricsFile, soongBuildMetricsFile, bazelMetricsFile}
  213. if err := deleteStaleMetrics(staleFileSlice); err != nil {
  214. log.Fatalln(err)
  215. }
  216. build.PrintOutDirWarning(buildCtx, config)
  217. stat := buildCtx.Status
  218. stat.AddOutput(status.NewVerboseLog(log, filepath.Join(logsDir, logsPrefix+"verbose.log")))
  219. stat.AddOutput(status.NewErrorLog(log, filepath.Join(logsDir, logsPrefix+"error.log")))
  220. stat.AddOutput(status.NewProtoErrorLog(log, buildErrorFile))
  221. stat.AddOutput(status.NewCriticalPathLogger(log, buildCtx.CriticalPath))
  222. stat.AddOutput(status.NewBuildProgressLog(log, filepath.Join(logsDir, logsPrefix+"build_progress.pb")))
  223. buildCtx.Verbosef("Detected %.3v GB total RAM", float32(config.TotalRAM())/(1024*1024*1024))
  224. buildCtx.Verbosef("Parallelism (local/remote/highmem): %v/%v/%v",
  225. config.Parallel(), config.RemoteParallel(), config.HighmemParallel())
  226. setMaxFiles(buildCtx)
  227. defer build.CheckProdCreds(buildCtx, config)
  228. // Read the time at the starting point.
  229. if start, ok := os.LookupEnv("TRACE_BEGIN_SOONG"); ok {
  230. // soong_ui.bash uses the date command's %N (nanosec) flag when getting the start time,
  231. // which Darwin doesn't support. Check if it was executed properly before parsing the value.
  232. if !strings.HasSuffix(start, "N") {
  233. if start_time, err := strconv.ParseUint(start, 10, 64); err == nil {
  234. log.Verbosef("Took %dms to start up.",
  235. time.Since(time.Unix(0, int64(start_time))).Nanoseconds()/time.Millisecond.Nanoseconds())
  236. buildCtx.CompleteTrace(metrics.RunSetupTool, "startup", start_time, uint64(time.Now().UnixNano()))
  237. }
  238. }
  239. if executable, err := os.Executable(); err == nil {
  240. buildCtx.ContextImpl.Tracer.ImportMicrofactoryLog(filepath.Join(filepath.Dir(executable), "."+filepath.Base(executable)+".trace"))
  241. }
  242. }
  243. // Fix up the source tree due to a repo bug where it doesn't remove
  244. // linkfiles that have been removed
  245. fixBadDanglingLink(buildCtx, "hardware/qcom/sdm710/Android.bp")
  246. fixBadDanglingLink(buildCtx, "hardware/qcom/sdm710/Android.mk")
  247. // Create a source finder.
  248. f := build.NewSourceFinder(buildCtx, config)
  249. defer f.Shutdown()
  250. build.FindSources(buildCtx, config, f)
  251. }
  252. func fixBadDanglingLink(ctx build.Context, name string) {
  253. _, err := os.Lstat(name)
  254. if err != nil {
  255. return
  256. }
  257. _, err = os.Stat(name)
  258. if os.IsNotExist(err) {
  259. err = os.Remove(name)
  260. if err != nil {
  261. ctx.Fatalf("Failed to remove dangling link %q: %v", name, err)
  262. }
  263. }
  264. }
  265. func dumpVar(ctx build.Context, config build.Config, args []string) {
  266. logAndSymlinkSetup(ctx, config)
  267. flags := flag.NewFlagSet("dumpvar", flag.ExitOnError)
  268. flags.SetOutput(ctx.Writer)
  269. flags.Usage = func() {
  270. fmt.Fprintf(ctx.Writer, "usage: %s --dumpvar-mode [--abs] <VAR>\n\n", os.Args[0])
  271. fmt.Fprintln(ctx.Writer, "In dumpvar mode, print the value of the legacy make variable VAR to stdout")
  272. fmt.Fprintln(ctx.Writer, "")
  273. fmt.Fprintln(ctx.Writer, "'report_config' is a special case that prints the human-readable config banner")
  274. fmt.Fprintln(ctx.Writer, "from the beginning of the build.")
  275. fmt.Fprintln(ctx.Writer, "")
  276. flags.PrintDefaults()
  277. }
  278. abs := flags.Bool("abs", false, "Print the absolute path of the value")
  279. flags.Parse(args)
  280. if flags.NArg() != 1 {
  281. flags.Usage()
  282. ctx.Fatalf("Invalid usage")
  283. }
  284. varName := flags.Arg(0)
  285. if varName == "report_config" {
  286. varData, err := build.DumpMakeVars(ctx, config, nil, build.BannerVars)
  287. if err != nil {
  288. ctx.Fatal(err)
  289. }
  290. fmt.Println(build.Banner(varData))
  291. } else {
  292. varData, err := build.DumpMakeVars(ctx, config, nil, []string{varName})
  293. if err != nil {
  294. ctx.Fatal(err)
  295. }
  296. if *abs {
  297. var res []string
  298. for _, path := range strings.Fields(varData[varName]) {
  299. if abs, err := filepath.Abs(path); err == nil {
  300. res = append(res, abs)
  301. } else {
  302. ctx.Fatalln("Failed to get absolute path of", path, err)
  303. }
  304. }
  305. fmt.Println(strings.Join(res, " "))
  306. } else {
  307. fmt.Println(varData[varName])
  308. }
  309. }
  310. }
  311. func dumpVars(ctx build.Context, config build.Config, args []string) {
  312. logAndSymlinkSetup(ctx, config)
  313. flags := flag.NewFlagSet("dumpvars", flag.ExitOnError)
  314. flags.SetOutput(ctx.Writer)
  315. flags.Usage = func() {
  316. fmt.Fprintf(ctx.Writer, "usage: %s --dumpvars-mode [--vars=\"VAR VAR ...\"]\n\n", os.Args[0])
  317. fmt.Fprintln(ctx.Writer, "In dumpvars mode, dump the values of one or more legacy make variables, in")
  318. fmt.Fprintln(ctx.Writer, "shell syntax. The resulting output may be sourced directly into a shell to")
  319. fmt.Fprintln(ctx.Writer, "set corresponding shell variables.")
  320. fmt.Fprintln(ctx.Writer, "")
  321. fmt.Fprintln(ctx.Writer, "'report_config' is a special case that dumps a variable containing the")
  322. fmt.Fprintln(ctx.Writer, "human-readable config banner from the beginning of the build.")
  323. fmt.Fprintln(ctx.Writer, "")
  324. flags.PrintDefaults()
  325. }
  326. varsStr := flags.String("vars", "", "Space-separated list of variables to dump")
  327. absVarsStr := flags.String("abs-vars", "", "Space-separated list of variables to dump (using absolute paths)")
  328. varPrefix := flags.String("var-prefix", "", "String to prepend to all variable names when dumping")
  329. absVarPrefix := flags.String("abs-var-prefix", "", "String to prepent to all absolute path variable names when dumping")
  330. flags.Parse(args)
  331. if flags.NArg() != 0 {
  332. flags.Usage()
  333. ctx.Fatalf("Invalid usage")
  334. }
  335. vars := strings.Fields(*varsStr)
  336. absVars := strings.Fields(*absVarsStr)
  337. allVars := append([]string{}, vars...)
  338. allVars = append(allVars, absVars...)
  339. if i := indexList("report_config", allVars); i != -1 {
  340. allVars = append(allVars[:i], allVars[i+1:]...)
  341. allVars = append(allVars, build.BannerVars...)
  342. }
  343. if len(allVars) == 0 {
  344. return
  345. }
  346. varData, err := build.DumpMakeVars(ctx, config, nil, allVars)
  347. if err != nil {
  348. ctx.Fatal(err)
  349. }
  350. for _, name := range vars {
  351. if name == "report_config" {
  352. fmt.Printf("%sreport_config='%s'\n", *varPrefix, build.Banner(varData))
  353. } else {
  354. fmt.Printf("%s%s='%s'\n", *varPrefix, name, varData[name])
  355. }
  356. }
  357. for _, name := range absVars {
  358. var res []string
  359. for _, path := range strings.Fields(varData[name]) {
  360. abs, err := filepath.Abs(path)
  361. if err != nil {
  362. ctx.Fatalln("Failed to get absolute path of", path, err)
  363. }
  364. res = append(res, abs)
  365. }
  366. fmt.Printf("%s%s='%s'\n", *absVarPrefix, name, strings.Join(res, " "))
  367. }
  368. }
  369. func stdio() terminal.StdioInterface {
  370. return terminal.StdioImpl{}
  371. }
  372. // dumpvar and dumpvars use stdout to output variable values, so use stderr instead of stdout when
  373. // reporting events to keep stdout clean from noise.
  374. func customStdio() terminal.StdioInterface {
  375. return terminal.NewCustomStdio(os.Stdin, os.Stderr, os.Stderr)
  376. }
  377. // dumpVarConfig does not require any arguments to be parsed by the NewConfig.
  378. func dumpVarConfig(ctx build.Context, args ...string) build.Config {
  379. return build.NewConfig(ctx)
  380. }
  381. func buildActionConfig(ctx build.Context, args ...string) build.Config {
  382. flags := flag.NewFlagSet("build-mode", flag.ContinueOnError)
  383. flags.SetOutput(ctx.Writer)
  384. flags.Usage = func() {
  385. fmt.Fprintf(ctx.Writer, "usage: %s --build-mode --dir=<path> <build action> [<build arg 1> <build arg 2> ...]\n\n", os.Args[0])
  386. fmt.Fprintln(ctx.Writer, "In build mode, build the set of modules based on the specified build")
  387. fmt.Fprintln(ctx.Writer, "action. The --dir flag is required to determine what is needed to")
  388. fmt.Fprintln(ctx.Writer, "build in the source tree based on the build action. See below for")
  389. fmt.Fprintln(ctx.Writer, "the list of acceptable build action flags.")
  390. fmt.Fprintln(ctx.Writer, "")
  391. flags.PrintDefaults()
  392. }
  393. buildActionFlags := []struct {
  394. name string
  395. description string
  396. action build.BuildAction
  397. set bool
  398. }{{
  399. name: "all-modules",
  400. description: "Build action: build from the top of the source tree.",
  401. action: build.BUILD_MODULES,
  402. }, {
  403. // This is redirecting to mma build command behaviour. Once it has soaked for a
  404. // while, the build command is deleted from here once it has been removed from the
  405. // envsetup.sh.
  406. name: "modules-in-a-dir-no-deps",
  407. description: "Build action: builds all of the modules in the current directory without their dependencies.",
  408. action: build.BUILD_MODULES_IN_A_DIRECTORY,
  409. }, {
  410. // This is redirecting to mmma build command behaviour. Once it has soaked for a
  411. // while, the build command is deleted from here once it has been removed from the
  412. // envsetup.sh.
  413. name: "modules-in-dirs-no-deps",
  414. description: "Build action: builds all of the modules in the supplied directories without their dependencies.",
  415. action: build.BUILD_MODULES_IN_DIRECTORIES,
  416. }, {
  417. name: "modules-in-a-dir",
  418. description: "Build action: builds all of the modules in the current directory and their dependencies.",
  419. action: build.BUILD_MODULES_IN_A_DIRECTORY,
  420. }, {
  421. name: "modules-in-dirs",
  422. description: "Build action: builds all of the modules in the supplied directories and their dependencies.",
  423. action: build.BUILD_MODULES_IN_DIRECTORIES,
  424. }}
  425. for i, flag := range buildActionFlags {
  426. flags.BoolVar(&buildActionFlags[i].set, flag.name, false, flag.description)
  427. }
  428. dir := flags.String("dir", "", "Directory of the executed build command.")
  429. // Only interested in the first two args which defines the build action and the directory.
  430. // The remaining arguments are passed down to the config.
  431. const numBuildActionFlags = 2
  432. if len(args) < numBuildActionFlags {
  433. flags.Usage()
  434. ctx.Fatalln("Improper build action arguments: too few arguments")
  435. }
  436. parseError := flags.Parse(args[0:numBuildActionFlags])
  437. // The next block of code is to validate that exactly one build action is set and the dir flag
  438. // is specified.
  439. buildActionFound := false
  440. var buildAction build.BuildAction
  441. for _, f := range buildActionFlags {
  442. if f.set {
  443. if buildActionFound {
  444. if parseError == nil {
  445. //otherwise Parse() already called Usage()
  446. flags.Usage()
  447. }
  448. ctx.Fatalf("Build action already specified, omit: --%s\n", f.name)
  449. }
  450. buildActionFound = true
  451. buildAction = f.action
  452. }
  453. }
  454. if !buildActionFound {
  455. if parseError == nil {
  456. //otherwise Parse() already called Usage()
  457. flags.Usage()
  458. }
  459. ctx.Fatalln("Build action not defined.")
  460. }
  461. if *dir == "" {
  462. ctx.Fatalln("-dir not specified.")
  463. }
  464. // Remove the build action flags from the args as they are not recognized by the config.
  465. args = args[numBuildActionFlags:]
  466. return build.NewBuildActionConfig(buildAction, *dir, ctx, args...)
  467. }
  468. func runMake(ctx build.Context, config build.Config, _ []string) {
  469. logAndSymlinkSetup(ctx, config)
  470. logsDir := config.LogsDir()
  471. if config.IsVerbose() {
  472. writer := ctx.Writer
  473. fmt.Fprintln(writer, "! The argument `showcommands` is no longer supported.")
  474. fmt.Fprintln(writer, "! Instead, the verbose log is always written to a compressed file in the output dir:")
  475. fmt.Fprintln(writer, "!")
  476. fmt.Fprintf(writer, "! gzip -cd %s/verbose.log.gz | less -R\n", logsDir)
  477. fmt.Fprintln(writer, "!")
  478. fmt.Fprintln(writer, "! Older versions are saved in verbose.log.#.gz files")
  479. fmt.Fprintln(writer, "")
  480. ctx.Fatal("Invalid argument")
  481. }
  482. if _, ok := config.Environment().Get("ONE_SHOT_MAKEFILE"); ok {
  483. writer := ctx.Writer
  484. fmt.Fprintln(writer, "! The variable `ONE_SHOT_MAKEFILE` is obsolete.")
  485. fmt.Fprintln(writer, "!")
  486. fmt.Fprintln(writer, "! If you're using `mm`, you'll need to run `source build/envsetup.sh` to update.")
  487. fmt.Fprintln(writer, "!")
  488. fmt.Fprintln(writer, "! Otherwise, either specify a module name with m, or use mma / MODULES-IN-...")
  489. fmt.Fprintln(writer, "")
  490. ctx.Fatal("Invalid environment")
  491. }
  492. build.Build(ctx, config)
  493. }
  494. // getCommand finds the appropriate command based on args[1] flag. args[0]
  495. // is the soong_ui filename.
  496. func getCommand(args []string) (*command, []string, error) {
  497. listFlags := func() []string {
  498. flags := make([]string, len(commands))
  499. for i, c := range commands {
  500. flags[i] = c.flag
  501. }
  502. return flags
  503. }
  504. if len(args) < 2 {
  505. return nil, nil, fmt.Errorf("Too few arguments: %q\nUse one of these: %q", args, listFlags())
  506. }
  507. for _, c := range commands {
  508. if c.flag == args[1] {
  509. return &c, args[2:], nil
  510. }
  511. }
  512. return nil, nil, fmt.Errorf("Command not found: %q\nDid you mean one of these: %q", args[1], listFlags())
  513. }
  514. // For Bazel support, this moves files and directories from e.g. out/dist/$f to DIST_DIR/$f if necessary.
  515. func populateExternalDistDir(ctx build.Context, config build.Config) {
  516. // Make sure that internalDistDirPath and externalDistDirPath are both absolute paths, so we can compare them
  517. var err error
  518. var internalDistDirPath string
  519. var externalDistDirPath string
  520. if internalDistDirPath, err = filepath.Abs(config.DistDir()); err != nil {
  521. ctx.Fatalf("Unable to find absolute path of %s: %s", internalDistDirPath, err)
  522. }
  523. if externalDistDirPath, err = filepath.Abs(config.RealDistDir()); err != nil {
  524. ctx.Fatalf("Unable to find absolute path of %s: %s", externalDistDirPath, err)
  525. }
  526. if externalDistDirPath == internalDistDirPath {
  527. return
  528. }
  529. // Make sure the internal DIST_DIR actually exists before trying to read from it
  530. if _, err = os.Stat(internalDistDirPath); os.IsNotExist(err) {
  531. ctx.Println("Skipping Bazel dist dir migration - nothing to do!")
  532. return
  533. }
  534. // Make sure the external DIST_DIR actually exists before trying to write to it
  535. if err = os.MkdirAll(externalDistDirPath, 0755); err != nil {
  536. ctx.Fatalf("Unable to make directory %s: %s", externalDistDirPath, err)
  537. }
  538. ctx.Println("Populating external DIST_DIR...")
  539. populateExternalDistDirHelper(ctx, config, internalDistDirPath, externalDistDirPath)
  540. }
  541. func populateExternalDistDirHelper(ctx build.Context, config build.Config, internalDistDirPath string, externalDistDirPath string) {
  542. files, err := ioutil.ReadDir(internalDistDirPath)
  543. if err != nil {
  544. ctx.Fatalf("Can't read internal distdir %s: %s", internalDistDirPath, err)
  545. }
  546. for _, f := range files {
  547. internalFilePath := filepath.Join(internalDistDirPath, f.Name())
  548. externalFilePath := filepath.Join(externalDistDirPath, f.Name())
  549. if f.IsDir() {
  550. // Moving a directory - check if there is an existing directory to merge with
  551. externalLstat, err := os.Lstat(externalFilePath)
  552. if err != nil {
  553. if !os.IsNotExist(err) {
  554. ctx.Fatalf("Can't lstat external %s: %s", externalDistDirPath, err)
  555. }
  556. // Otherwise, if the error was os.IsNotExist, that's fine and we fall through to the rename at the bottom
  557. } else {
  558. if externalLstat.IsDir() {
  559. // Existing dir - try to merge the directories?
  560. populateExternalDistDirHelper(ctx, config, internalFilePath, externalFilePath)
  561. continue
  562. } else {
  563. // Existing file being replaced with a directory. Delete the existing file...
  564. if err := os.RemoveAll(externalFilePath); err != nil {
  565. ctx.Fatalf("Unable to remove existing %s: %s", externalFilePath, err)
  566. }
  567. }
  568. }
  569. } else {
  570. // Moving a file (not a dir) - delete any existing file or directory
  571. if err := os.RemoveAll(externalFilePath); err != nil {
  572. ctx.Fatalf("Unable to remove existing %s: %s", externalFilePath, err)
  573. }
  574. }
  575. // The actual move - do a rename instead of a copy in order to save disk space.
  576. if err := os.Rename(internalFilePath, externalFilePath); err != nil {
  577. ctx.Fatalf("Unable to rename %s -> %s due to error %s", internalFilePath, externalFilePath, err)
  578. }
  579. }
  580. }
  581. func setMaxFiles(ctx build.Context) {
  582. var limits syscall.Rlimit
  583. err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &limits)
  584. if err != nil {
  585. ctx.Println("Failed to get file limit:", err)
  586. return
  587. }
  588. ctx.Verbosef("Current file limits: %d soft, %d hard", limits.Cur, limits.Max)
  589. if limits.Cur == limits.Max {
  590. return
  591. }
  592. limits.Cur = limits.Max
  593. err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &limits)
  594. if err != nil {
  595. ctx.Println("Failed to increase file limit:", err)
  596. }
  597. }
  598. func finalizeBazelMetrics(ctx build.Context, config build.Config, args []string) {
  599. updateTotalRealTime(ctx, config, args)
  600. logsDir := config.LogsDir()
  601. logsPrefix := config.GetLogsPrefix()
  602. bazelMetricsFile := filepath.Join(logsDir, logsPrefix+"bazel_metrics.pb")
  603. bazelProfileFile := filepath.Join(logsDir, logsPrefix+"analyzed_bazel_profile.txt")
  604. build.ProcessBazelMetrics(bazelProfileFile, bazelMetricsFile, ctx, config)
  605. }
  606. func updateTotalRealTime(ctx build.Context, config build.Config, args []string) {
  607. soongMetricsFile := filepath.Join(config.LogsDir(), "soong_metrics")
  608. //read file into proto
  609. data, err := os.ReadFile(soongMetricsFile)
  610. if err != nil {
  611. ctx.Fatal(err)
  612. }
  613. met := ctx.ContextImpl.Metrics
  614. err = met.UpdateTotalRealTimeAndNonZeroExit(data, config.BazelExitCode())
  615. if err != nil {
  616. ctx.Fatal(err)
  617. }
  618. }