-
Notifications
You must be signed in to change notification settings - Fork 8
/
api.go
428 lines (355 loc) · 8.33 KB
/
api.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright 2016 Mark Clarkson
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
)
// Inbound
type JobIn struct {
ScriptSource []byte // From manager
ScriptName string // From manager
Args string // From manager
EnvVars string // From manager
//NotifURL string // From manager
JobID int64 // From manager
Key string // From manager
Type int64 // From manager: 1 - user job, 2 - system job
Guid string // Locally created
Pid int64 // Locally created
Errors int64 // Locally created
UserCancel bool // Used locally only
}
// Outbound: All created locally
type JobOut struct {
Id int64 // JobID
Status int64
StatusReason string
StatusPercent int64
Errors int64
}
type OutputLine struct {
Id int64
Serial int64
JobId int64
Text string
//Type int64 // 0 - output, 1 - error output
}
type Api struct {
jobs []JobIn
mutex *sync.Mutex
loginmutex *sync.Mutex
guid string
}
type ApiError struct {
details string
}
const (
STATUS_UNKNOWN = iota
STATUS_NOTSTARTED
STATUS_USERCANCELLED
STATUS_SYSCANCELLED
STATUS_INPROGRESS
STATUS_OK
STATUS_ERROR
)
type Login struct {
Login string
Password string
}
// Shared transport, to ensure connections are reused
var tr *http.Transport
func (api *Api) sendOutputLine(job JobIn, line string, serial int64) error {
data := OutputLine{}
data.Serial = serial
data.JobId = job.JobID
data.Text = line
r := &http.Response{}
tries := 0
for {
jsondata, err := json.Marshal(data)
if err != nil {
return ApiError{"Internal error: Manager login, JSON Encode"}
}
resp, err := POST(jsondata,
config.User+"/"+api.Guid()+"/outputlines")
if err != nil {
return ApiError{err.Error()}
}
r = resp
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
// Retry login (only once) on a 401
if resp.StatusCode != 401 {
break
}
if tries == 1 {
break
}
tries = tries + 1
api.Login()
}
return nil
}
func (api *Api) sendStatus(jobin JobIn, jobout JobOut) error {
tries := 0
r := &http.Response{}
for {
jsondata, err := json.Marshal(jobout)
if err != nil {
return ApiError{"Internal error: sendStatus, JSON Encode"}
}
resp, err := PUT(jsondata, config.User+"/"+api.Guid()+"/"+
"jobs/"+fmt.Sprintf("%d", jobin.JobID))
if err != nil {
return ApiError{err.Error()}
}
r = resp
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
// Retry login (only once) on a 401
if resp.StatusCode != 401 {
break
}
if tries == 1 {
break
}
tries = tries + 1
api.Login()
}
if r.StatusCode != 200 {
// There was an error
// Read the response body for details
var body []byte
defer r.Body.Close()
if b, err := ioutil.ReadAll(r.Body); err != nil {
txt := fmt.Sprintf("Error reading Body ('%s').", err.Error())
return ApiError{txt}
} else {
body = b
}
type myErr struct {
Error string
}
errstr := myErr{}
if err := json.Unmarshal(body, &errstr); err != nil {
txt := fmt.Sprintf("Error decoding JSON ('%s')", err.Error())
return ApiError{txt}
}
txt := fmt.Sprintf("SendStatus to Manager failed ('%s').",
errstr.Error)
return ApiError{txt}
} else {
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
}
return nil
}
func (e ApiError) Error() string {
return fmt.Sprintf("%s", e.details)
}
func POST(jsondata []byte, endpoint string) (r *http.Response,
e error) {
buf := bytes.NewBuffer(jsondata)
client := &http.Client{Transport: tr}
resp := &http.Response{}
req, err := http.NewRequest("POST",
config.ManUrlPrefix+"/api/"+endpoint, buf)
if err != nil {
txt := fmt.Sprintf("Could not send REST request ('%s').", err.Error())
return resp, ApiError{txt}
}
resp, err = client.Do(req)
return resp, err
}
func PUT(jsondata []byte, endpoint string) (r *http.Response,
e error) {
buf := bytes.NewBuffer(jsondata)
client := &http.Client{Transport: tr}
resp := &http.Response{}
req, err := http.NewRequest("PUT",
config.ManUrlPrefix+"/api/"+endpoint, buf)
if err != nil {
txt := fmt.Sprintf("Could not send REST request ('%s').", err.Error())
return resp, ApiError{txt}
}
req.Header.Add("Content-Type", `application/json`)
resp, err = client.Do(req)
return resp, nil
}
func (api *Api) Login() error {
data := Login{}
data.Login = config.User
data.Password = config.Password
jsondata, err := json.Marshal(data)
if err != nil {
return ApiError{"Internal error: Manager login, JSON Encode"}
}
resp, err := POST(jsondata, "login")
if err != nil {
logit("Logging in. POST FAILED." + err.Error() +
" (Maybe transport_timeout is too low or not set?)")
return ApiError{err.Error()}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
// There was an error
// Read the response body for details
var body []byte
if b, err := ioutil.ReadAll(resp.Body); err != nil {
txt := fmt.Sprintf("Error reading Body ('%s').", err.Error())
return ApiError{txt}
} else {
body = b
}
type myErr struct {
Error string
}
errstr := myErr{}
if err := json.Unmarshal(body, &errstr); err != nil {
txt := fmt.Sprintf("Error decoding JSON ('%s')", err.Error())
return ApiError{txt}
}
txt := fmt.Sprintf("Login from worker to Manager failed ('%s').",
errstr.Error)
return ApiError{txt}
} else {
// Logged in OK, save the GUID
var body []byte
if b, err := ioutil.ReadAll(resp.Body); err != nil {
txt := fmt.Sprintf("Error reading Body ('%s').", err.Error())
return ApiError{txt}
} else {
body = b
}
type login struct{ GUID string }
loginDetails := login{}
if err := json.Unmarshal(body, &loginDetails); err != nil {
txt := fmt.Sprintf(
"Error decoding login response from Manager ('%s')",
err.Error())
return ApiError{txt}
}
api.UpdateGuid(loginDetails.GUID)
}
return nil
}
func (api *Api) Logout() error {
jsondata := []byte{} // No json for logout
r, err := POST(jsondata,
config.User+"/"+api.Guid()+"/logout")
if err != nil {
return ApiError{err.Error()}
}
io.Copy(ioutil.Discard, r.Body)
r.Body.Close()
api.UpdateGuid("")
return nil
}
func (api *Api) AppendJob(job JobIn) {
api.mutex.Lock()
api.jobs = append(api.jobs, job)
api.mutex.Unlock()
}
func (api *Api) FindJob(jobid int64) (jobret JobIn, e error) {
api.mutex.Lock()
found := 0
for i, job := range api.jobs {
if job.JobID == jobid {
jobret = api.jobs[i]
found = 1
break
}
}
api.mutex.Unlock()
if found == 0 {
return jobret, ApiError{}
}
return jobret, nil
}
func (api *Api) SetUserCancel(jobid int64) {
api.mutex.Lock()
for i, job := range api.jobs {
if job.JobID == jobid {
api.jobs[i].UserCancel = true
break
}
}
api.mutex.Unlock()
}
func (api *Api) UserCancel(jobid int64) bool {
api.mutex.Lock()
for i, job := range api.jobs {
if job.JobID == jobid {
if api.jobs[i].UserCancel == true {
api.mutex.Unlock()
return true
}
break
}
}
api.mutex.Unlock()
return false
}
func (api *Api) SetPid(jobid int64, pid int64) {
api.mutex.Lock()
for i, job := range api.jobs {
if job.JobID == jobid {
api.jobs[i].Pid = pid
break
}
}
api.mutex.Unlock()
}
func (api *Api) RemoveJob(jobid int64) {
api.mutex.Lock()
i := -1
for j, job := range api.jobs {
if job.JobID == jobid {
i = j
break
}
}
if i != -1 {
api.jobs = append(api.jobs[:i], api.jobs[i+1:]...)
}
api.mutex.Unlock()
}
func (api *Api) Guid() string {
api.mutex.Lock()
defer api.mutex.Unlock()
return api.guid
}
func (api *Api) UpdateGuid(guid string) {
api.mutex.Lock()
api.guid = guid
api.mutex.Unlock()
}
func (api *Api) Jobs() []JobIn {
api.mutex.Lock()
defer api.mutex.Unlock()
return api.jobs
}
func NewApi() Api {
api := Api{}
api.jobs = make([]JobIn, 0)
api.mutex = &sync.Mutex{}
api.loginmutex = &sync.Mutex{}
return api
}