forked from gophergala/go-tasky
/
tasky.go
359 lines (285 loc) · 7.03 KB
/
tasky.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
package tasky
import (
"crypto/rand"
"encoding/json"
"fmt"
// "github.com/davecgh/go-spew/spew"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
"sync"
"github.com/gorilla/mux"
)
const (
Enabled = "Enabled"
Disabled = "Disabled"
)
type Action uint64
const (
Cancel Action = iota
Pause
Resume
Restart
)
//WorkerDetails is an object that describes the worker
type WorkerDetails struct {
// Name of the worker
Name string `json:"name"`
// human readable description of the worker
Description string `json:"description"`
//an config struct for all config values
Config interface{} `json:"config_objects,omitempty"`
}
type Worker interface {
// Details provides all metadata info about the worker and it's config
Details() *WorkerDetails
// Worker name
Name() string
// Description of the worker and it's usage
Usage() string
// Execute the task
Perform([]byte, chan []byte, chan error, chan bool)
// Worker status
Status() string
// Action to be taken on ongoing task
Signal(Action) bool
// Maximum number of simultaneous tasks allowed
MaxNumTasks() uint64
}
type TaskyError struct {
Error string
}
var (
wMut sync.RWMutex
workers map[string]Worker
tMut sync.RWMutex
tasks map[string]*taskyTask
apiBase string
)
func init() {
workers = make(map[string]Worker)
tasks = make(map[string]*taskyTask)
apiBase = "/tasky/v1"
}
func NewWorker(w Worker) (Worker, error) {
tw := &taskyWorker{}
tw.w = w
name := strings.ToLower(w.Name())
wMut.Lock()
workers[name] = tw
wMut.Unlock()
return tw, nil
}
func uuid() string {
b := make([]byte, 16)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
log.Fatal(err)
}
b[6] = (b[6] & 0x0F) | 0x40
b[8] = (b[8] &^ 0x40) | 0x80
return fmt.Sprintf("%x%x%x%x%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
type taskid struct {
TaskId string
}
type tstat struct {
TaskId string
Status string
Duration string `json:"Duration,omitempty"`
}
func handlerGetTaskOutput(rw http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
tMut.RLock()
t, ok := tasks[id]
tMut.RUnlock()
if !ok {
e := TaskyError{"Could not found a task with given id"}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusNotFound)
return
}
if len(t.result()) > 0 {
results := make(map[string]interface{})
err := json.Unmarshal(t.result(), &results)
if err != nil {
log.Println("Tasky.go_handlerGetTaskOutput - Error Unmarshaling Task Result: ", err.Error())
results["string_output"] = string(t.result()) //last ditch effort to save the data
}
js := make(map[string]interface{})
js["TaskId"] = id
js["Output"] = results
jsonStr, err := json.Marshal(js)
if err != nil {
e := TaskyError{err.Error()}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprintf(rw, "%s\n", string(jsonStr))
}
}
func handlerCancelTask(rw http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
tMut.RLock()
t, ok := tasks[id]
tMut.RUnlock()
if !ok {
e := TaskyError{"Could not found a task with given id"}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusNotFound)
return
}
t.cancel()
}
func handlerGetTaskStatus(rw http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
tMut.RLock()
t, ok := tasks[id]
tMut.RUnlock()
if !ok {
e := TaskyError{"Could not found a task with given id"}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusNotFound)
return
}
s := t.status()
var durStr string
if s != Running {
d := t.duration()
if d > 0 {
durStr = fmt.Sprintf("%v", d)
}
}
ts := tstat{id, s, durStr}
jsonStr, err := json.Marshal(ts)
if err != nil {
e := TaskyError{err.Error()}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprintf(rw, "%s\n", string(jsonStr))
}
func newTask(w Worker, job []byte) taskid {
id := uuid()
t := &taskyTask{}
t.new(w)
tMut.Lock()
tasks[id] = t
tMut.Unlock()
go t.run(job)
return taskid{id}
}
type ts struct {
Tasks []tstat
}
func listTasks() ts {
t := ts{}
tMut.RLock()
for k, v := range tasks {
s := v.status()
durStr := ""
if s != Running {
d := v.duration()
if d > 0 {
durStr = fmt.Sprintf("%v", d)
}
}
if len(t.Tasks) <= 0 {
t.Tasks = make([]tstat, 1)
t.Tasks[0] = tstat{k, s, durStr}
} else {
t.Tasks = append(t.Tasks, tstat{k, s, durStr})
}
}
tMut.RUnlock()
return t
}
func handlerListTasks(rw http.ResponseWriter, r *http.Request) {
t := listTasks()
jsonStr, err := json.Marshal(t)
if err != nil {
e := TaskyError{err.Error()}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprintf(rw, "%s\n", jsonStr)
}
func handlerNewTask(rw http.ResponseWriter, r *http.Request) {
job, err := ioutil.ReadAll(r.Body)
if err != nil {
e := TaskyError{err.Error()}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusInternalServerError)
return
}
name := mux.Vars(r)["name"]
wMut.RLock()
w, ok := workers[name]
wMut.RUnlock()
if !ok {
e := TaskyError{"Could not found worker with given name"}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusNotFound)
return
}
t := newTask(w, job)
jsonStr, err := json.Marshal(t)
if err != nil {
e := TaskyError{err.Error()}
estr, _ := json.Marshal(e)
fmt.Fprintf(rw, "%s\n", estr)
rw.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Fprintf(rw, "%s\n", string(jsonStr))
}
func handlerListWorkers(rw http.ResponseWriter, r *http.Request) {
// jsonStr, _ := listWorkers()
listWorkers, err := listWorkerDetails()
if err != nil {
rw.WriteHeader(http.StatusNoContent)
return
}
rw.Header().Set("Content-Type", "application/json")
RespondJSON(rw, r, listWorkers)
return
// fmt.Fprintf(rw, "%s\n", jsonStr)
}
func RegisterTaskyHandlers(r *mux.Router) {
r.StrictSlash(true) //enables matching a route with or without a trailing slash
//Handles /tasky/v1 routes. Create new subrouters off this
tr := r.PathPrefix(apiBase).Subrouter()
workersRtr := tr.PathPrefix("/workers").Subrouter()
workersRtr.HandleFunc("/", handlerListWorkers).Methods("GET")
workersRtr.HandleFunc("/{name}", handlerNewTask).Methods("POST")
tasksRtr := tr.PathPrefix("/tasks").Subrouter()
tasksRtr.HandleFunc("/", handlerListTasks).Methods("GET")
// tasksRtr.HandleFunc("/{id:[0-9a-f]+}", handlerGetTaskInfo).Methods("GET")
tasksRtr.HandleFunc("/{id:[0-9a-f]+}/status", handlerGetTaskStatus).Methods("GET")
tasksRtr.HandleFunc("/{id:[0-9a-f]+}/cancel", handlerCancelTask).Methods("POST")
tasksRtr.HandleFunc("/{id:[0-9a-f]+}/result", handlerGetTaskOutput).Methods("GET")
}
func RespondJSON(w http.ResponseWriter, req *http.Request, v interface{}, code ...int) error {
if code != nil {
w.WriteHeader(code[0])
}
err := json.NewEncoder(w).Encode(v)
if err != nil {
//encoding failed
panic(err)
}
return err
}