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