forked from contribsys/faktory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
256 lines (225 loc) · 5.03 KB
/
commands.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
package server
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/contribsys/faktory"
"github.com/contribsys/faktory/storage"
"github.com/contribsys/faktory/util"
)
type command func(c *Connection, s *Server, cmd string)
var cmdSet = map[string]command{
"END": end,
"PUSH": push,
"FETCH": fetch,
"ACK": ack,
"FAIL": fail,
"BEAT": heartbeat,
"INFO": info,
"FLUSH": flush,
}
func flush(c *Connection, s *Server, cmd string) {
if s.Options.Environment == "development" {
util.Info("Flushing dataset")
} else {
util.Warn("Flushing dataset")
}
err := s.store.Flush()
if err != nil {
c.Error(cmd, err)
return
}
c.Ok()
}
func end(c *Connection, s *Server, cmd string) {
c.Close()
}
func push(c *Connection, s *Server, cmd string) {
data := []byte(cmd[5:])
job, err := parseJob(data)
if err != nil {
c.Error(cmd, err)
return
}
if job.Jid == "" || len(job.Jid) < 8 {
c.Error(cmd, fmt.Errorf("All jobs must have a reasonable jid parameter"))
return
}
if job.Type == "" {
c.Error(cmd, fmt.Errorf("All jobs must have a jobtype parameter"))
return
}
if job.Args == nil {
c.Error(cmd, fmt.Errorf("All jobs must have an args parameter"))
return
}
if job.At != "" {
t, err := util.ParseTime(job.At)
if err != nil {
c.Error(cmd, fmt.Errorf("Invalid timestamp for 'at': '%s'", job.At))
return
}
if t.After(time.Now()) {
data, err = json.Marshal(job)
if err != nil {
c.Error(cmd, err)
return
}
// scheduler for later
err = s.store.Scheduled().AddElement(job.At, job.Jid, data)
if err != nil {
c.Error(cmd, err)
return
}
c.Ok()
return
}
}
// enqueue immediately
q, err := s.store.GetQueue(job.Queue)
if err != nil {
c.Error(cmd, err)
return
}
job.EnqueuedAt = util.Nows()
data, err = json.Marshal(job)
if err != nil {
c.Error(cmd, err)
return
}
err = q.Push(data)
if err != nil {
c.Error(cmd, err)
return
}
c.Ok()
}
func fetch(c *Connection, s *Server, cmd string) {
// quiet or terminated clients should not get new jobs
if c.client.state != "" {
c.Result(nil)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
qs := strings.Split(cmd, " ")[1:]
job, err := s.Fetch(func(job *faktory.Job) error {
return reserve(c.client.Wid, job, s.store.Working())
}, ctx, qs...)
if err != nil {
c.Error(cmd, err)
return
}
if job != nil {
res, err := json.Marshal(job)
if err != nil {
c.Error(cmd, err)
return
}
atomic.AddInt64(&s.Stats.Processed, 1)
c.Result(res)
} else {
c.Result(nil)
}
}
func ack(c *Connection, s *Server, cmd string) {
data := cmd[4:]
var hash map[string]string
err := json.Unmarshal([]byte(data), &hash)
if err != nil {
c.Error(cmd, fmt.Errorf("Invalid ACK %s", data))
return
}
jid, ok := hash["jid"]
if !ok {
c.Error(cmd, fmt.Errorf("Invalid ACK %s", data))
return
}
_, err = acknowledge(jid, s.store.Working())
if err != nil {
c.Error(cmd, err)
return
}
c.Ok()
}
func uptimeInSeconds(s *Server) int {
return int(time.Now().Sub(s.Stats.StartedAt).Seconds())
}
func currentMemoryUsage(s *Server) string {
// TODO maybe remove this and/or offer a better stat?
return "123 MB"
}
func CurrentState(s *Server) (map[string]interface{}, error) {
defalt, err := s.store.GetQueue("default")
if err != nil {
return nil, err
}
store := s.Store()
totalQueued := 0
totalQueues := 0
// queue size is cached so this should be very efficient.
store.EachQueue(func(q storage.Queue) {
totalQueued += int(q.Size())
totalQueues += 1
})
return map[string]interface{}{
"server_utc_time": time.Now().UTC().Format("03:04:05 UTC"),
"faktory": map[string]interface{}{
"default_size": defalt.Size(),
"total_failures": s.Stats.Failures,
"total_processed": s.Stats.Processed,
"total_enqueued": totalQueued,
"total_queues": totalQueues,
"tasks": s.taskRunner.Stats()},
"server": map[string]interface{}{
"faktory_version": faktory.Version,
"uptime": uptimeInSeconds(s),
"connections": s.Stats.Connections,
"command_count": s.Stats.Commands,
"used_memory_mb": currentMemoryUsage(s)},
}, nil
}
func info(c *Connection, s *Server, cmd string) {
data, err := CurrentState(s)
if err != nil {
c.Error(cmd, err)
return
}
bytes, err := json.Marshal(data)
if err != nil {
c.Error(cmd, err)
return
}
c.Result(bytes)
}
/*
BEAT {"wid":1238971623}
*/
func heartbeat(c *Connection, s *Server, cmd string) {
if !strings.HasPrefix(cmd, "BEAT {") {
c.Error(cmd, fmt.Errorf("Invalid format %s", cmd))
return
}
var worker ClientWorker
data := cmd[5:]
err := json.Unmarshal([]byte(data), &worker)
if err != nil {
c.Error(cmd, fmt.Errorf("Invalid format %s", data))
return
}
entry, ok := s.heartbeats[worker.Wid]
if !ok {
c.Error(cmd, fmt.Errorf("Unknown client %s", worker.Wid))
return
}
entry.lastHeartbeat = time.Now()
if entry.signal == "" {
c.Ok()
} else {
c.Result([]byte(fmt.Sprintf(`{"signal":"%s"}`, entry.signal)))
entry.signal = ""
}
}