-
Notifications
You must be signed in to change notification settings - Fork 2
/
compute.go
292 lines (243 loc) · 6.14 KB
/
compute.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
package main
/*
Compute service runs jobs on this node's GPUs, if any.
*/
import (
"fmt"
"io"
"log"
"os/exec"
"strings"
"time"
"github.com/mumax/3/httpfs"
"github.com/mumax/3/util"
)
var (
MumaxVersion string
GPUs []string
Processes = make(map[string]*Process) // job id -> process
)
// Process is a running simulation process
type Process struct {
*exec.Cmd
Start time.Time
Out io.WriteCloser
ID string
OutputURL string
GUI string
Killed bool
}
func (p *Process) Host() string {
return JobHost(p.OutputURL)
}
// Runs a compute service on this node, if GPUs are available.
// The compute service asks storage nodes for a job, runs it,
// saves results over httpfs and notifies storage when ready.
func RunComputeService() {
if len(GPUs) == 0 {
return
}
// queue of available GPU numbers
idle := make(chan int, len(GPUs))
for i := range GPUs {
idle <- i
}
for {
gpu := <-idle // take an available GPU
GUIAddr := fmt.Sprint(thisHost+":", GUI_PORT+gpu)
ID := WaitForJob() // take an available job
go func() {
defer func() {
// remove from "running" list
WLock()
delete(Processes, ID)
WUnlock()
// add GPU number back to idle stack
idle <- gpu
}()
p := NewProcess(ID, gpu, GUIAddr)
if p == nil {
return
}
WLock()
Processes[ID] = p
WUnlock()
p.Run()
_, err := RPCCall(JobHost(ID), "UpdateJob", ID)
if err != nil {
log.Println(err)
}
}()
}
}
func WaitForJob() string {
ID := FindJob()
for ID == "" {
time.Sleep(2 * time.Second) // TODO: don't poll
ID = FindJob()
}
return ID
}
func FindJob() string {
// quickly list peers first
RLock()
p := make([]string, 0, len(peers))
for addr, _ := range peers {
p = append(p, addr)
}
RUnlock()
// TODO: pick peers fairly
// then do slow RPC calls without blocking the rest of the program
for _, addr := range p {
ID, _ := RPCCall(addr, "GiveJob", thisAddr)
if ID != "" {
return ID
}
}
return ""
}
// RPC-callable function kills job corresponding to given job id.
// The job has to be running on this node.
func Kill(id string) string {
log.Println("KILL", id)
WLock() // modifies Cmd state
defer WUnlock()
job := Processes[id]
if job == nil {
return fmt.Sprintf("kill %v: job not running.", id)
}
job.Killed = true
err := job.Cmd.Process.Kill()
if err != nil {
return err.Error()
}
return "" // OK
}
// prepare exec.Cmd to run mumax3 compute process
func NewProcess(ID string, gpu int, webAddr string) *Process {
// prepare command
inputURL := "http://" + ID
command := *flag_mumax
gpuFlag := fmt.Sprint(`-gpu=`, gpu)
httpFlag := fmt.Sprint(`-http=`, webAddr)
cacheFlag := fmt.Sprint(`-cache=`, *flag_cachedir)
forceFlag := `-f=0`
cmd := exec.Command(command, gpuFlag, httpFlag, cacheFlag, forceFlag, inputURL)
// Pipe stdout, stderr to log file over httpfs
outDir := util.NoExt(inputURL) + ".out"
errMkdir := httpfs.Mkdir(outDir)
if errMkdir != nil {
SetJobError(ID, errMkdir)
log.Println("makeProcess", errMkdir)
j := JobByName(ID)
if j != nil {
j.Reque()
}
return nil
}
out, errD := httpfs.Create(outDir + "/stdout.txt")
if errD != nil {
SetJobError(ID, errD)
log.Println("makeProcess", errD)
j := JobByName(ID)
if j != nil {
j.Reque()
}
return nil
}
cmd.Stderr = out
cmd.Stdout = out
return &Process{ID: ID, Cmd: cmd, Start: time.Now(), Out: out, OutputURL: OutputDir(inputURL), GUI: webAddr}
}
func (p *Process) Run() {
log.Println("=> exec ", p.Path, p.Args)
defer p.Out.Close()
httpfs.Put(p.OutputURL+"host", []byte(thisAddr))
startTime := AskTime(p.Host())
httpfs.Put(p.OutputURL+"start", []byte(startTime.Format(time.UnixDate)))
WLock() // Cmd.Start() modifies state
err1 := p.Cmd.Start() // err?
WUnlock()
if err1 != nil {
SetJobError(p.ID, err1)
}
timeOffset := time.Now().Sub(startTime) // our clock is most likely out-of-sync with host
tick := time.NewTicker(KeepaliveInterval)
// need initial alive in case watchdog sniffs between start and first alive tick
httpfs.Put(p.OutputURL+"alive", []byte(time.Now().Add(timeOffset).Format(time.UnixDate)))
go func() {
for t := range tick.C {
httpfs.Put(p.OutputURL+"alive", []byte(t.Add(timeOffset).Format(time.UnixDate)))
}
}()
err2 := p.Cmd.Wait()
if err1 == nil && err2 != nil {
SetJobError(p.ID, err2)
}
tick.Stop()
status := -1
// TODO: determine proper status number
if err1 != nil || err2 != nil {
log.Println(p.Path, p.Args, err1, err2)
status = 1
} else {
status = 0
}
if p.Killed {
httpfs.Put(p.OutputURL+"killed", []byte(time.Now().Format(time.UnixDate)))
} else {
httpfs.Put(p.OutputURL+"exitstatus", []byte(fmt.Sprint(status)))
}
stopTime := AskTime(p.Host())
nanos := stopTime.Sub(startTime).Nanoseconds()
httpfs.Put(p.OutputURL+"duration", []byte(fmt.Sprint(nanos)))
if status == 0 {
ret, err := RPCCall(p.Host(), "AddFairShare", JobUser(p.ID)+"/"+fmt.Sprint(nanos/1e9))
if err != nil || ret != "" {
log.Println("***ERR: AddFairShare", JobUser(p.ID), ret, err)
}
}
return
}
func (p *Process) Duration() time.Duration { return Since(time.Now(), p.Start) }
func DetectGPUs() {
if GPUs != nil {
panic("multiple DetectGPUs() calls")
}
for i := 0; i < MAXGPU; i++ {
gpuflag := fmt.Sprint("-gpu=", i)
out, err := exec.Command(*flag_mumax, "-test", gpuflag).Output()
if err == nil {
info := string(out)
if strings.HasSuffix(info, "\n") {
info = info[:len(info)-1]
}
log.Println("gpu", i, ":", info)
GPUs = append(GPUs, info)
}
}
}
func DetectMumax() {
out, err := exec.Command(*flag_mumax, "-test", "-v").CombinedOutput()
info := string(out)
if err == nil {
split := strings.SplitN(info, "\n", 2)
version := split[0]
log.Println("have", version)
MumaxVersion = version
} else {
MumaxVersion = fmt.Sprint(*flag_mumax, "-test", ": ", err, info)
}
}
// RPC-callable function, answers by this node's time
func WhatsTheTime(string) string {
return time.Now().Format(time.UnixDate)
}
func AskTime(host string) time.Time {
str, _ := RPCCall(host, "WhatsTheTime", "")
return parseTime(str)
}
func parseTime(str string) time.Time {
t, _ := time.Parse(time.UnixDate, str)
return t
}