-
Notifications
You must be signed in to change notification settings - Fork 1
/
zimplayground.go
248 lines (205 loc) · 5.87 KB
/
zimplayground.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
package main
import (
"crypto/sha1"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path"
"syscall"
"time"
)
const (
resultsDir = "results"
modelFilename = "model.zpl"
solutionFilename = "scip.sol"
outputFilename = "output.log"
queueLength = 1024
)
var (
timeLimitSec = flag.Int("time", 3*60, "SCIP time limit (s)")
memoryLimitMB = flag.Int("mem", 100, "SCIP memory limit (MB)")
sleepTime = flag.Int("sleep", 100, "sleep before redirect to results (ms)")
address = flag.String("address", ":8080", "hostname:port of server")
processLimit = flag.Int("processes", 4, "limit on number of SCIP processes")
scipExec = flag.String("scipExec", "scip", "(path to) scip executable")
)
// A Job is identified by the path to run in
type Job struct {
dir string
}
// Sem is a channel-based semaphore
type Sem chan int
// the solveHandler submits jobs here, the workers get them
var queue = make(chan Job, queueLength)
// take jobs from queue and start processes
// cf. github.com/golang/go/wiki/BoundingResourceUse
func processQueue(sem Sem) {
for {
sem <- 1 // block until there's capacity to start a new process
job := <-queue
go runSolver(job, sem) // don't wait for solver to finish.
}
}
// run subprocess and wait to finish
func runSolver(job Job, sem Sem) {
if _, err := os.Stat(job.dir); os.IsNotExist(err) {
return
}
outputFile, err := os.Create(path.Join(job.dir, outputFilename))
if err != nil {
return
}
defer outputFile.Close()
commands := fmt.Sprintf("set limits time %d "+
"set limits memory %d "+
"read %s "+
"optimize "+
"display statistics "+
"write solution %s "+
"quit",
*timeLimitSec, *memoryLimitMB,
modelFilename, solutionFilename)
cmd := exec.Command(*scipExec, "-c", commands)
cmd.Dir = job.dir
cmd.Stdout = outputFile
cmd.Stderr = outputFile
if err := cmd.Start(); err != nil {
log.Printf("Solver in %s failed to start.", job.dir)
}
log.Printf("Solver in %s started with PID %d", job.dir, cmd.Process.Pid)
if err := cmd.Wait(); err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// The program has exited with an exit code != 0
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
log.Printf("Solver in %s failed with code %d.",
job.dir, status.ExitStatus())
fmt.Fprintf(outputFile, "Terminated with return code %d!",
status.ExitStatus())
}
} else {
log.Print("Solver in %s failed: %v", job.dir, err)
}
}
log.Printf("Solver finished in %s", job.dir)
<-sem // done, resource freed
}
// submit job to queue
func submit(job Job) (err error) {
if _, err := os.Stat(job.dir); os.IsNotExist(err) {
return err
}
log.Printf("Submitting job for %s", job.dir)
// submit job to queue, never block
go func() {
queue <- job
}()
return nil
}
// The Input contains the whole model text.
type Input struct {
Model string
}
func inputHandler(w http.ResponseWriter, r *http.Request) {
// optional prefilled model text
prefilled := r.FormValue("prefilled")
input := &Result{Model: prefilled}
err := inputTemplate.Execute(w, input)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func solveHandler(w http.ResponseWriter, r *http.Request) {
model := r.FormValue("model")
hash := fmt.Sprintf("%x", sha1.Sum([]byte(model)))
log.Printf("Request for model %s", hash)
dir := path.Join(resultsDir, hash)
if _, err := os.Stat(dir); os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
filename := path.Join(dir, modelFilename)
err = ioutil.WriteFile(filename, []byte(model), 0644)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = submit(Job{dir})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// add short sleep so that result might already exist when we
// finally redirect.
time.Sleep(time.Duration(*sleepTime) * time.Millisecond)
http.Redirect(w, r, "/result/"+hash, http.StatusFound)
}
// The Result contains several segments of text, including the input,
// log and solution
type Result struct {
Hash string
Model string
Solution string
Output string
}
func resultHandler(w http.ResponseWriter, r *http.Request) {
hash := r.URL.Path[len("/result/"):]
dir := path.Join(resultsDir, hash)
if _, err := os.Stat(dir); os.IsNotExist(err) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res := &Result{Hash: hash, Model: "", Solution: "", Output: ""}
model := path.Join(dir, modelFilename)
if _, err := os.Stat(model); err == nil {
content, err := ioutil.ReadFile(model)
if err == nil {
res.Model = string(content)
}
}
sol := path.Join(dir, solutionFilename)
if _, err := os.Stat(sol); err == nil {
content, err := ioutil.ReadFile(sol)
if err == nil {
res.Solution = string(content)
}
}
out := path.Join(dir, outputFilename)
if _, err := os.Stat(out); err == nil {
content, err := ioutil.ReadFile(out)
if err == nil {
res.Output = string(content)
}
}
if err := resultTemplate.Execute(w, res); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
flag.Parse()
// check that solver exists
scipPath, err := exec.LookPath(*scipExec)
if err != nil {
log.Fatalf("No solver executable found at %s!", *scipExec)
} else {
log.Printf("Using solver executable at %s.", scipPath)
}
// semaphore for number of go routines starting processes
var sem = make(Sem, *processLimit)
go processQueue(sem)
http.HandleFunc("/", inputHandler)
http.HandleFunc("/input/", inputHandler)
http.HandleFunc("/solve/", solveHandler)
http.HandleFunc("/result/", resultHandler)
http.Handle("/static/",
http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
log.Printf("listening on %s", *address)
log.Fatal(http.ListenAndServe(*address, nil))
}