blob: 4f2d6455c0c17649cc8e0e451caa65d4bc36ca3a [file] [log] [blame]
Rupert Shuttleworth680387b2020-10-25 12:31:27 +00001// Copyright 2020 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 build
16
17import (
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000018 "bytes"
19 "fmt"
Chris Parsonsc09495b2020-11-04 20:45:50 -050020 "io/ioutil"
21 "os"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000022 "path/filepath"
23 "strings"
Patrice Arruda18cb70d2020-11-13 11:37:06 -080024
25 "android/soong/shared"
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080026 "android/soong/ui/metrics"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000027)
28
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000029func getBazelInfo(ctx Context, config Config, bazelExecutable string, bazelEnv map[string]string, query string) string {
Rupert Shuttleworthad532f22020-12-04 08:41:14 +000030 infoCmd := Command(ctx, config, "bazel", bazelExecutable)
31
32 if extraStartupArgs, ok := infoCmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
33 infoCmd.Args = append(infoCmd.Args, strings.Fields(extraStartupArgs)...)
34 }
35
36 // Obtain the output directory path in the execution root.
37 infoCmd.Args = append(infoCmd.Args,
38 "info",
39 query,
40 )
41
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000042 for k, v := range bazelEnv {
43 infoCmd.Environment.Set(k, v)
44 }
Rupert Shuttleworthad532f22020-12-04 08:41:14 +000045
46 infoCmd.Dir = filepath.Join(config.OutDir(), "..")
47
48 queryResult := strings.TrimSpace(string(infoCmd.OutputOrFatal()))
49 return queryResult
50}
51
Jingwen Chen7a5391a2020-11-17 03:42:12 -050052// Main entry point to construct the Bazel build command line, environment
53// variables and post-processing steps (e.g. converge output directories)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000054func runBazel(ctx Context, config Config) {
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080055 ctx.BeginTrace(metrics.RunBazel, "bazel")
56 defer ctx.EndTrace()
57
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000058 // "droid" is the default ninja target.
Jingwen Chen8024c952020-11-08 23:57:56 -050059 // TODO(b/160568333): stop hardcoding 'droid' to support building any
60 // Ninja target.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000061 outputGroups := "droid"
62 if len(config.ninjaArgs) > 0 {
63 // At this stage, the residue slice of args passed to ninja
64 // are the ninja targets to build, which can correspond directly
65 // to ninja_build's output_groups.
66 outputGroups = strings.Join(config.ninjaArgs, ",")
67 }
68
Jingwen Chen7a5391a2020-11-17 03:42:12 -050069 // Environment variables are the primary mechanism to pass information from
70 // soong_ui configuration or context to Bazel.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000071 bazelEnv := make(map[string]string)
72
Jingwen Chen7a5391a2020-11-17 03:42:12 -050073 // Use *_NINJA variables to pass the root-relative path of the combined,
74 // kati-generated, soong-generated, and packaging Ninja files to Bazel.
75 // Bazel reads these from the lunch() repository rule.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000076 bazelEnv["COMBINED_NINJA"] = config.CombinedNinjaFile()
77 bazelEnv["KATI_NINJA"] = config.KatiBuildNinjaFile()
78 bazelEnv["PACKAGE_NINJA"] = config.KatiPackageNinjaFile()
79 bazelEnv["SOONG_NINJA"] = config.SoongNinjaFile()
80
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000081 // NOTE: When Bazel is used, config.DistDir() is rigged to return a fake distdir under config.OutDir()
82 // This is to ensure that Bazel can actually write there. See config.go for more details.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000083 bazelEnv["DIST_DIR"] = config.DistDir()
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000084
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000085 bazelEnv["SHELL"] = "/bin/bash"
Jingwen Chena26ac3c2020-11-10 08:17:59 -050086
Jingwen Chen7a5391a2020-11-17 03:42:12 -050087 // `tools/bazel` is the default entry point for executing Bazel in the AOSP
88 // source tree.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000089 bazelExecutable := filepath.Join("tools", "bazel")
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000090 cmd := Command(ctx, config, "bazel", bazelExecutable)
91
Jingwen Chen7a5391a2020-11-17 03:42:12 -050092 // Append custom startup flags to the Bazel command. Startup flags affect
93 // the Bazel server itself, and any changes to these flags would incur a
94 // restart of the server, losing much of the in-memory incrementality.
95 if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
96 cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000097 }
98
Jingwen Chen7a5391a2020-11-17 03:42:12 -050099 // Start constructing the `build` command.
Patrice Arruda18cb70d2020-11-13 11:37:06 -0800100 actionName := "build"
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000101 cmd.Args = append(cmd.Args,
Patrice Arruda18cb70d2020-11-13 11:37:06 -0800102 actionName,
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500103 // Use output_groups to select the set of outputs to produce from a
104 // ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000105 "--output_groups="+outputGroups,
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500106 // Generate a performance profile
Patrice Arruda83842d72020-12-08 19:42:08 +0000107 "--profile="+filepath.Join(shared.BazelMetricsFilename(config, actionName)),
Patrice Arruda18cb70d2020-11-13 11:37:06 -0800108 "--slim_profile=true",
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000109 )
110
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000111 if config.UseRBE() {
112 for _, envVar := range []string{
113 // RBE client
114 "RBE_compare",
115 "RBE_exec_strategy",
116 "RBE_invocation_id",
117 "RBE_log_dir",
118 "RBE_platform",
119 "RBE_remote_accept_cache",
120 "RBE_remote_update_cache",
121 "RBE_server_address",
122 // TODO: remove old FLAG_ variables.
123 "FLAG_compare",
124 "FLAG_exec_root",
125 "FLAG_exec_strategy",
126 "FLAG_invocation_id",
127 "FLAG_log_dir",
128 "FLAG_platform",
129 "FLAG_remote_accept_cache",
130 "FLAG_remote_update_cache",
131 "FLAG_server_address",
132 } {
133 cmd.Args = append(cmd.Args,
134 "--action_env="+envVar)
135 }
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000136
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000137 // We need to calculate --RBE_exec_root ourselves
138 ctx.Println("Getting Bazel execution_root...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000139 cmd.Args = append(cmd.Args, "--action_env=RBE_exec_root="+getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "execution_root"))
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000140 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000141
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500142 // Ensure that the PATH environment variable value used in the action
143 // environment is the restricted set computed from soong_ui, and not a
144 // user-provided one, for hermeticity reasons.
Jingwen Chen3a4b58d2020-11-16 04:19:35 -0500145 if pathEnvValue, ok := config.environ.Get("PATH"); ok {
146 cmd.Environment.Set("PATH", pathEnvValue)
147 cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
148 }
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500149
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000150 // Append custom build flags to the Bazel command. Changes to these flags
151 // may invalidate Bazel's analysis cache.
152 // These should be appended as the final args, so that they take precedence.
153 if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
154 cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
155 }
156
157 // Append the label of the default ninja_build target.
158 cmd.Args = append(cmd.Args,
159 "//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
160 )
161
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500162 // Execute the command at the root of the directory.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000163 cmd.Dir = filepath.Join(config.OutDir(), "..")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000164
165 for k, v := range bazelEnv {
166 cmd.Environment.Set(k, v)
167 }
168
169 // Make a human-readable version of the bazelEnv map
170 bazelEnvStringBuffer := new(bytes.Buffer)
171 for k, v := range bazelEnv {
172 fmt.Fprintf(bazelEnvStringBuffer, "%s=%s ", k, v)
173 }
174
Rupert Shuttleworth72f72b42020-12-08 06:12:00 +0000175 // Print the implicit command line
176 ctx.Println("Bazel implicit command line: " + strings.Join(cmd.Environment.Environ(), " ") + " " + cmd.Cmd.String() + "\n")
177
178 // Print the explicit command line too
179 ctx.Println("Bazel explicit command line: " + bazelEnvStringBuffer.String() + cmd.Cmd.String() + "\n")
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500180
181 // Execute the build command.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000182 cmd.RunAndStreamOrFatal()
Chris Parsonsc09495b2020-11-04 20:45:50 -0500183
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500184 // Post-processing steps start here. Once the Bazel build completes, the
185 // output files are still stored in the execution root, not in $OUT_DIR.
186 // Ensure that the $OUT_DIR contains the expected set of files by symlinking
187 // the files from the execution root's output direction into $OUT_DIR.
188
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000189 ctx.Println("Getting Bazel output_path...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000190 outputBasePath := getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "output_path")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500191 // TODO: Don't hardcode out/ as the bazel output directory. This is
192 // currently hardcoded as ninja_build.output_root.
193 bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
194
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000195 ctx.Println("Populating output directory...")
196 populateOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500197}
198
199// For all files F recursively under rootPath/relativePath, creates symlinks
200// such that OutDir/F resolves to rootPath/F via symlinks.
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000201// NOTE: For distdir paths we rename files instead of creating symlinks, so that the distdir is independent.
202func populateOutdir(ctx Context, config Config, rootPath string, relativePath string) {
Chris Parsonsc09495b2020-11-04 20:45:50 -0500203 destDir := filepath.Join(rootPath, relativePath)
204 os.MkdirAll(destDir, 0755)
205 files, err := ioutil.ReadDir(destDir)
206 if err != nil {
207 ctx.Fatal(err)
208 }
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000209
Chris Parsonsc09495b2020-11-04 20:45:50 -0500210 for _, f := range files {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000211 // The original Bazel file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500212 destPath := filepath.Join(destDir, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000213
214 // The desired Soong file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500215 srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000216
217 destLstatResult, destLstatErr := os.Lstat(destPath)
218 if destLstatErr != nil {
219 ctx.Fatalf("Unable to Lstat dest %s: %s", destPath, destLstatErr)
220 }
221
222 srcLstatResult, srcLstatErr := os.Lstat(srcPath)
223
224 if srcLstatErr == nil {
225 if srcLstatResult.IsDir() && destLstatResult.IsDir() {
226 // src and dest are both existing dirs - recurse on the dest dir contents...
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000227 populateOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
Chris Parsonsc09495b2020-11-04 20:45:50 -0500228 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000229 // Ignore other pre-existing src files (could be pre-existing files, directories, symlinks, ...)
230 // This can arise for files which are generated under OutDir outside of soong_build, such as .bootstrap files.
231 // FIXME: This might cause a problem later e.g. if a symlink in the build graph changes...
Chris Parsonsc09495b2020-11-04 20:45:50 -0500232 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500233 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000234 if !os.IsNotExist(srcLstatErr) {
235 ctx.Fatalf("Unable to Lstat src %s: %s", srcPath, srcLstatErr)
236 }
237
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000238 if strings.Contains(destDir, config.DistDir()) {
239 // We need to make a "real" file/dir instead of making a symlink (because the distdir can't have symlinks)
240 // Rename instead of copy in order to save disk space.
241 if err := os.Rename(destPath, srcPath); err != nil {
242 ctx.Fatalf("Unable to rename %s -> %s due to error %s", srcPath, destPath, err)
243 }
244 } else {
245 // src does not exist, so try to create a src -> dest symlink (i.e. a Soong path -> Bazel path symlink)
246 if err := os.Symlink(destPath, srcPath); err != nil {
247 ctx.Fatalf("Unable to create symlink %s -> %s due to error %s", srcPath, destPath, err)
248 }
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000249 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500250 }
251 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000252}