blob: fac046139e64b4baa771a8f78f834269a463de5c [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 (
Chris Parsonsc09495b2020-11-04 20:45:50 -050018 "io/ioutil"
19 "os"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000020 "path/filepath"
21 "strings"
Patrice Arruda18cb70d2020-11-13 11:37:06 -080022
23 "android/soong/shared"
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080024 "android/soong/ui/metrics"
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000025)
26
Rupert Shuttleworthad532f22020-12-04 08:41:14 +000027func getBazelInfo(ctx Context, config Config, bazelExecutable string, query string) string {
28 infoCmd := Command(ctx, config, "bazel", bazelExecutable)
29
30 if extraStartupArgs, ok := infoCmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
31 infoCmd.Args = append(infoCmd.Args, strings.Fields(extraStartupArgs)...)
32 }
33
34 // Obtain the output directory path in the execution root.
35 infoCmd.Args = append(infoCmd.Args,
36 "info",
37 query,
38 )
39
40 infoCmd.Environment.Set("DIST_DIR", config.DistDir())
41 infoCmd.Environment.Set("SHELL", "/bin/bash")
42
43 infoCmd.Dir = filepath.Join(config.OutDir(), "..")
44
45 queryResult := strings.TrimSpace(string(infoCmd.OutputOrFatal()))
46 return queryResult
47}
48
Jingwen Chen7a5391a2020-11-17 03:42:12 -050049// Main entry point to construct the Bazel build command line, environment
50// variables and post-processing steps (e.g. converge output directories)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000051func runBazel(ctx Context, config Config) {
Patrice Arrudab7cf9ba2020-11-13 13:04:17 -080052 ctx.BeginTrace(metrics.RunBazel, "bazel")
53 defer ctx.EndTrace()
54
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000055 // "droid" is the default ninja target.
Jingwen Chen8024c952020-11-08 23:57:56 -050056 // TODO(b/160568333): stop hardcoding 'droid' to support building any
57 // Ninja target.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000058 outputGroups := "droid"
59 if len(config.ninjaArgs) > 0 {
60 // At this stage, the residue slice of args passed to ninja
61 // are the ninja targets to build, which can correspond directly
62 // to ninja_build's output_groups.
63 outputGroups = strings.Join(config.ninjaArgs, ",")
64 }
65
Jingwen Chen7a5391a2020-11-17 03:42:12 -050066 // Environment variables are the primary mechanism to pass information from
67 // soong_ui configuration or context to Bazel.
68 //
69 // Use *_NINJA variables to pass the root-relative path of the combined,
70 // kati-generated, soong-generated, and packaging Ninja files to Bazel.
71 // Bazel reads these from the lunch() repository rule.
Jingwen Chena26ac3c2020-11-10 08:17:59 -050072 config.environ.Set("COMBINED_NINJA", config.CombinedNinjaFile())
73 config.environ.Set("KATI_NINJA", config.KatiBuildNinjaFile())
74 config.environ.Set("PACKAGE_NINJA", config.KatiPackageNinjaFile())
75 config.environ.Set("SOONG_NINJA", config.SoongNinjaFile())
76
Jingwen Chen7a5391a2020-11-17 03:42:12 -050077 // `tools/bazel` is the default entry point for executing Bazel in the AOSP
78 // source tree.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000079 bazelExecutable := filepath.Join("tools", "bazel")
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000080 cmd := Command(ctx, config, "bazel", bazelExecutable)
81
Jingwen Chen7a5391a2020-11-17 03:42:12 -050082 // Append custom startup flags to the Bazel command. Startup flags affect
83 // the Bazel server itself, and any changes to these flags would incur a
84 // restart of the server, losing much of the in-memory incrementality.
85 if extraStartupArgs, ok := cmd.Environment.Get("BAZEL_STARTUP_ARGS"); ok {
86 cmd.Args = append(cmd.Args, strings.Fields(extraStartupArgs)...)
Rupert Shuttleworth680387b2020-10-25 12:31:27 +000087 }
88
Jingwen Chen7a5391a2020-11-17 03:42:12 -050089 // Start constructing the `build` command.
Patrice Arruda18cb70d2020-11-13 11:37:06 -080090 actionName := "build"
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000091 cmd.Args = append(cmd.Args,
Patrice Arruda18cb70d2020-11-13 11:37:06 -080092 actionName,
Jingwen Chen7a5391a2020-11-17 03:42:12 -050093 // Use output_groups to select the set of outputs to produce from a
94 // ninja_build target.
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000095 "--output_groups="+outputGroups,
Jingwen Chen7a5391a2020-11-17 03:42:12 -050096 // Generate a performance profile
Patrice Arruda18cb70d2020-11-13 11:37:06 -080097 "--profile="+filepath.Join(shared.BazelMetricsFilename(config.OutDir(), actionName)),
98 "--slim_profile=true",
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +000099 )
100
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000101 if config.UseRBE() {
102 for _, envVar := range []string{
103 // RBE client
104 "RBE_compare",
105 "RBE_exec_strategy",
106 "RBE_invocation_id",
107 "RBE_log_dir",
108 "RBE_platform",
109 "RBE_remote_accept_cache",
110 "RBE_remote_update_cache",
111 "RBE_server_address",
112 // TODO: remove old FLAG_ variables.
113 "FLAG_compare",
114 "FLAG_exec_root",
115 "FLAG_exec_strategy",
116 "FLAG_invocation_id",
117 "FLAG_log_dir",
118 "FLAG_platform",
119 "FLAG_remote_accept_cache",
120 "FLAG_remote_update_cache",
121 "FLAG_server_address",
122 } {
123 cmd.Args = append(cmd.Args,
124 "--action_env="+envVar)
125 }
Rupert Shuttleworthf8ae3172020-11-10 02:04:14 +0000126
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000127 // We need to calculate --RBE_exec_root ourselves
128 ctx.Println("Getting Bazel execution_root...")
129 cmd.Args = append(cmd.Args, "--action_env=RBE_exec_root="+getBazelInfo(ctx, config, bazelExecutable, "execution_root"))
130 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000131
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500132 // Ensure that the PATH environment variable value used in the action
133 // environment is the restricted set computed from soong_ui, and not a
134 // user-provided one, for hermeticity reasons.
Jingwen Chen3a4b58d2020-11-16 04:19:35 -0500135 if pathEnvValue, ok := config.environ.Get("PATH"); ok {
136 cmd.Environment.Set("PATH", pathEnvValue)
137 cmd.Args = append(cmd.Args, "--action_env=PATH="+pathEnvValue)
138 }
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500139
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000140 // Append custom build flags to the Bazel command. Changes to these flags
141 // may invalidate Bazel's analysis cache.
142 // These should be appended as the final args, so that they take precedence.
143 if extraBuildArgs, ok := cmd.Environment.Get("BAZEL_BUILD_ARGS"); ok {
144 cmd.Args = append(cmd.Args, strings.Fields(extraBuildArgs)...)
145 }
146
147 // Append the label of the default ninja_build target.
148 cmd.Args = append(cmd.Args,
149 "//:"+config.TargetProduct()+"-"+config.TargetBuildVariant(),
150 )
151
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000152 cmd.Environment.Set("DIST_DIR", config.DistDir())
153 cmd.Environment.Set("SHELL", "/bin/bash")
154
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500155 // Print the full command line for debugging purposes.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000156 ctx.Println(cmd.Cmd)
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500157
158 // Execute the command at the root of the directory.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000159 cmd.Dir = filepath.Join(config.OutDir(), "..")
160 ctx.Status.Status("Starting Bazel..")
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500161
162 // Execute the build command.
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000163 cmd.RunAndStreamOrFatal()
Chris Parsonsc09495b2020-11-04 20:45:50 -0500164
Jingwen Chen7a5391a2020-11-17 03:42:12 -0500165 // Post-processing steps start here. Once the Bazel build completes, the
166 // output files are still stored in the execution root, not in $OUT_DIR.
167 // Ensure that the $OUT_DIR contains the expected set of files by symlinking
168 // the files from the execution root's output direction into $OUT_DIR.
169
Rupert Shuttleworthad532f22020-12-04 08:41:14 +0000170 ctx.Println("Getting Bazel output_path...")
171 outputBasePath := getBazelInfo(ctx, config, bazelExecutable, "output_path")
Chris Parsonsc09495b2020-11-04 20:45:50 -0500172 // TODO: Don't hardcode out/ as the bazel output directory. This is
173 // currently hardcoded as ninja_build.output_root.
174 bazelNinjaBuildOutputRoot := filepath.Join(outputBasePath, "..", "out")
175
176 symlinkOutdir(ctx, config, bazelNinjaBuildOutputRoot, ".")
177}
178
179// For all files F recursively under rootPath/relativePath, creates symlinks
180// such that OutDir/F resolves to rootPath/F via symlinks.
181func symlinkOutdir(ctx Context, config Config, rootPath string, relativePath string) {
182 destDir := filepath.Join(rootPath, relativePath)
183 os.MkdirAll(destDir, 0755)
184 files, err := ioutil.ReadDir(destDir)
185 if err != nil {
186 ctx.Fatal(err)
187 }
188 for _, f := range files {
189 destPath := filepath.Join(destDir, f.Name())
190 srcPath := filepath.Join(config.OutDir(), relativePath, f.Name())
191 if statResult, err := os.Stat(srcPath); err == nil {
192 if statResult.Mode().IsDir() && f.IsDir() {
193 // Directory under OutDir already exists, so recurse on its contents.
194 symlinkOutdir(ctx, config, rootPath, filepath.Join(relativePath, f.Name()))
195 } else if !statResult.Mode().IsDir() && !f.IsDir() {
196 // File exists both in source and destination, and it's not a directory
197 // in either location. Do nothing.
198 // This can arise for files which are generated under OutDir outside of
199 // soong_build, such as .bootstrap files.
200 } else {
201 // File is a directory in one location but not the other. Raise an error.
202 ctx.Fatalf("Could not link %s to %s due to conflict", srcPath, destPath)
203 }
204 } else if os.IsNotExist(err) {
205 // Create symlink srcPath -> fullDestPath.
206 os.Symlink(destPath, srcPath)
207 } else {
208 ctx.Fatalf("Unable to stat %s: %s", srcPath, err)
209 }
210 }
Rupert Shuttleworth680387b2020-10-25 12:31:27 +0000211}