blob: 4b008eb8bab6babd9f1f0687c9c6c340e61c4f53 [file] [log] [blame]
Jeff Gastonefc1b412017-03-29 17:29:06 -07001// 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
15package main
16
17import (
Jeff Gaston93f0f372017-11-01 13:33:02 -070018 "flag"
Jeff Gastonefc1b412017-03-29 17:29:06 -070019 "fmt"
20 "io/ioutil"
21 "os"
22 "os/exec"
23 "path"
24 "path/filepath"
25 "strings"
26)
27
Jeff Gaston93f0f372017-11-01 13:33:02 -070028var (
29 sandboxesRoot string
30 rawCommand string
31 outputRoot string
32 keepOutDir bool
33 depfileOut string
34)
35
36func init() {
37 flag.StringVar(&sandboxesRoot, "sandbox-path", "",
38 "root of temp directory to put the sandbox into")
39 flag.StringVar(&rawCommand, "c", "",
40 "command to run")
41 flag.StringVar(&outputRoot, "output-root", "",
42 "root of directory to copy outputs into")
43 flag.BoolVar(&keepOutDir, "keep-out-dir", false,
44 "whether to keep the sandbox directory when done")
45
46 flag.StringVar(&depfileOut, "depfile-out", "",
47 "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__")
48}
49
50func usageViolation(violation string) {
51 if violation != "" {
52 fmt.Fprintf(os.Stderr, "Usage error: %s.\n\n", violation)
53 }
54
55 fmt.Fprintf(os.Stderr,
56 "Usage: sbox -c <commandToRun> --sandbox-path <sandboxPath> --output-root <outputRoot> [--depfile-out depFile] <outputFile> [<outputFile>...]\n"+
57 "\n"+
58 "Runs <commandToRun> and moves each <outputFile> out of <sandboxPath>\n"+
59 "and into <outputRoot>\n")
60
61 flag.PrintDefaults()
62
63 os.Exit(1)
64}
65
Jeff Gastonefc1b412017-03-29 17:29:06 -070066func main() {
Jeff Gaston93f0f372017-11-01 13:33:02 -070067 flag.Usage = func() {
68 usageViolation("")
69 }
70 flag.Parse()
71
Jeff Gastonefc1b412017-03-29 17:29:06 -070072 error := run()
73 if error != nil {
74 fmt.Fprintln(os.Stderr, error)
75 os.Exit(1)
76 }
77}
78
Jeff Gastonefc1b412017-03-29 17:29:06 -070079func run() error {
Jeff Gaston02a684b2017-10-27 14:59:27 -070080 if rawCommand == "" {
Jeff Gaston93f0f372017-11-01 13:33:02 -070081 usageViolation("-c <commandToRun> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -070082 }
Jeff Gaston02a684b2017-10-27 14:59:27 -070083 if sandboxesRoot == "" {
Jeff Gastonefc1b412017-03-29 17:29:06 -070084 // In practice, the value of sandboxesRoot will mostly likely be at a fixed location relative to OUT_DIR,
85 // and the sbox executable will most likely be at a fixed location relative to OUT_DIR too, so
86 // the value of sandboxesRoot will most likely be at a fixed location relative to the sbox executable
87 // However, Soong also needs to be able to separately remove the sandbox directory on startup (if it has anything left in it)
88 // and by passing it as a parameter we don't need to duplicate its value
Jeff Gaston93f0f372017-11-01 13:33:02 -070089 usageViolation("--sandbox-path <sandboxPath> is required and must be non-empty")
Jeff Gastonefc1b412017-03-29 17:29:06 -070090 }
Jeff Gaston02a684b2017-10-27 14:59:27 -070091 if len(outputRoot) == 0 {
Jeff Gaston93f0f372017-11-01 13:33:02 -070092 usageViolation("--output-root <outputRoot> is required and must be non-empty")
Jeff Gaston193f2fb2017-06-12 15:00:12 -070093 }
94
Jeff Gaston93f0f372017-11-01 13:33:02 -070095 // the contents of the __SBOX_OUT_FILES__ variable
96 outputsVarEntries := flag.Args()
97 if len(outputsVarEntries) == 0 {
98 usageViolation("at least one output file must be given")
99 }
100
101 // all outputs
102 var allOutputs []string
103
Jeff Gastonefc1b412017-03-29 17:29:06 -0700104 os.MkdirAll(sandboxesRoot, 0777)
105
106 tempDir, err := ioutil.TempDir(sandboxesRoot, "sbox")
Jeff Gaston02a684b2017-10-27 14:59:27 -0700107
108 // Rewrite output file paths to be relative to output root
109 // This facilitates matching them up against the corresponding paths in the temporary directory in case they're absolute
110 for i, filePath := range outputsVarEntries {
111 relativePath, err := filepath.Rel(outputRoot, filePath)
112 if err != nil {
113 return err
114 }
115 outputsVarEntries[i] = relativePath
116 }
117
118 allOutputs = append([]string(nil), outputsVarEntries...)
119
Jeff Gaston93f0f372017-11-01 13:33:02 -0700120 if depfileOut != "" {
121 sandboxedDepfile, err := filepath.Rel(outputRoot, depfileOut)
Jeff Gaston02a684b2017-10-27 14:59:27 -0700122 if err != nil {
123 return err
124 }
125 allOutputs = append(allOutputs, sandboxedDepfile)
126 if !strings.Contains(rawCommand, "__SBOX_DEPFILE__") {
127 return fmt.Errorf("the --depfile-out argument only makes sense if the command contains the text __SBOX_DEPFILE__")
128 }
129 rawCommand = strings.Replace(rawCommand, "__SBOX_DEPFILE__", filepath.Join(tempDir, sandboxedDepfile), -1)
130
131 }
132
Jeff Gastonefc1b412017-03-29 17:29:06 -0700133 if err != nil {
134 return fmt.Errorf("Failed to create temp dir: %s", err)
135 }
136
137 // In the common case, the following line of code is what removes the sandbox
138 // If a fatal error occurs (such as if our Go process is killed unexpectedly),
139 // then at the beginning of the next build, Soong will retry the cleanup
Jeff Gastonf49082a2017-06-07 13:22:22 -0700140 defer func() {
141 // in some cases we decline to remove the temp dir, to facilitate debugging
Jeff Gaston93f0f372017-11-01 13:33:02 -0700142 if !keepOutDir {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700143 os.RemoveAll(tempDir)
144 }
145 }()
Jeff Gastonefc1b412017-03-29 17:29:06 -0700146
147 if strings.Contains(rawCommand, "__SBOX_OUT_DIR__") {
148 rawCommand = strings.Replace(rawCommand, "__SBOX_OUT_DIR__", tempDir, -1)
149 }
150
151 if strings.Contains(rawCommand, "__SBOX_OUT_FILES__") {
152 // expands into a space-separated list of output files to be generated into the sandbox directory
153 tempOutPaths := []string{}
Jeff Gaston02a684b2017-10-27 14:59:27 -0700154 for _, outputPath := range outputsVarEntries {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700155 tempOutPath := path.Join(tempDir, outputPath)
156 tempOutPaths = append(tempOutPaths, tempOutPath)
157 }
158 pathsText := strings.Join(tempOutPaths, " ")
159 rawCommand = strings.Replace(rawCommand, "__SBOX_OUT_FILES__", pathsText, -1)
160 }
161
Jeff Gaston02a684b2017-10-27 14:59:27 -0700162 for _, filePath := range allOutputs {
163 dir := path.Join(tempDir, filepath.Dir(filePath))
164 err = os.MkdirAll(dir, 0777)
165 if err != nil {
166 return err
167 }
Jeff Gastonefc1b412017-03-29 17:29:06 -0700168 }
169
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700170 commandDescription := rawCommand
171
Jeff Gastonefc1b412017-03-29 17:29:06 -0700172 cmd := exec.Command("bash", "-c", rawCommand)
173 cmd.Stdin = os.Stdin
174 cmd.Stdout = os.Stdout
175 cmd.Stderr = os.Stderr
176 err = cmd.Run()
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700177
Jeff Gastonefc1b412017-03-29 17:29:06 -0700178 if exit, ok := err.(*exec.ExitError); ok && !exit.Success() {
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700179 return fmt.Errorf("sbox command (%s) failed with err %#v\n", commandDescription, err.Error())
Jeff Gastonefc1b412017-03-29 17:29:06 -0700180 } else if err != nil {
181 return err
182 }
183
Jeff Gastonf49082a2017-06-07 13:22:22 -0700184 // validate that all files are created properly
185 var outputErrors []error
Jeff Gaston02a684b2017-10-27 14:59:27 -0700186 for _, filePath := range allOutputs {
Jeff Gastonefc1b412017-03-29 17:29:06 -0700187 tempPath := filepath.Join(tempDir, filePath)
188 fileInfo, err := os.Stat(tempPath)
189 if err != nil {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700190 outputErrors = append(outputErrors, fmt.Errorf("failed to create expected output file: %s\n", tempPath))
191 continue
Jeff Gastonefc1b412017-03-29 17:29:06 -0700192 }
193 if fileInfo.IsDir() {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700194 outputErrors = append(outputErrors, fmt.Errorf("Output path %s refers to a directory, not a file. This is not permitted because it prevents robust up-to-date checks\n", filePath))
Jeff Gastonefc1b412017-03-29 17:29:06 -0700195 }
Jeff Gastonf49082a2017-06-07 13:22:22 -0700196 }
197 if len(outputErrors) > 0 {
198 // Keep the temporary output directory around in case a user wants to inspect it for debugging purposes.
199 // Soong will delete it later anyway.
Jeff Gaston93f0f372017-11-01 13:33:02 -0700200 keepOutDir = true
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700201 return fmt.Errorf("mismatch between declared and actual outputs in sbox command (%s):\n%v", commandDescription, outputErrors)
Jeff Gastonf49082a2017-06-07 13:22:22 -0700202 }
203 // the created files match the declared files; now move them
Jeff Gaston02a684b2017-10-27 14:59:27 -0700204 for _, filePath := range allOutputs {
Jeff Gastonf49082a2017-06-07 13:22:22 -0700205 tempPath := filepath.Join(tempDir, filePath)
Jeff Gaston193f2fb2017-06-12 15:00:12 -0700206 destPath := filePath
207 if len(outputRoot) != 0 {
208 destPath = filepath.Join(outputRoot, filePath)
209 }
210 err := os.Rename(tempPath, destPath)
Jeff Gastonefc1b412017-03-29 17:29:06 -0700211 if err != nil {
212 return err
213 }
214 }
Jeff Gastonf49082a2017-06-07 13:22:22 -0700215
Jeff Gastonefc1b412017-03-29 17:29:06 -0700216 // TODO(jeffrygaston) if a process creates more output files than it declares, should there be a warning?
217 return nil
218}