-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
378 lines (315 loc) · 6.15 KB
/
main.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
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"os"
"strconv"
)
const (
msgInsertedFmt = "INSERTED %d\r\n"
msgBadFmt = "BAD_FORMAT\r\n"
msgUnknownCommand = "UNKNOWN_COMMAND\r\n"
msgExpectedCRLF = "EXPECTED_CRLF\r\n"
)
type opType int
const (
opPut opType = iota
opStats
opUse
opQuit
opUnknown
)
var (
cmdUse = "use "
cmdUseLen = len(cmdUse)
cmdPut = "put "
cmdStats = "stats"
cmdQuit = "quit"
opNames = map[opType]string{
opPut: cmdPut,
opStats: cmdStats,
opUse: cmdUse,
opQuit: cmdQuit,
opUnknown: "<unknown>",
}
opCount = map[opType]uint64{}
curConnCount = 0
readyCount = 0
globalStat = stats{}
)
type stats struct {
urgentCount uint
waitingCount uint
buriedCount uint
reservedCount uint
pauseCount uint
totalJobsCount uint64
}
func main() {
hostPort := ":3333"
l, err := net.Listen("tcp", hostPort)
if err != nil {
fmt.Printf("Failed to listen: %v\n", err)
os.Exit(-1)
}
defer l.Close()
fmt.Printf("Listening on %v\n", hostPort)
for {
conn, err := l.Accept()
if err != nil {
fmt.Printf("Failed to accept: %v\n", err)
continue
}
c := makeConn(conn, connStateWantCommand)
go handleConn(c)
}
}
type connState int
const (
connStateWantCommand connState = iota
connStateSendWord
connStateSendJob
connStateClose
)
const (
lineBufSize = 224
)
type conn struct {
conn net.Conn
state connState
reader *bufio.Reader
cmd []byte
cmdLen int
cmdRead int
reply string
inJobRead int
inJob *job
}
func makeConn(c net.Conn, initialState connState) *conn {
curConnCount++
return &conn{
conn: c,
reader: bufio.NewReader(c),
state: initialState,
}
}
type job struct {
pri uint64
delay uint64
ttr uint64
bodySize uint64
body []byte
}
func makeJob(pri, delay, ttr, bodySize uint64) *job {
return &job{
pri: pri,
delay: delay,
ttr: ttr,
bodySize: bodySize,
body: make([]byte, bodySize),
}
}
func handleConn(c *conn) {
for {
connData(c)
if c.state == connStateClose {
connClose(c)
return
}
}
}
func connData(c *conn) {
switch c.state {
case connStateWantCommand:
r, err := c.reader.ReadBytes('\n')
if err != nil {
c.state = connStateClose
return
}
c.cmd = r
// TODO handle large job
doCmd(c)
return
break
case connStateSendWord:
_, err := c.conn.Write([]byte(c.reply))
if err != nil {
// TODO log error
c.state = connStateClose
return
}
resetConn(c)
break
case connStateSendJob:
_, err := c.conn.Write([]byte(c.reply))
if err != nil {
// TODO log error
c.state = connStateClose
return
}
resetConn(c)
break
}
}
func resetConn(c *conn) {
c.state = connStateWantCommand
}
func wantCommand(c *conn) bool {
return c.state == connStateWantCommand
}
func cmdDataReady(c *conn) bool {
return wantCommand(c) && c.cmdRead > 0
}
func doCmd(c *conn) {
msgType := whichCmd(c.cmd)
fmt.Printf("command %s\n", opNames[msgType])
switch msgType {
case opPut:
fields := bytes.Fields(c.cmd)
if len(fields) != 5 {
replyMsg(c, msgBadFmt)
return
}
pri, err := strconv.ParseUint(string(fields[1]), 10, 32)
if err != nil {
replyMsg(c, msgBadFmt)
return
}
delay, err := strconv.ParseUint(string(fields[2]), 10, 32)
if err != nil {
replyMsg(c, msgBadFmt)
return
}
ttr, err := strconv.ParseUint(string(fields[3]), 10, 32)
if err != nil {
replyMsg(c, msgBadFmt)
return
}
bodySize, err := strconv.ParseUint(string(fields[4]), 10, 32)
if err != nil {
replyMsg(c, msgBadFmt)
return
}
opCount[msgType]++
// TODO check max job size
if ttr < 1000000000 {
ttr = 1000000000
}
c.inJob = makeJob(pri, delay, ttr, bodySize+2)
nbRead, err := c.reader.Read(c.inJob.body)
if nbRead != len(c.inJob.body) {
replyMsg(c, msgBadFmt)
return
}
fmt.Printf("body %s\n", string(c.inJob.body))
enqueueIncomingJob(c)
return
break
case opStats:
// TODO verify no trailing garbage
opCount[msgType]++
doStats(c, fmtStats)
break
case opUse:
name := c.cmd[cmdUseLen:]
// TODO verify name
opCount[msgType]++
replyLine(c, connStateSendWord, "USING %s\r\n", name)
break
case opQuit:
c.state = connStateClose
break
default:
replyMsg(c, msgUnknownCommand)
return
}
}
func whichCmd(cmd []byte) opType {
if bytes.HasPrefix(cmd, []byte(cmdPut)) {
return opPut
}
if bytes.HasPrefix(cmd, []byte(cmdStats)) {
return opStats
}
if bytes.HasPrefix(cmd, []byte(cmdUse)) {
return opUse
}
if bytes.HasPrefix(cmd, []byte(cmdQuit)) {
return opQuit
}
return opUnknown
}
func enqueueIncomingJob(c *conn) {
j := c.inJob
c.inJob = nil
if !bytes.HasSuffix(j.body, []byte("\r\n")) {
replyMsg(c, msgExpectedCRLF)
return
}
// TODO log new job
// XXX do something with job
_ = j
globalStat.totalJobsCount++
// TODO increase tube stats
id := 1
replyLine(c, connStateSendWord, msgInsertedFmt, id)
}
func replyLine(c *conn, state connState, f string, data ...interface{}) {
r := fmt.Sprintf(f, data...)
reply(c, r, state)
}
func replyMsg(c *conn, msg string) {
reply(c, msg, connStateSendWord)
}
func reply(c *conn, msg string, state connState) {
if c == nil {
return
}
c.reply = msg
c.state = state
fmt.Printf("reply %s\n", msg)
}
func countCurConns() int {
return curConnCount
}
func getDelayedJobCount() uint {
// FIXME
return 0
}
type fmtFunc func(data ...interface{}) string
var statsFmt = "---\n" +
"current-jobs-urgent: %d\n" +
"current-jobs-ready: %d\n" +
"current-jobs-reserved: %d\n" +
"current-jobs-delayed: %d\n" +
"current-jobs-buried: %d\n" +
"cmd-put: %d\n" +
"cmd-use: %d\n" +
"cmd-stats: %d\n" +
"current-connections: %d\n"
func fmtStats(data ...interface{}) string {
return fmt.Sprintf(statsFmt,
globalStat.urgentCount,
readyCount,
globalStat.reservedCount,
getDelayedJobCount(),
globalStat.buriedCount,
opCount[opPut],
opCount[opUse],
opCount[opStats],
countCurConns(),
)
}
func doStats(c *conn, fmtFn fmtFunc, data ...interface{}) {
res := fmtFn(data)
replyLine(c, connStateSendJob, "OK %s\r\n", res)
}
func connClose(c *conn) {
if err := c.conn.Close(); err != nil {
// TODO log error
}
curConnCount = curConnCount - 1
// TODO clean
}