-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
368 lines (289 loc) · 8 KB
/
client.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
)
type jobInfo struct {
Configuration
PID int
StartTime time.Time
ExpiryTime time.Time
Cmd *exec.Cmd
DeadCounter int
}
type clientData struct {
Hostname string
MaximumJobCount int
ServerAddress string
SafeExpression string
MaxMemoryLimit int
MinimumCPUPercent int
KillDeadProcessAfterMinutes int
Jobs map[int]jobInfo
Lock sync.Mutex
}
func newClientData() *clientData {
data := new(clientData)
data.Jobs = make(map[int]jobInfo)
data.Lock = sync.Mutex{}
return data
}
var client *clientData
func startClient() {
client = newClientData()
flag.Bool("client", true, "Sets client mode")
flag.StringVar(&client.Hostname, "hostname", "<unk>", "Client hostname")
flag.IntVar(&client.MaximumJobCount, "maxjobs", 1, "Maximal concurrent job count")
// TODO: remove HACK for modifying of java memory limit
flag.IntVar(&client.MaxMemoryLimit, "memory", 32, "Maximum JRE memory for heap in GBs")
flag.IntVar(&client.MinimumCPUPercent, "minimumcpupercent", 3, "Process must use minimum of X % of CPU to consider as alive")
flag.IntVar(&client.KillDeadProcessAfterMinutes, "killdeadprocessafterminutes", 5, "Kill process after X minutes of dead state")
flag.StringVar(&client.ServerAddress, "master", "http://localhost:8088", "Master address")
flag.StringVar(&client.SafeExpression, "safeexpr", "", "Safe expression") // "java -cp sleepyjava.jar"
workingFolder := flag.String("workdir", "./", "Sets working folder")
flag.Parse()
if client.ServerAddress[len(client.ServerAddress)-1] == '/' {
client.ServerAddress = client.ServerAddress[:len(client.ServerAddress)-1]
}
log.Println("Starting client -", client.ServerAddress)
log.Println("Hostname:", client.Hostname)
log.Println("Max jobs:", client.MaximumJobCount)
log.Println("SafeExpression:", client.SafeExpression)
if workingFolder != nil {
log.Println("Changed workdir", *workingFolder)
if err := os.Chdir(*workingFolder); err != nil {
log.Println("Cant set working folder of", *workingFolder, err)
}
}
go routineJobRequester()
go routineJobChecker()
go routineUsageLogger()
ch := make(chan struct{})
<-ch
}
func routineUsageLogger() {
<-time.After(time.Second * 5)
for {
client.Lock.Lock()
for _, job := range client.Jobs {
cpu, mem := getJobStats(job)
go processLogUsageFor(job.Configuration, cpu, mem)
}
client.Lock.Unlock()
<-time.After(time.Second * 60)
}
}
func routineJobChecker() {
<-time.After(time.Second * 5)
for {
client.Lock.Lock()
for _, job := range client.Jobs {
switch {
case time.Now().After(job.ExpiryTime):
go processTimeoutedJob(job)
case !testIfProcessIsRunning(job.PID):
go processFinishedJob(job)
case testIfProcessIsDead(&job):
go processDeadJob(job)
}
}
client.Lock.Unlock()
<-time.After(time.Second * 15)
}
}
func processTimeoutedJob(job jobInfo) {
log.Println("processTimeoutedJob", job.ID, "PID:", job.PID)
killProcess(job.PID)
err := sendJobFinishNotification(job.Configuration, false)
if err == nil {
client.Lock.Lock()
delete(client.Jobs, job.PID)
client.Lock.Unlock()
} else {
log.Println(err)
}
// else let job stay in map and try to delete it on next cycle
}
func processFinishedJob(job jobInfo) {
log.Println("processFinishedJob", job.ID, "PID:", job.PID)
err := sendJobFinishNotification(job.Configuration, true)
if err == nil {
client.Lock.Lock()
delete(client.Jobs, job.PID)
client.Lock.Unlock()
}
// else let job stay in map and try to delete it on next cycle
}
func processDeadJob(job jobInfo) {
log.Println("processDeadJob", job.ID, "PID:", job.PID)
killProcess(job.PID)
err := sendJobDeadNotification(job.Configuration)
if err == nil {
client.Lock.Lock()
delete(client.Jobs, job.PID)
client.Lock.Unlock()
}
// else let job stay in map and try to delete it on next cycle
}
func routineJobRequester() {
<-time.After(time.Second * 2)
for {
client.Lock.Lock()
shouldGetANewJob := len(client.Jobs) < client.MaximumJobCount
client.Lock.Unlock()
if shouldGetANewJob {
conf, err := requestNewJob()
if err != nil {
log.Println("Request job error", err)
<-time.After(time.Minute * 5)
continue
}
if conf != nil {
go launchNewJob(conf)
}
}
<-time.After(time.Second * 30)
}
}
func launchNewJob(conf *Configuration) {
log.Println("launchNewJob", conf.ID, *conf)
if !satisfiesSafeExpression(conf) {
log.Println("Ignoring job", conf.ID, "safe condition not satisfied")
return
}
// TODO: remove this HACK, modifies configuration, changes java memory limit
for idx, value := range conf.Params {
if value == "-Xmx32g" {
conf.Params[idx] = fmt.Sprintf("-Xmx%dg", client.MaxMemoryLimit)
}
}
var job jobInfo
job.Configuration = *conf
job.StartTime = time.Now()
job.ExpiryTime = time.Now().Add(time.Second*time.Duration(conf.Runtime) + time.Minute*2)
executable := job.Configuration.Params[0]
parameters := job.Configuration.Params[1:]
cmd := exec.Command(executable, parameters...)
err := cmd.Start()
if err != nil {
log.Fatalln("Couldnt start job", *conf, err)
return
}
job.PID = cmd.Process.Pid
job.Cmd = cmd
client.Lock.Lock()
client.Jobs[job.PID] = job
client.Lock.Unlock()
}
func satisfiesSafeExpression(conf *Configuration) bool {
if len(client.SafeExpression) == 0 {
return true
}
command := strings.Join(conf.Params, " ")
return strings.HasPrefix(command, client.SafeExpression)
}
func requestNewJob() (*Configuration, error) {
u, err := url.Parse(fmt.Sprintf("%s/request", client.ServerAddress))
if err != nil {
return nil, err
}
q := u.Query()
q.Set("hostname", client.Hostname)
u.RawQuery = q.Encode()
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusNoContent {
return nil, nil // errors.New("No new jobs available")
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New("Invalid response status code")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var conf Configuration
if !unmarshalJSON(body, &conf) {
return nil, err
}
return &conf, nil
}
func sendJobFinishNotification(conf Configuration, success bool) error {
action := "finish"
if !success {
action = "timeout"
}
// log.Println("job", conf, action)
u, err := url.Parse(fmt.Sprintf("%s/%s", client.ServerAddress, action))
if err != nil {
return err
}
q := u.Query()
q.Set("hostname", client.Hostname)
q.Set("configuration", marshalJSONAsString(conf))
u.RawQuery = q.Encode()
r, err := http.Get(u.String())
// log.Println("ret:", r.StatusCode, r.Status)
if err != nil {
return err
}
if r.StatusCode != http.StatusOK {
return errors.New("Unexpected status code on finish notification")
}
return nil
}
func sendJobDeadNotification(conf Configuration) error {
action := "dead"
// log.Println("job", conf, action)
u, err := url.Parse(fmt.Sprintf("%s/%s", client.ServerAddress, action))
if err != nil {
return err
}
q := u.Query()
q.Set("hostname", client.Hostname)
q.Set("configuration", marshalJSONAsString(conf))
u.RawQuery = q.Encode()
r, err := http.Get(u.String())
// log.Println("ret:", r.StatusCode, r.Status)
if err != nil {
return err
}
if r.StatusCode != http.StatusOK {
return errors.New("Unexpected status code on dead notification")
}
return nil
}
func processLogUsageFor(conf Configuration, cpu int64, mem int64) {
u, err := url.Parse(fmt.Sprintf("%s/usage", client.ServerAddress))
if err != nil {
return
}
q := u.Query()
q.Set("hostname", client.Hostname)
q.Set("cpu", strconv.FormatInt(cpu, 10))
q.Set("mem", strconv.FormatInt(mem, 10))
q.Set("configuration", marshalJSONAsString(conf))
u.RawQuery = q.Encode()
r, err := http.Get(u.String())
// log.Println("ret:", r.StatusCode, r.Status)
if err != nil {
return
}
if r.StatusCode != http.StatusOK {
return //errors.New("Unexpected status code on finish notification")
}
}