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

feat(init): provide and endpoint for getting logs of running processes #9

Merged
merged 1 commit into from
Mar 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions initramfs/src/init/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ func main() {
http.HandleFunc("/kubeconfig", kubernetes.KubeConfigHandleFunc)
// An endpoint for listing the running containers.
http.HandleFunc("/containers", docker.ContainersHandleFunc)
// An endpoint for streaming a process' stdout/stderr.
http.HandleFunc("/logs/", process.StreamHandleFunc)
// TODO: TLS only.
http.ListenAndServe(":8080", nil)
}
40 changes: 37 additions & 3 deletions initramfs/src/init/pkg/process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package process

import (
"fmt"
"io"
"log"
"os"
"net/http"
"os/exec"
"path"
"strings"
"time"

"github.com/autonomy/dianemo/initramfs/src/init/pkg/constants"
Expand All @@ -18,6 +21,8 @@ const (
OnceAndOnlyOnce
)

var outputstreams = map[string]*io.PipeReader{}

type Process interface {
Cmd() (string, []string)
Condition() func() (bool, error)
Expand All @@ -34,9 +39,13 @@ func NewManager() *Manager {
func (m *Manager) build(proc Process) (*exec.Cmd, error) {
name, args := proc.Cmd()
cmd := exec.Command(name, args...)
// Set the environment for the process.
cmd.Env = append(proc.Env(), fmt.Sprintf("PATH=%s", constants.PATH))
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// Create a buffer for the stdout and stderr of the process.
r, w := io.Pipe()
outputstreams[path.Base(name)] = r
cmd.Stdout = w
cmd.Stderr = w

return cmd, nil
}
Expand All @@ -61,6 +70,31 @@ func (m *Manager) Start(proc Process) error {
return nil
}

func StreamHandleFunc(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(r.URL.Path, "/logs/")
stream, ok := outputstreams[name]
if !ok {
w.WriteHeader(http.StatusNotFound)
}

buffer := make([]byte, 1024)
for {
n, err := stream.Read(buffer)
if err != nil {
stream.Close()
break
}
data := buffer[0:n]
w.Write(data)
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
for i := 0; i < n; i++ {
buffer[i] = 0
}
}
}

func (m *Manager) waitAndRestart(proc Process) {
cmd, err := m.build(proc)
if err != nil {
Expand Down