forked from ajvb/kala
/
api.go
301 lines (257 loc) · 8.08 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
package api
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"github.com/ajvb/kala/api/middleware"
"github.com/ajvb/kala/job"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
)
const (
// Base API v1 Path
ApiUrlPrefix = "/api/v1/"
JobPath = "job/"
ApiJobPath = ApiUrlPrefix + JobPath
contentType = "Content-Type"
jsonContentType = "application/json;charset=UTF-8"
)
type KalaStatsResponse struct {
Stats *job.KalaStats
}
// HandleKalaStatsRequest is the hanlder for getting system-level metrics
// /api/v1/stats
func HandleKalaStatsRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
resp := &KalaStatsResponse{
Stats: job.NewKalaStats(cache),
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occured when marshalling response: %s", err)
return
}
}
}
type ListJobStatsResponse struct {
JobStats []*job.JobStat `json:"job_stats"`
}
// HandleListJobStatsRequest is the handler for getting job-specific stats
// /api/v1/job/stats/{id}
func HandleListJobStatsRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
j, err := cache.Get(id)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
resp := &ListJobStatsResponse{
JobStats: j.Stats,
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occured when marshalling response: %s", err)
return
}
}
}
type ListJobsResponse struct {
Jobs map[string]*job.Job `json:"jobs"`
}
// HandleListJobs responds with an array of all Jobs within the server,
// active or disabled.
func HandleListJobsRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
allJobs := cache.GetAll()
allJobs.Lock.RLock()
defer allJobs.Lock.RUnlock()
resp := &ListJobsResponse{
Jobs: allJobs.Jobs,
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occured when marshalling response: %s", err)
return
}
}
}
type AddJobResponse struct {
Id string `json:"id"`
}
func unmarshalNewJob(r *http.Request) (*job.Job, error) {
newJob := &job.Job{}
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
log.Errorf("Error occured when reading r.Body: %s", err)
return nil, err
}
defer r.Body.Close()
if err := json.Unmarshal(body, newJob); err != nil {
log.Errorf("Error occured when unmarshalling data: %s", err)
return nil, err
}
return newJob, nil
}
// HandleAddJob takes a job object and unmarshals it to a Job type,
// and then throws the job in the schedulers.
func HandleAddJob(cache job.JobCache, defaultOwner string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
newJob, err := unmarshalNewJob(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if defaultOwner != "" && newJob.Owner == "" {
newJob.Owner = defaultOwner
}
err = newJob.Init(cache)
if err != nil {
errStr := "Error occured when initializing the job"
log.Errorf(errStr+": %s", err)
http.Error(w, errStr, http.StatusBadRequest)
return
}
resp := &AddJobResponse{
Id: newJob.Id,
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occured when marshalling response: %s", err)
return
}
}
}
// HandleJobRequest routes requests to /api/v1/job/{id} to either
// handleDeleteJob if its a DELETE or handleGetJob if its a GET request.
func HandleJobRequest(cache job.JobCache, db job.JobDB) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
j, err := cache.Get(id)
if err != nil {
log.Errorf("Error occured when trying to get the job you requested.")
w.WriteHeader(http.StatusNotFound)
return
}
if j == nil {
w.WriteHeader(http.StatusNotFound)
return
}
if r.Method == "DELETE" {
err = j.Delete(cache, db)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusNoContent)
}
} else if r.Method == "GET" {
handleGetJob(w, r, j)
}
}
}
type JobResponse struct {
Job *job.Job `json:"job"`
}
func handleGetJob(w http.ResponseWriter, r *http.Request, j *job.Job) {
resp := &JobResponse{
Job: j,
}
w.Header().Set(contentType, jsonContentType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.Errorf("Error occured when marshalling response: %s", err)
return
}
}
// HandleStartJobRequest is the handler for manually starting jobs
// /api/v1/job/start/{id}
func HandleStartJobRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
j, err := cache.Get(id)
if err != nil {
log.Errorf("Error occured when trying to get the job you requested.")
w.WriteHeader(http.StatusNotFound)
return
}
if j == nil {
w.WriteHeader(http.StatusNotFound)
return
}
j.StopTimer()
j.Run(cache)
w.WriteHeader(http.StatusNoContent)
}
}
// HandleDisableJobRequest is the handler for mdisabling jobs
// /api/v1/job/disable/{id}
func HandleDisableJobRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
j, err := cache.Get(id)
if err != nil {
log.Errorf("Error occured when trying to get the job you requested.")
w.WriteHeader(http.StatusNotFound)
return
}
if j == nil {
w.WriteHeader(http.StatusNotFound)
return
}
j.Disable()
w.WriteHeader(http.StatusNoContent)
}
}
// HandleEnableJobRequest is the handler for enable jobs
// /api/v1/job/enable/{id}
func HandleEnableJobRequest(cache job.JobCache) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
j, err := cache.Get(id)
if err != nil {
log.Errorf("Error occured when trying to get the job you requested.")
w.WriteHeader(http.StatusNotFound)
return
}
if j == nil {
w.WriteHeader(http.StatusNotFound)
return
}
j.Enable(cache)
w.WriteHeader(http.StatusNoContent)
}
}
// SetupApiRoutes is used within main to initialize all of the routes
func SetupApiRoutes(r *mux.Router, cache job.JobCache, db job.JobDB, defaultOwner string) {
// Route for creating a job
r.HandleFunc(ApiJobPath, HandleAddJob(cache, defaultOwner)).Methods("POST")
// Route for deleting and getting a job
r.HandleFunc(ApiJobPath+"{id}/", HandleJobRequest(cache, db)).Methods("DELETE", "GET")
// Route for getting job stats
r.HandleFunc(ApiJobPath+"stats/{id}/", HandleListJobStatsRequest(cache)).Methods("GET")
// Route for listing all jops
r.HandleFunc(ApiJobPath, HandleListJobsRequest(cache)).Methods("GET")
// Route for manually start a job
r.HandleFunc(ApiJobPath+"start/{id}/", HandleStartJobRequest(cache)).Methods("POST")
// Route for manually start a job
r.HandleFunc(ApiJobPath+"enable/{id}/", HandleEnableJobRequest(cache)).Methods("POST")
// Route for manually disable a job
r.HandleFunc(ApiJobPath+"disable/{id}/", HandleDisableJobRequest(cache)).Methods("POST")
// Route for getting app-level metrics
r.HandleFunc(ApiUrlPrefix+"stats/", HandleKalaStatsRequest(cache)).Methods("GET")
}
func StartServer(listenAddr string, cache job.JobCache, db job.JobDB, defaultOwner string) error {
r := mux.NewRouter()
// Allows for the use for /job as well as /job/
r.StrictSlash(true)
SetupApiRoutes(r, cache, db, defaultOwner)
n := negroni.New(negroni.NewRecovery(), &middleware.Logger{log.Logger{}})
n.UseHandler(r)
return http.ListenAndServe(listenAddr, n)
}