forked from fnasim/WebCompile
/
webcompile.go
333 lines (260 loc) · 8.09 KB
/
webcompile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package main
/*
WebCompile v0.1
//github.com/fnasim/webcompile
Design: On startup, create N (ConcurrentConatiners) docker containers. At each run, container is
discarded and recreated. So any given time we should have N containers available
in the system in idle state. This makes execution blazing fast.
More info: https://github.com/fnasim/WebCompile
*/
import (
"io"
"net/http"
"log"
"os/exec"
"os"
"os/signal"
"github.com/kjk/betterguid"
"time"
"encoding/json"
"fmt"
"strings"
"io/ioutil"
"github.com/fsouza/go-dockerclient"
)
// Configuration
// # of concurrent containers to start
const ConcurrentContainers = 5
// docker image to use
const DockerImage = "mono"
// maximum code execution time
const ExecutionTimeout = 5 * time.Second
// limit code size
const MaximumCodeSizeInBytes = 8 * 1024;
// allow requests from other sites, empty to disable
const CorsHeader = "*";
// run the compile server on this port
const Port = "8000";
// command to run on the container to compile code
const ShellCommand = "mcs -out:/home/code/code.exe /home/code/source/code.cs; startTime=$(date +%s%3N); if [[ $? == 0 ]]; then mono /home/code/code.exe; endTime=$(date +%s%3N); diff=$(($endTime-$startTime)); echo Code Execution: $diff ms; fi";
// local path which is mounted on the docker image for writing code
var PathForCodeStorage string // current working directoy or exact path, should be writable
var PathSuffix = "runs";
// globals
var DockerClient *docker.Client
type CompileResponse struct {
Output string
LatencyInMS int64
ErrorString string
Timeout bool
}
type ContainerInfo struct {
ID string
Path string
}
var AvailableContainers chan ContainerInfo
func start(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "text/html")
io.WriteString(w,
"<form method=POST action=compile>" +
"<textarea name=code rows=10 cols=50>public class X { public static void Main() { int sum = 0; for(int i = 0; i < 1000; i++) sum += i; System.Console.WriteLine(\"Sum: \" + sum); } }</textarea><br>" +
"<input type=submit></form>")
}
func compile(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "application/json")
if(len(CorsHeader) > 0) {
w.Header().Set("Access-Control-Allow-Origin", CorsHeader)
}
// language := r.PostFormValue("language")
code := r.PostFormValue("code")
codeSize := len(code)
if(codeSize <= 0 || codeSize > MaximumCodeSizeInBytes) {
compileResponseError(w, "Code is malformed. May be max limit")
return
}
out, err, elapsed, timedOut := executeCodeOnDocker(code)
compileResponse(
w,
out,
int64(elapsed / time.Millisecond),
err,
timedOut)
}
func executeCodeOnDocker(code string) (string, string, time.Duration, bool) {
// get a prepped container containers
log.Print("Acquiring container")
containerInfo := <- AvailableContainers
containerId, runPath := containerInfo.ID, containerInfo.Path
defer func() {
go createNewContainer()
go destroyContainer(containerId, runPath)
}()
codePath := runPath + "/code.cs"
fo, err := os.Create(codePath)
if err != nil {
return "", "Cannot create code file", time.Second, false
}
fo.WriteString(code)
fo.Close()
log.Print("Running container from path: " + runPath)
startTime := time.Now()
args := []string { "exec", containerId, "/bin/bash", "-c", ShellCommand}
cmd := exec.Command("docker", args...)
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
err = cmd.Start()
if err != nil {
log.Print("Command start: ", err)
}
timedOut := false
timer := time.AfterFunc(ExecutionTimeout, func() {
timedOut = true
stdin.Close()
stdout.Close()
stderr.Close()
err := cmd.Process.Kill()
if err != nil {
log.Print("Cannot kill process: ", err)
}
})
out, _ := ioutil.ReadAll(stdout)
errout, _ := ioutil.ReadAll(stderr)
cmd.Wait()
timer.Stop()
elapsedTime := time.Since(startTime)
return string(out), string(errout), elapsedTime, timedOut
}
func destroyContainer(containerId string, path string) {
log.Print("Destroy " + containerId)
err := DockerClient.KillContainer(docker.KillContainerOptions { ID: containerId })
if err != nil {
log.Print("KillContainer: ", err)
}
err = DockerClient.RemoveContainer(docker.RemoveContainerOptions { ID: containerId })
if err != nil {
log.Print("RemoveContainer: ", err)
}
os.RemoveAll(path)
}
func createNewContainer() {
tmpPath := createTempPath()
cmd := "docker"
args := []string { "run", "-d", "-v", tmpPath + ":/home/code/source", "-t", DockerImage,"/bin/bash"}
startTime := time.Now()
out, err := exec.Command(cmd, args...).Output()
elapsedTime := time.Since(startTime)
if err != nil {
log.Print("CreateContainer: ", err)
return
}
containerId := strings.TrimSpace(string(out))
log.Print("New container: " + containerId + " in " + elapsedTime.String())
AvailableContainers <- ContainerInfo {ID: containerId, Path: tmpPath}
}
func compileResponse(w http.ResponseWriter, output string, latency int64, error string, timeout bool) {
res := &CompileResponse {
Output: output,
LatencyInMS: latency,
ErrorString: error,
Timeout: timeout}
resJson, _ := json.Marshal(res)
response := string(resJson)
io.WriteString(w, response)
}
func compileResponseError(w http.ResponseWriter, error string) {
res := &CompileResponse {
Output: "",
LatencyInMS: 0,
ErrorString: error,
Timeout: false,
}
resJson, _ := json.Marshal(res)
response := string(resJson)
io.WriteString(w, response)
}
func main() {
log.Print("Starting up")
AvailableContainers = make(chan ContainerInfo, ConcurrentContainers)
pwd, err := os.Getwd()
if err != nil {
log.Fatal("Cannot get present directory")
return
}
PathForCodeStorage = pwd + "/" + PathSuffix
client, err := docker.NewClientFromEnv()
if err != nil {
log.Fatal("Cannot create docker client: ", err)
}
DockerClient = client
imgs, err := client.ListImages(docker.ListImagesOptions{ All: false })
if err != nil {
log.Fatal(err)
}
for _, img := range imgs {
log.Print(fmt.Sprintf("[ID %s] [Name %s]", img.ID, img.RepoTags))
}
// list of running containers
containers, err := client.ListContainers(docker.ListContainersOptions {All: false})
for _, container := range containers {
log.Print(fmt.Sprintf("[ID %s] [Image %s] [Command %s]", container.ID, container.Image, container.Command))
}
for i := 0; i < ConcurrentContainers; i++ {
go createNewContainer()
}
defer destroyContainers()
log.Print("Path for new folders: " + PathForCodeStorage)
log.Print("Listening on " + Port)
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
go func() {
<-sig
log.Print("BYE")
destroyContainers()
os.Exit(0)
}()
mux := http.NewServeMux();
mux.HandleFunc("/", start)
mux.HandleFunc("/compile", compile)
err = http.ListenAndServe(":" + Port, mux)
if err != nil {
log.Fatal("ListenAndServe failed: ", err)
}
}
func destroyContainers() {
close(AvailableContainers)
// destroy all active containers
for containerInfo := range AvailableContainers {
destroyContainer(containerInfo.ID, containerInfo.Path)
}
}
func createTempPath() string {
uuid := betterguid.New()
date := time.Now().Format("2006-01-15")
runPath := PathForCodeStorage + "/" + date + uuid
err := os.Mkdir(runPath, 0777)
if err != nil {
log.Print("Could not create temporary path: ", runPath)
log.Print(err)
return ""
}
return runPath
}
func cp(dst, src string) error {
s, err := os.Open(src)
if err != nil {
return err
}
// no need to check errors on read only file, we already got everything
// we need from the filesystem, so nothing can go wrong now.
defer s.Close()
d, err := os.Create(dst)
if err != nil {
return err
}
if _, err := io.Copy(d, s); err != nil {
d.Close()
return err
}
return d.Close()
}