added error handling

This commit is contained in:
Mark Joling 2018-10-10 12:47:20 +02:00 committed by GitHub
parent 8dcfea4b90
commit a14a810925
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 101 additions and 92 deletions

View File

@ -1,136 +1,145 @@
package main package main
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "log"
"os" "net/http"
"os/exec" "os"
"strings" "os/exec"
"strconv" "strings"
"time" "strconv"
"time"
) )
type inbound struct { type inbound struct {
Language string `json:"language"` Language string `json:"language"`
Source string `json:"source"` Source string `json:"source"`
Args []string `json:"args"` Args []string `json:"args"`
} }
type problem struct { type problem struct {
Code string `json:"code"` Code string `json:"code"`
Message string `json:"message"` Message string `json:"message"`
} }
type outbound struct { type outbound struct {
Generator string `json:"instance"` Generator string `json:"instance"`
Ran bool `json:"ran"` Ran bool `json:"ran"`
Output string `json:"output"` Output string `json:"output"`
} }
var instance int var instance int
func main() { func main() {
port := 2000 port := 2000
if len(os.Args) > 1 { if len(os.Args) > 1 {
if i, err := strconv.Atoi(os.Args[1]); err == nil { if i, err := strconv.Atoi(os.Args[1]); err == nil {
instance = i instance = i
port += i port += i
} }
} else { } else {
instance = 0 instance = 0
} }
fmt.Println("starting api on port", port) fmt.Println("starting api on port", port)
http.HandleFunc("/execute", Execute) http.HandleFunc("/execute", Execute)
http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil) err := http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil); if err != nil{
log.Fatal(err)
}
} }
func Execute(res http.ResponseWriter, req *http.Request) { func Execute(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "application/json") res.Header().Set("Content-Type", "application/json")
// get json // get json
inbound := inbound{} inbound := inbound{}
message := json.NewDecoder(req.Body) message := json.NewDecoder(req.Body)
message.Decode(&inbound) message.Decode(&inbound)
whitelist := []string{ whitelist := []string{
"c", "c",
"cpp", "c++", "cpp", "c++",
"c#", "csharp", "cs", "c#", "csharp", "cs",
"go", "go",
"java", "java",
"nasm", "asm", "nasm", "asm",
"javascript", "js", "node", "javascript", "js", "node",
"php", "php",
"python", "python2", "python3", "python", "python2", "python3",
"r", "r",
"ruby", "ruby",
} }
// check if the supplied language is supported // check if the supplied language is supported
// now calls function and returns // now calls function and returns
for _, lang := range whitelist { for _, lang := range whitelist {
if lang == inbound.Language { if lang == inbound.Language {
launch(inbound, res) launch(inbound, res)
return return
} }
} }
// now only called when the language is not supported // now only called when the language is not supported
problem := problem{ problem := problem{
Code: "unsupported_language", Code: "unsupported_language",
Message: inbound.Language + " is not supported by Piston", Message: inbound.Language + " is not supported by Piston",
} }
pres, _ := json.Marshal(problem) pres, err := json.Marshal(problem); if err != nil{
log.Fatal(err)
}
res.Write(pres) res.Write(pres)
} }
func launch(request inbound, res http.ResponseWriter) { func launch(request inbound, res http.ResponseWriter) {
stamp := time.Now().UnixNano() stamp := time.Now().UnixNano()
// write the code to temp dir // write the code to temp dir
srcfile := fmt.Sprintf("/tmp/%d.code", stamp) srcfile := fmt.Sprintf("/tmp/%d.code", stamp)
ioutil.WriteFile(srcfile, []byte(request.Source), 0644) ioutil.WriteFile(srcfile, []byte(request.Source), 0644)
// set up the arguments to send to the execute command // set up the arguments to send to the execute command
var args []string var args []string
args = append(args, request.Language) args = append(args, request.Language)
args = append(args, srcfile) args = append(args, srcfile)
args = append(args, strings.Join(request.Args, "\n")) args = append(args, strings.Join(request.Args, "\n"))
// set up the execution // set up the execution
cmd := exec.Command("../docker/execute", args...) cmd := exec.Command("../docker/execute", args...)
cmd.Env = os.Environ() cmd.Env = os.Environ()
if instance > 0 { if instance > 0 {
cmd.Env = append(cmd.Env, fmt.Sprintf("SOCKET=unix:///var/run/docker-%d.sock", instance)) cmd.Env = append(cmd.Env, fmt.Sprintf("SOCKET=unix:///var/run/docker-%d.sock", instance))
} }
// capture out/err // capture out/err
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout cmd.Stdout = &stdout
cmd.Stderr = &stderr cmd.Stderr = &stderr
err := cmd.Run() err := cmd.Run(); if err != nil{
log.Fatal(err)
}
// prepare response // prepare response
outbound := outbound{ outbound := outbound{
Generator: fmt.Sprintf("docker-%d", instance), Generator: fmt.Sprintf("docker-%d", instance),
Ran: err == nil, Ran: err == nil,
Output: strings.TrimSpace(stdout.String()), Output: strings.TrimSpace(stdout.String()),
} }
response, _ := json.Marshal(outbound) response, err:= json.Marshal(outbound); if err != nil{
log.Fatal(err)
}
res.Write(response) res.Write(response)
} }