blob: 81ce9397a7773d6262f6398ca737d46a37769154 [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
Patrice Arruda05ab2d02020-12-12 06:24:26 +000025 "android/soong/bazel"
Patrice Arruda18cb70d2020-11-13 11:37:06 -080026 "android/soong/shared"
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080027 "android/soong/ui/metrics"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000028)
29
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000030func getBazelInfo(ctx Context, config Config, bazelExecutable string, bazelEnv map[string]string, query string) string {
Rupert Shuttleworthad532f22020-12-04 08:41:14 +000031 infoCmd := Command(ctx, config, "bazel", bazelExecutable)
32
33 if extraStartupArgs, ok := infoCmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
34 infoCmd.Args = append(infoCmd.Args, strings.Fields(extraStartupArgs)...)
35 }
36
37 // Obtain the output directory path in the execution root.
38 infoCmd.Args = append(infoCmd.Args,
39 "info",
40 query,
41 )
42
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000043 for k, v := range bazelEnv {
44 infoCmd.Environment.Set(k, v)
45 }
Rupert Shuttleworthad532f22020-12-04 08:41:14 +000046
47 infoCmd.Dir = filepath.Join(config.OutDir(), "..")
48
49 queryResult := strings.TrimSpace(string(infoCmd.OutputOrFatal()))
50 return queryResult
51}
52
Jingwen Chen7a5391a2020-11-17 03:42:12 -050053// Main entry point to construct the Bazel build command line, environment
54// variables and post-processing steps (e.g. converge output directories)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000055func runBazel(ctx Context, config Config) {
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080056 ctx.BeginTrace(metrics.RunBazel, "bazel")
57 defer ctx.EndTrace()
58
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000059 // "droid" is the default ninja target.
Jingwen Chen8024c952020-11-08 23:57:56 -050060 // TODO(b/160568333): stop hardcoding 'droid' to support building any
61 // Ninja target.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000062 outputGroups := "droid"
63 if len(config.ninjaArgs) > 0 {
64 // At this stage, the residue slice of args passed to ninja
65 // are the ninja targets to build, which can correspond directly
66 // to ninja_build's output_groups.
67 outputGroups = strings.Join(config.ninjaArgs, ",")
68 }
69
Jingwen Chen7a5391a2020-11-17 03:42:12 -050070 // Environment variables are the primary mechanism to pass information from
71 // soong_ui configuration or context to Bazel.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000072 bazelEnv := make(map[string]string)
73
Jingwen Chen7a5391a2020-11-17 03:42:12 -050074 // Use *_NINJA variables to pass the root-relative path of the combined,
75 // kati-generated, soong-generated, and packaging Ninja files to Bazel.
76 // Bazel reads these from the lunch() repository rule.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000077 bazelEnv["COMBINED_NINJA"] = config.CombinedNinjaFile()
78 bazelEnv["KATI_NINJA"] = config.KatiBuildNinjaFile()
79 bazelEnv["PACKAGE_NINJA"] = config.KatiPackageNinjaFile()
80 bazelEnv["SOONG_NINJA"] = config.SoongNinjaFile()
81
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000082 // NOTE: When Bazel is used, config.DistDir() is rigged to return a fake distdir under config.OutDir()
83 // This is to ensure that Bazel can actually write there. See config.go for more details.
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000084 bazelEnv["DIST_DIR"] = config.DistDir()
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +000085
Rupert Shuttleworth947ed972020-12-04 19:31:02 +000086 bazelEnv["SHELL"] = "/bin/bash"
Jingwen Chena26ac3c2020-11-10 08:17:59 -050087
Jingwen Chen7a5391a2020-11-17 03:42:12 -050088 // `tools/bazel` is the default entry point for executing Bazel in the AOSP
89 // source tree.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000090 bazelExecutable := filepath.Join("tools", "bazel")
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000091 cmd := Command(ctx, config, "bazel", bazelExecutable)
92
Jingwen Chen7a5391a2020-11-17 03:42:12 -050093 // Append custom startup flags to the Bazel command. Startup flags affect
94 // the Bazel server itself, and any changes to these flags would incur a
95 // restart of the server, losing much of the in-memory incrementality.
96 if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
97 cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000098 }
99
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500100 // Start constructing the `build` command.
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000101 actionName := bazel.BazelNinjaExecRunName
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000102 cmd.Args = append(cmd.Args,
Patrice Arruda05ab2d02020-12-12 06:24:26 +0000103 "build",
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500104 // Use output_groups to select the set of outputs to produce from a
105 // ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000106 "--output_groups="+outputGroups,
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500107 // Generate a performance profile
Patrice Arruda83842d72020-12-08 19:42:08 +0000108 "--profile="+filepath.Join(shared.BazelMetricsFilename(config, actionName)),
Patrice Arruda18cb70d2020-11-13 11:37:06 -0800109 "--slim_profile=true",
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000110 )
111
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000112 if config.UseRBE() {
113 for _, envVar := range []string{
114 // RBE client
115 "RBE_compare",
116 "RBE_exec_strategy",
117 "RBE_invocation_id",
118 "RBE_log_dir",
119 "RBE_platform",
120 "RBE_remote_accept_cache",
121 "RBE_remote_update_cache",
122 "RBE_server_address",
123 // TODO: remove old FLAG_ variables.
124 "FLAG_compare",
125 "FLAG_exec_root",
126 "FLAG_exec_strategy",
127 "FLAG_invocation_id",
128 "FLAG_log_dir",
129 "FLAG_platform",
130 "FLAG_remote_accept_cache",
131 "FLAG_remote_update_cache",
132 "FLAG_server_address",
133 } {
134 cmd.Args = append(cmd.Args,
135 "--action_env="+envVar)
136 }
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000137
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000138 // We need to calculate --RBE_exec_root ourselves
139 ctx.Println("Getting Bazel execution_root...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000140 cmd.Args = append(cmd.Args, "--action_env=RBE_exec_root="+getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "execution_root"))
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000141 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000142
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500143 // Ensure that the PATH environment variable value used in the action
144 // environment is the restricted set computed from soong_ui, and not a
145 // user-provided one, for hermeticity reasons.
Jingwen Chen3a4b58d2020-11-16 04:19:35 -0500146 if pathEnvValue, ok := config.environ.Get("PATH"); ok {
147 cmd.Environment.Set("PATH", pathEnvValue)
148 cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
149 }
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500150
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000151 // Append custom build flags to the Bazel command. Changes to these flags
152 // may invalidate Bazel's analysis cache.
153 // These should be appended as the final args, so that they take precedence.
154 if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
155 cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
156 }
157
158 // Append the label of the default ninja_build target.
159 cmd.Args = append(cmd.Args,
160 "//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
161 )
162
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500163 // Execute the command at the root of the directory.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000164 cmd.Dir = filepath.Join(config.OutDir(), "..")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000165
166 for k, v := range bazelEnv {
167 cmd.Environment.Set(k, v)
168 }
169
170 // Make a human-readable version of the bazelEnv map
171 bazelEnvStringBuffer := new(bytes.Buffer)
172 for k, v := range bazelEnv {
173 fmt.Fprintf(bazelEnvStringBuffer, "%s=%s ", k, v)
174 }
175
Rupert Shuttleworth72f72b42020-12-08 06:12:00 +0000176 // Print the implicit command line
177 ctx.Println("Bazel implicit command line: " + strings.Join(cmd.Environment.Environ(), " ") + " " + cmd.Cmd.String() + "\n")
178
179 // Print the explicit command line too
180 ctx.Println("Bazel explicit command line: " + bazelEnvStringBuffer.String() + cmd.Cmd.String() + "\n")
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500181
182 // Execute the build command.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000183 cmd.RunAndStreamOrFatal()
Chris Parsonsc09495b2020-11-04 20:45:50 -0500184
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500185 // Post-processing steps start here. Once the Bazel build completes, the
186 // output files are still stored in the execution root, not in $OUT_DIR.
187 // Ensure that the $OUT_DIR contains the expected set of files by symlinking
188 // the files from the execution root's output direction into $OUT_DIR.
189
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000190 ctx.Println("Getting Bazel output_path...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000191 outputBasePath := getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "output_path")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500192 // TODO: Don't hardcode out/ as the bazel output directory. This is
193 // currently hardcoded as ninja_build.output_root.
194 bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
195
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000196 ctx.Println("Populating output directory...")
197 populateOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500198}
199
200// For all files F recursively under rootPath/relativePath, creates symlinks
201// such that OutDir/F resolves to rootPath/F via symlinks.
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000202// NOTE: For distdir paths we rename files instead of creating symlinks, so that the distdir is independent.
203func populateOutdir(ctx Context, config Config, rootPath string, relativePath string) {
Chris Parsonsc09495b2020-11-04 20:45:50 -0500204 destDir := filepath.Join(rootPath, relativePath)
205 os.MkdirAll(destDir, 0755)
206 files, err := ioutil.ReadDir(destDir)
207 if err != nil {
208 ctx.Fatal(err)
209 }
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000210
Chris Parsonsc09495b2020-11-04 20:45:50 -0500211 for _, f := range files {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000212 // The original Bazel file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500213 destPath := filepath.Join(destDir, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000214
215 // The desired Soong file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500216 srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000217
218 destLstatResult, destLstatErr := os.Lstat(destPath)
219 if destLstatErr != nil {
220 ctx.Fatalf("Unable to Lstat dest %s: %s", destPath, destLstatErr)
221 }
222
223 srcLstatResult, srcLstatErr := os.Lstat(srcPath)
224
225 if srcLstatErr == nil {
226 if srcLstatResult.IsDir() && destLstatResult.IsDir() {
227 // src and dest are both existing dirs - recurse on the dest dir contents...
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000228 populateOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
Chris Parsonsc09495b2020-11-04 20:45:50 -0500229 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000230 // Ignore other pre-existing src files (could be pre-existing files, directories, symlinks, ...)
231 // This can arise for files which are generated under OutDir outside of soong_build, such as .bootstrap files.
232 // FIXME: This might cause a problem later e.g. if a symlink in the build graph changes...
Chris Parsonsc09495b2020-11-04 20:45:50 -0500233 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500234 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000235 if !os.IsNotExist(srcLstatErr) {
236 ctx.Fatalf("Unable to Lstat src %s: %s", srcPath, srcLstatErr)
237 }
238
Rupert Shuttleworth3c9f5ac2020-12-10 11:32:38 +0000239 if strings.Contains(destDir, config.DistDir()) {
240 // We need to make a "real" file/dir instead of making a symlink (because the distdir can't have symlinks)
241 // Rename instead of copy in order to save disk space.
242 if err := os.Rename(destPath, srcPath); err != nil {
243 ctx.Fatalf("Unable to rename %s -> %s due to error %s", srcPath, destPath, err)
244 }
245 } else {
246 // src does not exist, so try to create a src -> dest symlink (i.e. a Soong path -> Bazel path symlink)
247 if err := os.Symlink(destPath, srcPath); err != nil {
248 ctx.Fatalf("Unable to create symlink %s -> %s due to error %s", srcPath, destPath, err)
249 }
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000250 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500251 }
252 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000253}