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

Provide access to sandbox logs #91

Merged
merged 5 commits into from
Jun 9, 2016
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
109 changes: 21 additions & 88 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,15 @@ package handler
import (
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"

"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/klarna/eremetic/assets"
"github.com/klarna/eremetic/database"
"github.com/klarna/eremetic/formatter"
"github.com/klarna/eremetic/scheduler"
"github.com/klarna/eremetic/types"
)
Expand All @@ -37,20 +33,6 @@ func Create(scheduler types.Scheduler, database database.TaskDB) Handler {
}
}

func absURL(r *http.Request, path string) string {
scheme := r.Header.Get("X-Forwarded-Proto")
if scheme == "" {
scheme = "http"
}

url := url.URL{
Scheme: scheme,
Host: r.Host,
Path: path,
}
return url.String()
}

// AddTask handles adding a task to the queue
func (h Handler) AddTask() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -88,6 +70,27 @@ func (h Handler) AddTask() http.HandlerFunc {
}
}

// GetFromSandbox fetches a file from the sandbox of the agent that ran the task
func (h Handler) GetFromSandbox(file string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
taskID := vars["taskId"]
task, _ := h.database.ReadTask(taskID)

status, data := getFile(file, task)

if status != http.StatusOK {
writeJSON(status, data, w)
return
}

defer data.Close()
w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
w.WriteHeader(http.StatusOK)
io.Copy(w, data)
}
}

// GetTaskInfo returns information about the given task.
func (h Handler) GetTaskInfo() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -119,73 +122,3 @@ func (h Handler) ListRunningTasks() http.HandlerFunc {
writeJSON(200, tasks, w)
}
}

func handleError(err error, w http.ResponseWriter, message string) {
if err == nil {
return
}

errorMessage := ErrorDocument{
err.Error(),
message,
}

if err = writeJSON(422, errorMessage, w); err != nil {
logrus.WithError(err).WithField("message", message).Panic("Unable to respond")
}
}

func writeJSON(status int, data interface{}, w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(data)
}

func renderHTML(w http.ResponseWriter, r *http.Request, task types.EremeticTask, taskID string) {
var templateFile string

data := make(map[string]interface{})
funcMap := template.FuncMap{
"ToLower": strings.ToLower,
"FormatTime": formatter.FormatTime,
}

if reflect.DeepEqual(task, (types.EremeticTask{})) {
templateFile = "error_404.html"
data["TaskID"] = taskID
} else {
templateFile = "task.html"
data = makeMap(task)
}

source, _ := assets.Asset(fmt.Sprintf("templates/%s", templateFile))
tpl, err := template.New(templateFile).Funcs(funcMap).Parse(string(source))

if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logrus.WithError(err).WithField("template", templateFile).Error("Unable to render template")
return
}

err = tpl.Execute(w, data)
}

func makeMap(task types.EremeticTask) map[string]interface{} {
data := make(map[string]interface{})

data["TaskID"] = task.ID
data["CommandEnv"] = task.Environment
data["CommandUser"] = task.User
data["Command"] = task.Command
// TODO: Support more than docker?
data["ContainerImage"] = task.Image
data["FrameworkID"] = task.FrameworkId
data["Hostname"] = task.Hostname
data["Name"] = task.Name
data["SlaveID"] = task.SlaveId
data["Status"] = task.Status
data["CPU"] = fmt.Sprintf("%.2f", task.TaskCPUs)
data["Memory"] = fmt.Sprintf("%.2f", task.TaskMem)

return data
}
117 changes: 117 additions & 0 deletions handler/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -210,4 +211,120 @@ func TestHandling(t *testing.T) {
So(wr.Code, ShouldEqual, 422)
})
})

Convey("Get Files from sandbox", t, func() {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "mocked")
}))
defer s.Close()

addr := strings.Split(s.Listener.Addr().String(), ":")
ip := addr[0]
port, _ := strconv.ParseInt(addr[1], 10, 32)
id := "eremetic-task.1234"

task := types.EremeticTask{
TaskCPUs: 0.2,
TaskMem: 0.5,
Command: "test",
Image: "test",
Status: status,
ID: id,
SandboxPath: "/tmp",
AgentIP: ip,
AgentPort: int32(port),
}
db.PutTask(&task)
wr := httptest.NewRecorder()
m := mux.NewRouter()

Convey("stdout", func() {
r, _ := http.NewRequest("GET", "/task/eremetic-task.1234/stdout", nil)
m.HandleFunc("/task/{taskId}/stdout", h.GetFromSandbox("stdout"))
m.ServeHTTP(wr, r)

So(wr.Code, ShouldEqual, http.StatusOK)
So(wr.Header().Get("Content-Type"), ShouldEqual, "text/plain; charset=UTF-8")

body, _ := ioutil.ReadAll(wr.Body)
So(string(body), ShouldEqual, "mocked")
})

Convey("stderr", func() {
r, _ := http.NewRequest("GET", "/task/eremetic-task.1234/stderr", nil)
m.HandleFunc("/task/{taskId}/stderr", h.GetFromSandbox("stderr"))
Copy link
Collaborator

Choose a reason for hiding this comment

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

I like this

🍰 👍


m.ServeHTTP(wr, r)

So(wr.Code, ShouldEqual, http.StatusOK)
So(wr.Header().Get("Content-Type"), ShouldEqual, "text/plain; charset=UTF-8")

body, _ := ioutil.ReadAll(wr.Body)
So(string(body), ShouldEqual, "mocked")
})

Convey("No Sandbox path", func() {
r, _ := http.NewRequest("GET", "/task/eremetic-task.1234/stdout", nil)
m.HandleFunc("/task/{taskId}/stdout", h.GetFromSandbox("stdout"))

task := types.EremeticTask{
TaskCPUs: 0.2,
TaskMem: 0.5,
Command: "test",
Image: "test",
Status: status,
ID: id,
SandboxPath: "",
AgentIP: ip,
AgentPort: int32(port),
}
db.PutTask(&task)

m.ServeHTTP(wr, r)

So(wr.Code, ShouldEqual, http.StatusNoContent)
})

})

Convey("renderHTML", t, func() {
id := "eremetic-task.1234"

task := types.EremeticTask{
TaskCPUs: 0.2,
TaskMem: 0.5,
Command: "test",
Image: "test",
Status: status,
ID: id,
}

wr := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/task/eremetic-task.1234", nil)

renderHTML(wr, r, task, id)

body, _ := ioutil.ReadAll(wr.Body)
So(body, ShouldNotBeEmpty)
So(string(body), ShouldContainSubstring, "html")
})

Convey("makeMap", t, func() {
task := types.EremeticTask{
TaskCPUs: 0.2,
TaskMem: 0.5,
Command: "test",
Image: "test",
Status: status,
ID: "eremetic-task.1234",
}

data := makeMap(task)
So(data, ShouldContainKey, "CPU")
So(data, ShouldContainKey, "Memory")
So(data, ShouldContainKey, "Status")
So(data, ShouldContainKey, "ContainerImage")
So(data, ShouldContainKey, "Command")
So(data, ShouldContainKey, "TaskID")
})
}
Loading