Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 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 | |
| 15 | package main |
| 16 | |
| 17 | import ( |
Dan Willemsen | c89b6f1 | 2019-08-29 14:47:40 -0700 | [diff] [blame] | 18 | "bytes" |
Jeff Gaston | 90cfb09 | 2017-09-26 16:46:10 -0700 | [diff] [blame] | 19 | "errors" |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 20 | "flag" |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 21 | "fmt" |
| 22 | "io/ioutil" |
| 23 | "os" |
| 24 | "os/exec" |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 25 | "path" |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 26 | "path/filepath" |
| 27 | "strings" |
Colin Cross | d1c1e6f | 2019-03-29 13:54:39 -0700 | [diff] [blame] | 28 | "time" |
Dan Willemsen | c89b6f1 | 2019-08-29 14:47:40 -0700 | [diff] [blame] | 29 | |
| 30 | "android/soong/makedeps" |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 31 | ) |
| 32 | |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 33 | var ( |
| 34 | sandboxesRoot string |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 35 | rawCommand string |
| 36 | outputRoot string |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 37 | keepOutDir bool |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 38 | depfileOut string |
| 39 | inputHash string |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 40 | ) |
| 41 | |
| 42 | func init() { |
| 43 | flag.StringVar(&sandboxesRoot, "sandbox-path", "", |
| 44 | "root of temp directory to put the sandbox into") |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 45 | flag.StringVar(&rawCommand, "c", "", |
| 46 | "command to run") |
| 47 | flag.StringVar(&outputRoot, "output-root", "", |
| 48 | "root of directory to copy outputs into") |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 49 | flag.BoolVar(&keepOutDir, "keep-out-dir", false, |
| 50 | "whether to keep the sandbox directory when done") |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 51 | |
| 52 | flag.StringVar(&depfileOut, "depfile-out", "", |
| 53 | "file path of the depfile to generate. This value will replace '__SBOX_DEPFILE__' in the command and will be treated as an output but won't be added to __SBOX_OUT_FILES__") |
| 54 | |
| 55 | flag.StringVar(&inputHash, "input-hash", "", |
| 56 | "This option is ignored. Typical usage is to supply a hash of the list of input names so that the module will be rebuilt if the list (and thus the hash) changes.") |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 57 | } |
| 58 | |
| 59 | func usageViolation(violation string) { |
| 60 | if violation != "" { |
| 61 | fmt.Fprintf(os.Stderr, "Usage error: %s.\n\n", violation) |
| 62 | } |
| 63 | |
| 64 | fmt.Fprintf(os.Stderr, |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 65 | "Usage: sbox -c <commandToRun> --sandbox-path <sandboxPath> --output-root <outputRoot> [--depfile-out depFile] [--input-hash hash] <outputFile> [<outputFile>...]\n"+ |
| 66 | "\n"+ |
| 67 | "Deletes <outputRoot>,"+ |
| 68 | "runs <commandToRun>,"+ |
| 69 | "and moves each <outputFile> out of <sandboxPath> and into <outputRoot>\n") |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 70 | |
| 71 | flag.PrintDefaults() |
| 72 | |
| 73 | os.Exit(1) |
| 74 | } |
| 75 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 76 | func main() { |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 77 | flag.Usage = func() { |
| 78 | usageViolation("") |
| 79 | } |
| 80 | flag.Parse() |
| 81 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 82 | error := run() |
| 83 | if error != nil { |
| 84 | fmt.Fprintln(os.Stderr, error) |
| 85 | os.Exit(1) |
| 86 | } |
| 87 | } |
| 88 | |
Jeff Gaston | 90cfb09 | 2017-09-26 16:46:10 -0700 | [diff] [blame] | 89 | func findAllFilesUnder(root string) (paths []string) { |
| 90 | paths = []string{} |
| 91 | filepath.Walk(root, func(path string, info os.FileInfo, err error) error { |
| 92 | if !info.IsDir() { |
| 93 | relPath, err := filepath.Rel(root, path) |
| 94 | if err != nil { |
| 95 | // couldn't find relative path from ancestor? |
| 96 | panic(err) |
| 97 | } |
| 98 | paths = append(paths, relPath) |
| 99 | } |
| 100 | return nil |
| 101 | }) |
| 102 | return paths |
| 103 | } |
| 104 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 105 | func run() error { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 106 | if rawCommand == "" { |
| 107 | usageViolation("-c <commandToRun> is required and must be non-empty") |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 108 | } |
Jeff Gaston | 02a684b | 2017-10-27 14:59:27 -0700 | [diff] [blame] | 109 | if sandboxesRoot == "" { |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 110 | // In practice, the value of sandboxesRoot will mostly likely be at a fixed location relative to OUT_DIR, |
| 111 | // and the sbox executable will most likely be at a fixed location relative to OUT_DIR too, so |
| 112 | // the value of sandboxesRoot will most likely be at a fixed location relative to the sbox executable |
| 113 | // However, Soong also needs to be able to separately remove the sandbox directory on startup (if it has anything left in it) |
| 114 | // and by passing it as a parameter we don't need to duplicate its value |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 115 | usageViolation("--sandbox-path <sandboxPath> is required and must be non-empty") |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 116 | } |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 117 | if len(outputRoot) == 0 { |
| 118 | usageViolation("--output-root <outputRoot> is required and must be non-empty") |
Jeff Gaston | 193f2fb | 2017-06-12 15:00:12 -0700 | [diff] [blame] | 119 | } |
| 120 | |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 121 | // the contents of the __SBOX_OUT_FILES__ variable |
| 122 | outputsVarEntries := flag.Args() |
| 123 | if len(outputsVarEntries) == 0 { |
| 124 | usageViolation("at least one output file must be given") |
| 125 | } |
| 126 | |
| 127 | // all outputs |
| 128 | var allOutputs []string |
| 129 | |
| 130 | // setup directories |
| 131 | err := os.MkdirAll(sandboxesRoot, 0777) |
Jeff Gaston | 8a88db5 | 2017-11-06 13:33:14 -0800 | [diff] [blame] | 132 | if err != nil { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 133 | return err |
| 134 | } |
| 135 | err = os.RemoveAll(outputRoot) |
| 136 | if err != nil { |
| 137 | return err |
| 138 | } |
| 139 | err = os.MkdirAll(outputRoot, 0777) |
| 140 | if err != nil { |
| 141 | return err |
Jeff Gaston | 8a88db5 | 2017-11-06 13:33:14 -0800 | [diff] [blame] | 142 | } |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 143 | |
| 144 | tempDir, err := ioutil.TempDir(sandboxesRoot, "sbox") |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 145 | |
| 146 | for i, filePath := range outputsVarEntries { |
| 147 | if !strings.HasPrefix(filePath, "__SBOX_OUT_DIR__/") { |
| 148 | return fmt.Errorf("output files must start with `__SBOX_OUT_DIR__/`") |
| 149 | } |
| 150 | outputsVarEntries[i] = strings.TrimPrefix(filePath, "__SBOX_OUT_DIR__/") |
| 151 | } |
| 152 | |
| 153 | allOutputs = append([]string(nil), outputsVarEntries...) |
| 154 | |
| 155 | if depfileOut != "" { |
| 156 | sandboxedDepfile, err := filepath.Rel(outputRoot, depfileOut) |
| 157 | if err != nil { |
| 158 | return err |
| 159 | } |
| 160 | allOutputs = append(allOutputs, sandboxedDepfile) |
| 161 | rawCommand = strings.Replace(rawCommand, "__SBOX_DEPFILE__", filepath.Join(tempDir, sandboxedDepfile), -1) |
| 162 | |
| 163 | } |
| 164 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 165 | if err != nil { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 166 | return fmt.Errorf("Failed to create temp dir: %s", err) |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 167 | } |
| 168 | |
| 169 | // In the common case, the following line of code is what removes the sandbox |
| 170 | // If a fatal error occurs (such as if our Go process is killed unexpectedly), |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 171 | // then at the beginning of the next build, Soong will retry the cleanup |
Jeff Gaston | f49082a | 2017-06-07 13:22:22 -0700 | [diff] [blame] | 172 | defer func() { |
| 173 | // in some cases we decline to remove the temp dir, to facilitate debugging |
Jeff Gaston | 93f0f37 | 2017-11-01 13:33:02 -0700 | [diff] [blame] | 174 | if !keepOutDir { |
Jeff Gaston | f49082a | 2017-06-07 13:22:22 -0700 | [diff] [blame] | 175 | os.RemoveAll(tempDir) |
| 176 | } |
| 177 | }() |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 178 | |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 179 | if strings.Contains(rawCommand, "__SBOX_OUT_DIR__") { |
| 180 | rawCommand = strings.Replace(rawCommand, "__SBOX_OUT_DIR__", tempDir, -1) |
| 181 | } |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 182 | |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 183 | if strings.Contains(rawCommand, "__SBOX_OUT_FILES__") { |
| 184 | // expands into a space-separated list of output files to be generated into the sandbox directory |
| 185 | tempOutPaths := []string{} |
| 186 | for _, outputPath := range outputsVarEntries { |
| 187 | tempOutPath := path.Join(tempDir, outputPath) |
| 188 | tempOutPaths = append(tempOutPaths, tempOutPath) |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 189 | } |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 190 | pathsText := strings.Join(tempOutPaths, " ") |
| 191 | rawCommand = strings.Replace(rawCommand, "__SBOX_OUT_FILES__", pathsText, -1) |
| 192 | } |
| 193 | |
| 194 | for _, filePath := range allOutputs { |
| 195 | dir := path.Join(tempDir, filepath.Dir(filePath)) |
| 196 | err = os.MkdirAll(dir, 0777) |
Jeff Gaston | 02a684b | 2017-10-27 14:59:27 -0700 | [diff] [blame] | 197 | if err != nil { |
| 198 | return err |
| 199 | } |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 200 | } |
| 201 | |
Jeff Gaston | 193f2fb | 2017-06-12 15:00:12 -0700 | [diff] [blame] | 202 | commandDescription := rawCommand |
| 203 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 204 | cmd := exec.Command("bash", "-c", rawCommand) |
| 205 | cmd.Stdin = os.Stdin |
| 206 | cmd.Stdout = os.Stdout |
| 207 | cmd.Stderr = os.Stderr |
| 208 | err = cmd.Run() |
Jeff Gaston | 193f2fb | 2017-06-12 15:00:12 -0700 | [diff] [blame] | 209 | |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 210 | if exit, ok := err.(*exec.ExitError); ok && !exit.Success() { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 211 | return fmt.Errorf("sbox command (%s) failed with err %#v\n", commandDescription, err.Error()) |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 212 | } else if err != nil { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 213 | return err |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 214 | } |
| 215 | |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 216 | // validate that all files are created properly |
| 217 | var missingOutputErrors []string |
| 218 | for _, filePath := range allOutputs { |
| 219 | tempPath := filepath.Join(tempDir, filePath) |
| 220 | fileInfo, err := os.Stat(tempPath) |
| 221 | if err != nil { |
| 222 | missingOutputErrors = append(missingOutputErrors, fmt.Sprintf("%s: does not exist", filePath)) |
| 223 | continue |
| 224 | } |
| 225 | if fileInfo.IsDir() { |
| 226 | missingOutputErrors = append(missingOutputErrors, fmt.Sprintf("%s: not a file", filePath)) |
| 227 | } |
| 228 | } |
Jeff Gaston | 90cfb09 | 2017-09-26 16:46:10 -0700 | [diff] [blame] | 229 | if len(missingOutputErrors) > 0 { |
| 230 | // find all created files for making a more informative error message |
| 231 | createdFiles := findAllFilesUnder(tempDir) |
| 232 | |
| 233 | // build error message |
| 234 | errorMessage := "mismatch between declared and actual outputs\n" |
| 235 | errorMessage += "in sbox command(" + commandDescription + ")\n\n" |
| 236 | errorMessage += "in sandbox " + tempDir + ",\n" |
| 237 | errorMessage += fmt.Sprintf("failed to create %v files:\n", len(missingOutputErrors)) |
| 238 | for _, missingOutputError := range missingOutputErrors { |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 239 | errorMessage += " " + missingOutputError + "\n" |
Jeff Gaston | 90cfb09 | 2017-09-26 16:46:10 -0700 | [diff] [blame] | 240 | } |
| 241 | if len(createdFiles) < 1 { |
| 242 | errorMessage += "created 0 files." |
| 243 | } else { |
| 244 | errorMessage += fmt.Sprintf("did create %v files:\n", len(createdFiles)) |
| 245 | creationMessages := createdFiles |
| 246 | maxNumCreationLines := 10 |
| 247 | if len(creationMessages) > maxNumCreationLines { |
| 248 | creationMessages = creationMessages[:maxNumCreationLines] |
| 249 | creationMessages = append(creationMessages, fmt.Sprintf("...%v more", len(createdFiles)-maxNumCreationLines)) |
| 250 | } |
| 251 | for _, creationMessage := range creationMessages { |
| 252 | errorMessage += " " + creationMessage + "\n" |
| 253 | } |
| 254 | } |
| 255 | |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 256 | // Keep the temporary output directory around in case a user wants to inspect it for debugging purposes. |
| 257 | // Soong will delete it later anyway. |
| 258 | keepOutDir = true |
| 259 | return errors.New(errorMessage) |
Jeff Gaston | f49082a | 2017-06-07 13:22:22 -0700 | [diff] [blame] | 260 | } |
| 261 | // the created files match the declared files; now move them |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 262 | for _, filePath := range allOutputs { |
| 263 | tempPath := filepath.Join(tempDir, filePath) |
| 264 | destPath := filePath |
| 265 | if len(outputRoot) != 0 { |
| 266 | destPath = filepath.Join(outputRoot, filePath) |
Jeff Gaston | 193f2fb | 2017-06-12 15:00:12 -0700 | [diff] [blame] | 267 | } |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 268 | err := os.MkdirAll(filepath.Dir(destPath), 0777) |
Jeff Gaston | 8a88db5 | 2017-11-06 13:33:14 -0800 | [diff] [blame] | 269 | if err != nil { |
| 270 | return err |
| 271 | } |
Colin Cross | d1c1e6f | 2019-03-29 13:54:39 -0700 | [diff] [blame] | 272 | |
| 273 | // Update the timestamp of the output file in case the tool wrote an old timestamp (for example, tar can extract |
| 274 | // files with old timestamps). |
| 275 | now := time.Now() |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 276 | err = os.Chtimes(tempPath, now, now) |
| 277 | if err != nil { |
| 278 | return err |
| 279 | } |
| 280 | |
| 281 | err = os.Rename(tempPath, destPath) |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 282 | if err != nil { |
| 283 | return err |
| 284 | } |
| 285 | } |
Colin Cross | 619b9ab | 2020-11-20 18:44:31 +0000 | [diff] [blame] | 286 | |
| 287 | // Rewrite the depfile so that it doesn't include the (randomized) sandbox directory |
| 288 | if depfileOut != "" { |
| 289 | in, err := ioutil.ReadFile(depfileOut) |
| 290 | if err != nil { |
| 291 | return err |
| 292 | } |
| 293 | |
| 294 | deps, err := makedeps.Parse(depfileOut, bytes.NewBuffer(in)) |
| 295 | if err != nil { |
| 296 | return err |
| 297 | } |
| 298 | |
| 299 | deps.Output = "outputfile" |
| 300 | |
| 301 | err = ioutil.WriteFile(depfileOut, deps.Print(), 0666) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | // TODO(jeffrygaston) if a process creates more output files than it declares, should there be a warning? |
Jeff Gaston | efc1b41 | 2017-03-29 17:29:06 -0700 | [diff] [blame] | 308 | return nil |
| 309 | } |