Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream command output to logger #346

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 43 additions & 3 deletions webhook.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package main

import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
Expand All @@ -12,6 +15,7 @@ import (
"os/exec"
"path/filepath"
"strings"
"sync"
"time"

"github.com/adnanh/webhook/hook"
Expand Down Expand Up @@ -401,10 +405,46 @@ func handleHook(h *hook.Hook, rid string, headers, query, payload *map[string]in

log.Printf("[%s] executing %s (%s) with arguments %q and environment %s using %s as cwd\n", rid, h.ExecuteCommand, cmd.Path, cmd.Args, envs, cmd.Dir)

out, err := cmd.CombinedOutput()
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't call log.Fatal. Change these to something like:

log.Printf("[%s] error opening stdout: %s", rid, err)
return "", err

}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Fatal(err)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

}
if err := cmd.Start(); err != nil {
log.Fatal(err)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same

}

var out bytes.Buffer

teeout := io.TeeReader(stdout, &out)
teeerr := io.TeeReader(stderr, &out)

var wg sync.WaitGroup
wg.Add(2)

logOut := func(out io.Reader, rid string) {
in := bufio.NewScanner(out)

for in.Scan() {
outln := in.Text()
log.Printf("[%s] command output: %s\n", rid, outln)
}
if err := in.Err(); err != nil {
log.Printf("[%s] error occurred: %+v\n", rid, err)
}

wg.Done()
}

go logOut(teeout, rid)
go logOut(teeerr, rid)

log.Printf("[%s] command output: %s\n", rid, out)
wg.Wait()

err = cmd.Wait()
if err != nil {
log.Printf("[%s] error occurred: %+v\n", rid, err)
}
Expand All @@ -421,7 +461,7 @@ func handleHook(h *hook.Hook, rid string, headers, query, payload *map[string]in

log.Printf("[%s] finished handling %s\n", rid, h.ID)

return string(out), err
return out.String(), err
}

func writeHttpResponseCode(w http.ResponseWriter, rid string, hookId string, responseCode int) {
Expand Down