/
api.go
431 lines (347 loc) · 13.1 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
429
430
431
package api
import (
"net/http"
"encoding/json"
"strconv"
"time"
"errors"
"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/brysearl/omicrond/job"
"github.com/brysearl/omicrond/conf"
"github.com/goji/httpauth"
)
//"github.com/davecgh/go-spew/spew"
type ChanComm struct {
Signal string
RunningSchedule job.JobSchedule
RunningJobs job.RunningJobTracker
Error error
}
var runningChanComm chan ChanComm
// StartServer - Create a TCP server running on the address and port configured in conf.go or cli arg.
// Should be run in a goroutine
func StartServer(commChannel chan ChanComm) {
runningChanComm = commChannel
router := buildRoutes(mux.NewRouter())
logrus.Info("Starting HTTP interface")
srv := &http.Server{
Handler: httpauth.SimpleBasicAuth(conf.Attr.APIUser, conf.Attr.APIPassword)(router),
Addr: conf.Attr.APIAddress + ":" + strconv.Itoa(conf.Attr.APIPort),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: time.Duration(conf.Attr.APITimeout) * time.Second,
ReadTimeout: time.Duration(conf.Attr.APITimeout) * time.Second,
}
if conf.Attr.APISSL == true {
logrus.Fatal(srv.ListenAndServeTLS(conf.Attr.APIPubKeyPath, conf.Attr.APIPrivKeyPath))
} else {
logrus.Fatal(srv.ListenAndServe())
}
}
// buildRoutes - Configure API routes and their functions
func buildRoutes(router *mux.Router) *mux.Router {
router.HandleFunc("/.status", getStatus).Methods("GET")
router.HandleFunc("/schedule/get/list", scheduleGetList).Methods("GET")
router.HandleFunc("/schedule/get/job/{jobLabel:[a-zA-Z0-9_]+}", scheduleGetJob).Methods("GET")
router.HandleFunc("/schedule/edit/job/{jobLabel:[a-zA-Z0-9_]+}", scheduleEditJob).Methods("POST")
router.HandleFunc("/schedule/create/job", scheduleCreateJob).Methods("POST")
router.HandleFunc("/schedule/delete/job/{jobLabel:[a-zA-Z0-9_]+}", scheduleDeleteJob).Methods("POST")
router.HandleFunc("/runningjob/get/list", runningjobGetList).Methods("GET")
router.HandleFunc("/runningjob/get/token/{jobToken:[a-zA-Z0-9]+}", runningjobGetToken).Methods("GET")
router.HandleFunc("/runningjob/stop/token/{jobToken:[a-zA-Z0-9]+}", runningjobStopToken).Methods("GET")
router.HandleFunc("/runningjob/tail/token/{jobToken:[a-zA-Z0-9]+}", runningjobTailToken).Methods("GET")
return router
}
// getStatus - Send the status of the server. Used as unit test, if you get a 404 your test failed.
func getStatus(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request for Omicrond status")
w.Write([]byte("Omicrond is running"))
return
}
// scheduleGetList - Send a JSON representation of the JobSchedule object within job.go
func scheduleGetList(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request for Omicrond job list")
encoder := json.NewEncoder(w)
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "scheduleGetList" }
returnComm := <-runningChanComm
currentSchedule := returnComm.RunningSchedule
apiRunningSchedule, err := currentSchedule.MakeAPIFormat()
if err != nil {
w.Write([]byte("Error: " + err.Error()))
}
// Return the running schedule in JSON format
err = encoder.Encode(apiRunningSchedule)
if err != nil {
w.Write([]byte("Error: " + err.Error()))
}
return
}
func scheduleGetJob(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request for single Omicrond job configuration")
// Assign the JSON encoder
encoder := json.NewEncoder(w)
// Convert the route variables
vars := mux.Vars(r)
jobLabelStr := vars["jobLabel"]
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "scheduleGetList", RunningSchedule: job.JobSchedule{} }
returnComm := <-runningChanComm
currentSchedule := returnComm.RunningSchedule
// Retrieve the Job
requestedJob, _, err := currentSchedule.GetJobByLabel(jobLabelStr)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Convert the job to API
apiRequestedJob, err := requestedJob.MakeAPIFormat()
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Return in JSON format
err = encoder.Encode(apiRequestedJob)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
return
}
func scheduleEditJob(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request to modify Omicrond job configuration")
// Convert the route variables
vars := mux.Vars(r)
jobLabelStr := vars["jobLabel"]
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "scheduleGetList", RunningSchedule: job.JobSchedule{} }
returnComm := <-runningChanComm
currentSchedule := returnComm.RunningSchedule
// Retrieve the Job
requestedJob, jobIndex, err := currentSchedule.GetJobByLabel(jobLabelStr)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
err = parseFormFieldsIntoJobConfig(&requestedJob, r)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the job back into the schedule
newSchedule := currentSchedule
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
newSchedule.Job[jobIndex] = requestedJob
// Make sure the changes are okay
err = newSchedule.CheckConfig()
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the new schedule into rotation
runningChanComm <- ChanComm{Signal: "replaceRunningSchedule", RunningSchedule: newSchedule}
return
}
func scheduleCreateJob(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request to create Omicrond job configuration")
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "scheduleGetList", RunningSchedule: job.JobSchedule{} }
returnComm := <-runningChanComm
currentSchedule := returnComm.RunningSchedule
// Create the empty Job
newJob := job.JobConfig{}
err := parseFormFieldsIntoJobConfig(&newJob, r)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the new job into the schedule
newSchedule := currentSchedule
newSchedule.Job = append(newSchedule.Job, newJob)
// Make sure the changes are okay
err = newSchedule.CheckConfig()
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the new schedule into rotation
runningChanComm <- ChanComm{Signal: "replaceRunningSchedule", RunningSchedule: newSchedule}
return
}
func scheduleDeleteJob(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request to delete Omicrond job configuration")
// Convert the route variables
vars := mux.Vars(r)
jobLabelStr := vars["jobLabel"]
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "scheduleGetList", RunningSchedule: job.JobSchedule{} }
returnComm := <-runningChanComm
currentSchedule := returnComm.RunningSchedule
// Retrieve the Job
_, jobIndex, err := currentSchedule.GetJobByLabel(jobLabelStr)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the job back into the schedule
newSchedule := currentSchedule
newSchedule.Job = append(newSchedule.Job[:jobIndex], newSchedule.Job[jobIndex + 1:]...)
// Make sure the changes are okay
err = newSchedule.CheckConfig()
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Put the new schedule into rotation
runningChanComm <- ChanComm{Signal: "replaceRunningSchedule", RunningSchedule: newSchedule}
return
}
// runningjobGetList - Send a JSON representation of the currently running jobs
func runningjobGetList(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request for Omicrond running jobs")
encoder := json.NewEncoder(w)
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "runningjobGetList"}
returnComm := <-runningChanComm
currentRunningJobs := returnComm.RunningJobs
apiRunningJobs, err := currentRunningJobs.MakeAPIFormat()
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Return the running schedule in JSON format
err = encoder.Encode(apiRunningJobs)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
return
}
func runningjobGetToken(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request for single running job")
// Assign the JSON encoder
encoder := json.NewEncoder(w)
// Convert the route variables
vars := mux.Vars(r)
jobToken := vars["jobToken"]
// Request the current running schedule from the main scheduling loop
runningJob, err := getRunningJobByToken(jobToken)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
apiRunningJob, err := runningJob.MakeAPIFormat(jobToken)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
// Return the running schedule in JSON format
err = encoder.Encode(apiRunningJob)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
return
}
func runningjobStopToken(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request to stop job")
// Convert the route variables
vars := mux.Vars(r)
jobToken := vars["jobToken"]
// Request the current running schedule from the main scheduling loop
runningJob, err := getRunningJobByToken(jobToken)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
runningJob.Channel <- job.ChanComm{Signal:"stop process"}
timeout, err := time.ParseDuration("15s")
select {
case <-time.After(timeout):
w.Write([]byte("Job could not be stopped. Times out in 15s"))
// Spawn thread on channel traffic and go back to listening
case comm := <-runningJob.Channel:
if comm.Error != nil {
http.Error(w, "{ \"Error\":\"" + comm.Error.Error() + "\"}", http.StatusBadRequest)
}
w.Write([]byte("Job successfully stopped"))
}
return
}
func runningjobTailToken(w http.ResponseWriter, r *http.Request) {
logrus.Debug("API request to tail job")
return
// Convert the route variables
vars := mux.Vars(r)
jobToken := vars["jobToken"]
// Request the current running schedule from the main scheduling loop
runningJob, err := getRunningJobByToken(jobToken)
if err != nil {
http.Error(w, "{ \"Error\":\"" + err.Error() + "\"}", http.StatusBadRequest)
return
}
runningJob.Channel <- job.ChanComm{Signal:"tail process", Writer: w}
<- runningJob.Channel
return
}
/////////////////////////////// Helper Functions /////////////////////////////////////
func getRunningJobByToken(jobToken string) (job.RunningJob, error) {
var err error
// Request the current running schedule from the main scheduling loop
runningChanComm <- ChanComm{Signal: "runningjobGetList"}
returnComm := <-runningChanComm
currentRunningJobs := returnComm.RunningJobs
runningJob, ok := currentRunningJobs.Jobs[jobToken]
if !ok {
err = errors.New("Job with token " + jobToken + " is no longer running")
return job.RunningJob{}, err
}
return runningJob, err
}
func parseFormFieldsIntoJobConfig(newJob *job.JobConfig, r *http.Request) (error) {
var err error
// Change the fields to the new settings
newLabel := r.PostFormValue("label")
if newLabel != "" {
newJob.Label = newLabel
} else {
return errors.New("{ \"Error\":\"" + "Requires parameter[label]" + "\"}")
}
newScheduleStr := r.PostFormValue("schedule")
if newScheduleStr != "" {
newJob.Schedule = newScheduleStr
err := newJob.ParseScheduleIntoFilters(false)
if err != nil {
return errors.New("{ \"Error\":\"" + err.Error() + "\"}")
return errors.New("Error parsing form fields")
}
} else {
return errors.New("{ \"Error\":\"" + "Requires parameter[schedule]" + "\"}")
}
newCommand := r.PostFormValue("command")
if newCommand != "" {
newJob.Command = newCommand
} else {
return errors.New("{ \"Error\":\"" + "Requires parameter[command]" + "\"}")
}
newGroupName := r.PostFormValue("groupName")
if newGroupName != "" {
newJob.GroupName = newGroupName
} else {
return errors.New("{ \"Error\":\"" + "Requires parameter[groupName]" + "\"}")
}
newLocking := r.PostFormValue("locking")
if newLocking != "" {
if newLocking == "true" {
newJob.Locking = true
} else if newLocking == "false" {
newJob.Locking = true
} else {
return errors.New("{ \"Error\":\"form field 'locking' must equal either 'true' or 'false'\"}")
}
}
return err
}