github.com/tarrant/terraform@v0.3.8-0.20150402012457-f68c9eee638e/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "log" 8 "os" 9 "sync" 10 11 "github.com/hashicorp/terraform/plugin" 12 "github.com/mitchellh/cli" 13 "github.com/mitchellh/panicwrap" 14 "github.com/mitchellh/prefixedio" 15 ) 16 17 func main() { 18 os.Exit(realMain()) 19 } 20 21 func realMain() int { 22 var wrapConfig panicwrap.WrapConfig 23 24 if !panicwrap.Wrapped(&wrapConfig) { 25 // Determine where logs should go in general (requested by the user) 26 logWriter, err := logOutput() 27 if err != nil { 28 fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err) 29 return 1 30 } 31 if logWriter == nil { 32 logWriter = ioutil.Discard 33 } 34 35 // We always send logs to a temporary file that we use in case 36 // there is a panic. Otherwise, we delete it. 37 logTempFile, err := ioutil.TempFile("", "terraform-log") 38 if err != nil { 39 fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err) 40 return 1 41 } 42 defer os.Remove(logTempFile.Name()) 43 defer logTempFile.Close() 44 45 // Tell the logger to log to this file 46 os.Setenv(EnvLog, "") 47 os.Setenv(EnvLogFile, "") 48 49 // Setup the prefixed readers that send data properly to 50 // stdout/stderr. 51 doneCh := make(chan struct{}) 52 outR, outW := io.Pipe() 53 go copyOutput(outR, doneCh) 54 55 // Create the configuration for panicwrap and wrap our executable 56 wrapConfig.Handler = panicHandler(logTempFile) 57 wrapConfig.Writer = io.MultiWriter(logTempFile, logWriter) 58 wrapConfig.Stdout = outW 59 exitStatus, err := panicwrap.Wrap(&wrapConfig) 60 if err != nil { 61 fmt.Fprintf(os.Stderr, "Couldn't start Terraform: %s", err) 62 return 1 63 } 64 65 // If >= 0, we're the parent, so just exit 66 if exitStatus >= 0 { 67 // Close the stdout writer so that our copy process can finish 68 outW.Close() 69 70 // Wait for the output copying to finish 71 <-doneCh 72 73 return exitStatus 74 } 75 76 // We're the child, so just close the tempfile we made in order to 77 // save file handles since the tempfile is only used by the parent. 78 logTempFile.Close() 79 } 80 81 // Call the real main 82 return wrappedMain() 83 } 84 85 func wrappedMain() int { 86 log.SetOutput(os.Stderr) 87 log.Printf( 88 "[INFO] Terraform version: %s %s %s", 89 Version, VersionPrerelease, GitCommit) 90 91 // Load the configuration 92 config := BuiltinConfig 93 if err := config.Discover(); err != nil { 94 Ui.Error(fmt.Sprintf("Error discovering plugins: %s", err)) 95 return 1 96 } 97 98 // Run checkpoint 99 go runCheckpoint(&config) 100 101 // Make sure we clean up any managed plugins at the end of this 102 defer plugin.CleanupClients() 103 104 // Initialize the TFConfig settings for the commands... 105 ContextOpts.Providers = config.ProviderFactories() 106 ContextOpts.Provisioners = config.ProvisionerFactories() 107 108 // Get the command line args. We shortcut "--version" and "-v" to 109 // just show the version. 110 args := os.Args[1:] 111 for _, arg := range args { 112 if arg == "-v" || arg == "-version" || arg == "--version" { 113 newArgs := make([]string, len(args)+1) 114 newArgs[0] = "version" 115 copy(newArgs[1:], args) 116 args = newArgs 117 break 118 } 119 } 120 121 cli := &cli.CLI{ 122 Args: args, 123 Commands: Commands, 124 HelpFunc: cli.BasicHelpFunc("terraform"), 125 HelpWriter: os.Stdout, 126 } 127 128 // Load the configuration file if we have one, that can be used to 129 // define extra providers and provisioners. 130 clicfgFile, err := cliConfigFile() 131 if err != nil { 132 Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err)) 133 return 1 134 } 135 136 if clicfgFile != "" { 137 usrcfg, err := LoadConfig(clicfgFile) 138 if err != nil { 139 Ui.Error(fmt.Sprintf("Error loading CLI configuration: \n\n%s", err)) 140 return 1 141 } 142 143 config = *config.Merge(usrcfg) 144 } 145 146 // Initialize the TFConfig settings for the commands... 147 ContextOpts.Providers = config.ProviderFactories() 148 ContextOpts.Provisioners = config.ProvisionerFactories() 149 150 exitCode, err := cli.Run() 151 if err != nil { 152 Ui.Error(fmt.Sprintf("Error executing CLI: %s", err.Error())) 153 return 1 154 } 155 156 return exitCode 157 } 158 159 func cliConfigFile() (string, error) { 160 mustExist := true 161 configFilePath := os.Getenv("TERRAFORM_CONFIG") 162 if configFilePath == "" { 163 var err error 164 configFilePath, err = ConfigFile() 165 mustExist = false 166 167 if err != nil { 168 log.Printf( 169 "[ERROR] Error detecting default CLI config file path: %s", 170 err) 171 } 172 } 173 174 log.Printf("[DEBUG] Attempting to open CLI config file: %s", configFilePath) 175 f, err := os.Open(configFilePath) 176 if err == nil { 177 f.Close() 178 return configFilePath, nil 179 } 180 181 if mustExist || !os.IsNotExist(err) { 182 return "", err 183 } 184 185 log.Println("[DEBUG] File doesn't exist, but doesn't need to. Ignoring.") 186 return "", nil 187 } 188 189 // copyOutput uses output prefixes to determine whether data on stdout 190 // should go to stdout or stderr. This is due to panicwrap using stderr 191 // as the log and error channel. 192 func copyOutput(r io.Reader, doneCh chan<- struct{}) { 193 defer close(doneCh) 194 195 pr, err := prefixedio.NewReader(r) 196 if err != nil { 197 panic(err) 198 } 199 200 stderrR, err := pr.Prefix(ErrorPrefix) 201 if err != nil { 202 panic(err) 203 } 204 stdoutR, err := pr.Prefix(OutputPrefix) 205 if err != nil { 206 panic(err) 207 } 208 defaultR, err := pr.Prefix("") 209 if err != nil { 210 panic(err) 211 } 212 213 var wg sync.WaitGroup 214 wg.Add(3) 215 go func() { 216 defer wg.Done() 217 io.Copy(os.Stderr, stderrR) 218 }() 219 go func() { 220 defer wg.Done() 221 io.Copy(os.Stdout, stdoutR) 222 }() 223 go func() { 224 defer wg.Done() 225 io.Copy(os.Stdout, defaultR) 226 }() 227 228 wg.Wait() 229 }