diff --git a/watchdog/main.go b/watchdog/main.go index a2c0598ab68c717af383229b599ffe7c4b61e451..da69c2fbf1ce8a0c269794f7347e1406c8eb22ee 100644 --- a/watchdog/main.go +++ b/watchdog/main.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "strings" + "sync" "time" ) @@ -20,42 +21,61 @@ func (OsEnv) Getenv(key string) string { return os.Getenv(key) } +func pipeRequest(config *WatchdogConfig, w http.ResponseWriter, r *http.Request) { + parts := strings.Split(config.faasProcess, " ") + + targetCmd := exec.Command(parts[0], parts[1:]...) + writer, _ := targetCmd.StdinPipe() + + var out []byte + var err error + var res []byte + + var wg sync.WaitGroup + wg.Add(2) + + res, _ = ioutil.ReadAll(r.Body) + defer r.Body.Close() + + go func() { + defer wg.Done() + writer.Write(res) + writer.Close() + }() + + go func() { + defer wg.Done() + out, err = targetCmd.CombinedOutput() + }() + + wg.Wait() + + if err != nil { + if config.writeDebug == true { + log.Println(targetCmd, err) + } + + w.WriteHeader(500) + response := bytes.NewBufferString(err.Error()) + w.Write(response.Bytes()) + return + } + if config.writeDebug == true { + os.Stdout.Write(out) + } + + // Match header for strict services + if r.Header.Get("Content-Type") == "application/json" { + w.Header().Set("Content-Type", "application/json") + } + w.WriteHeader(200) + w.Write(out) +} + func makeRequestHandler(config *WatchdogConfig) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { - parts := strings.Split(config.faasProcess, " ") - - targetCmd := exec.Command(parts[0], parts[1:]...) - writer, _ := targetCmd.StdinPipe() - - res, _ := ioutil.ReadAll(r.Body) - defer r.Body.Close() - - writer.Write(res) - writer.Close() - - out, err := targetCmd.CombinedOutput() - - if err != nil { - if config.writeDebug == true { - log.Println(targetCmd, err) - } - - w.WriteHeader(500) - response := bytes.NewBufferString(err.Error()) - w.Write(response.Bytes()) - return - } - if config.writeDebug == true { - os.Stdout.Write(out) - } - - // Match header for strict services - if r.Header.Get("Content-Type") == "application/json" { - w.Header().Set("Content-Type", "application/json") - } - w.WriteHeader(200) - w.Write(out) + pipeRequest(config, w, r) } else { w.WriteHeader(http.StatusMethodNotAllowed) }