blob: 1cab8f8a73723c1b73ba82c01aba8d29de5ec9f6 [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
81 bazelEnv["DIST_DIR"] = config.DistDir()
82 bazelEnv["SHELL"] = "/bin/bash"
Jingwen Chena26ac3c2020-11-10 08:17:59 -050083
Jingwen Chen7a5391a2020-11-17 03:42:12 -050084 // `tools/bazel` is the default entry point for executing Bazel in the AOSP
85 // source tree.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000086 bazelExecutable := filepath.Join("tools", "bazel")
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000087 cmd := Command(ctx, config, "bazel", bazelExecutable)
88
Jingwen Chen7a5391a2020-11-17 03:42:12 -050089 // Append custom startup flags to the Bazel command. Startup flags affect
90 // the Bazel server itself, and any changes to these flags would incur a
91 // restart of the server, losing much of the in-memory incrementality.
92 if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
93 cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000094 }
95
Jingwen Chen7a5391a2020-11-17 03:42:12 -050096 // Start constructing the `build` command.
Patrice Arruda18cb70d2020-11-13 11:37:06 -080097 actionName := "build"
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000098 cmd.Args = append(cmd.Args,
Patrice Arruda18cb70d2020-11-13 11:37:06 -080099 actionName,
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500100 // Use output_groups to select the set of outputs to produce from a
101 // ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000102 "--output_groups="+outputGroups,
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500103 // Generate a performance profile
Patrice Arruda18cb70d2020-11-13 11:37:06 -0800104 "--profile="+filepath.Join(shared.BazelMetricsFilename(config.OutDir(), actionName)),
105 "--slim_profile=true",
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000106 )
107
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000108 if config.UseRBE() {
109 for _, envVar := range []string{
110 // RBE client
111 "RBE_compare",
112 "RBE_exec_strategy",
113 "RBE_invocation_id",
114 "RBE_log_dir",
115 "RBE_platform",
116 "RBE_remote_accept_cache",
117 "RBE_remote_update_cache",
118 "RBE_server_address",
119 // TODO: remove old FLAG_ variables.
120 "FLAG_compare",
121 "FLAG_exec_root",
122 "FLAG_exec_strategy",
123 "FLAG_invocation_id",
124 "FLAG_log_dir",
125 "FLAG_platform",
126 "FLAG_remote_accept_cache",
127 "FLAG_remote_update_cache",
128 "FLAG_server_address",
129 } {
130 cmd.Args = append(cmd.Args,
131 "--action_env="+envVar)
132 }
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000133
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000134 // We need to calculate --RBE_exec_root ourselves
135 ctx.Println("Getting Bazel execution_root...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000136 cmd.Args = append(cmd.Args, "--action_env=RBE_exec_root="+getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "execution_root"))
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000137 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000138
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500139 // Ensure that the PATH environment variable value used in the action
140 // environment is the restricted set computed from soong_ui, and not a
141 // user-provided one, for hermeticity reasons.
Jingwen Chen3a4b58d2020-11-16 04:19:35 -0500142 if pathEnvValue, ok := config.environ.Get("PATH"); ok {
143 cmd.Environment.Set("PATH", pathEnvValue)
144 cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
145 }
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500146
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000147 // Append custom build flags to the Bazel command. Changes to these flags
148 // may invalidate Bazel's analysis cache.
149 // These should be appended as the final args, so that they take precedence.
150 if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
151 cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
152 }
153
154 // Append the label of the default ninja_build target.
155 cmd.Args = append(cmd.Args,
156 "//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
157 )
158
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500159 // Print the full command line for debugging purposes.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000160 ctx.Println(cmd.Cmd)
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500161
162 // 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
175 // Print the full command line (including environment variables) for debugging purposes.
176 ctx.Println("Bazel command line: " + bazelEnvStringBuffer.String() + cmd.Cmd.String() + "\n")
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500177
178 // Execute the build command.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000179 cmd.RunAndStreamOrFatal()
Chris Parsonsc09495b2020-11-04 20:45:50 -0500180
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500181 // Post-processing steps start here. Once the Bazel build completes, the
182 // output files are still stored in the execution root, not in $OUT_DIR.
183 // Ensure that the $OUT_DIR contains the expected set of files by symlinking
184 // the files from the execution root's output direction into $OUT_DIR.
185
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000186 ctx.Println("Getting Bazel output_path...")
Rupert Shuttleworth947ed972020-12-04 19:31:02 +0000187 outputBasePath := getBazelInfo(ctx, config, bazelExecutable, bazelEnv, "output_path")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500188 // TODO: Don't hardcode out/ as the bazel output directory. This is
189 // currently hardcoded as ninja_build.output_root.
190 bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
191
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000192 ctx.Println("Creating output symlinks..")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500193 symlinkOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
194}
195
196// For all files F recursively under rootPath/relativePath, creates symlinks
197// such that OutDir/F resolves to rootPath/F via symlinks.
198func symlinkOutdir(ctx Context, config Config, rootPath string, relativePath string) {
199 destDir := filepath.Join(rootPath, relativePath)
200 os.MkdirAll(destDir, 0755)
201 files, err := ioutil.ReadDir(destDir)
202 if err != nil {
203 ctx.Fatal(err)
204 }
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000205
Chris Parsonsc09495b2020-11-04 20:45:50 -0500206 for _, f := range files {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000207 // The original Bazel file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500208 destPath := filepath.Join(destDir, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000209
210 // The desired Soong file path
Chris Parsonsc09495b2020-11-04 20:45:50 -0500211 srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000212
213 destLstatResult, destLstatErr := os.Lstat(destPath)
214 if destLstatErr != nil {
215 ctx.Fatalf("Unable to Lstat dest %s: %s", destPath, destLstatErr)
216 }
217
218 srcLstatResult, srcLstatErr := os.Lstat(srcPath)
219
220 if srcLstatErr == nil {
221 if srcLstatResult.IsDir() && destLstatResult.IsDir() {
222 // src and dest are both existing dirs - recurse on the dest dir contents...
Chris Parsonsc09495b2020-11-04 20:45:50 -0500223 symlinkOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
Chris Parsonsc09495b2020-11-04 20:45:50 -0500224 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000225 // Ignore other pre-existing src files (could be pre-existing files, directories, symlinks, ...)
226 // This can arise for files which are generated under OutDir outside of soong_build, such as .bootstrap files.
227 // FIXME: This might cause a problem later e.g. if a symlink in the build graph changes...
Chris Parsonsc09495b2020-11-04 20:45:50 -0500228 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500229 } else {
Rupert Shuttleworthead7ef62020-12-04 01:05:59 +0000230 if !os.IsNotExist(srcLstatErr) {
231 ctx.Fatalf("Unable to Lstat src %s: %s", srcPath, srcLstatErr)
232 }
233
234 // src does not exist, so try to create a src -> dest symlink (i.e. a Soong path -> Bazel path symlink)
235 if symlinkErr := os.Symlink(destPath, srcPath); symlinkErr != nil {
236 ctx.Fatalf("Unable to create symlink %s -> %s due to error %s", srcPath, destPath, symlinkErr)
237 }
Chris Parsonsc09495b2020-11-04 20:45:50 -0500238 }
239 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000240}