-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhandlersocket.go
532 lines (421 loc) · 12.1 KB
/
handlersocket.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
Copyright 2011 Brian Ketelsen
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handlersocket
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"net"
"strconv"
"strings"
"sync"
)
const (
Version = "0.0.3"
DefaultReadPort = 9998
DefaultWritePort = 9999
MaxPacketSize = 1 << 24
)
/**
* The main HandlerSocket struct
* shamelessly modeled after Philio/GoMySQL
* for consistency of usage
*/
type HandlerSocket struct {
Logging bool
auth *HandlerSocketAuth
conn net.Conn
wrConn net.Conn
// In <-chan HandlerSocketResponse
in chan HandlerSocketResponse
out chan HandlerSocketCommandWriter
wrIn chan HandlerSocketResponse
wrOut chan HandlerSocketCommandWriter
connected bool
wrConnected bool
mutex *sync.Mutex
}
type HandlerSocketAuth struct {
host string
dbname string
readPort int
writePort int
}
/**
* Row definition
*/
type HandlerSocketRow struct {
Data map[string]interface{}
}
type HandlerSocketCommandWriter interface {
write(w io.Writer) (err error)
}
type hsopencommand struct {
command string
params []string
}
type hsfindcommand struct {
command string
params []string
limit int
offset int
}
type hsmodifycommand struct {
command string
criteria []string
limit int
offset int
mop string
newvals []string
}
type hsinsertcommand struct {
command string
params []string
}
type HandlerSocketResponse struct {
ReturnCode string
Data []string
}
type header map[string]string
var indexes map[int][]string
func (handlerSocket *HandlerSocket) OpenIndex(index int, dbName string, tableName string, indexName string, columns ...string) (err error) {
if !handlerSocket.connected {
handlerSocket.connect()
}
cols := strings.Join(columns, ",")
strindex := strconv.Itoa(index)
a := []string{strindex, dbName, tableName, indexName, cols}
handlerSocket.mutex.Lock()
handlerSocket.out <- &hsopencommand{command: "P", params: a}
handlerSocket.wrOut <- &hsopencommand{command: "P", params: a}
message2 := <-handlerSocket.wrIn
message := <-handlerSocket.in
handlerSocket.mutex.Unlock()
indexes[index] = columns
if message.ReturnCode != "0" {
return errors.New("Error Opening Index")
}
if message2.ReturnCode != "0" {
return errors.New("Error Opening Index")
}
return
}
/*
----------------------------------------------------------------------------
Updating/Deleting data
The 'find_modify' request has the following syntax.
<indexid> <op> <vlen> <v1> ... <vn> <limit> <offset> <mop> <m1> ... <mk>
- <mop> is either 'U' (update) or 'D' (delete).
- <m1> ... <mk> specifies the column values to set. The length of <m1> ...
<mk> must be smaller than or equal to the length of <columns> specified by
the corresponding 'open_index' request. If <mop> is 'D', these parameters
are ignored.
ind op pc key lim off mop newpk newval ...
1 = 1 red 1 0 U red brian
----------------------------------------------------------------------------
*/
func (handlerSocket *HandlerSocket) Modify(index int, oper string, limit int, offset int, modifyOper string, keys []string, newvals []string) (modifiedRows int, err error) {
query := strings.Join(keys, "\t")
queryCount := strconv.Itoa(len(keys))
a := []string{oper, queryCount, query}
//a := []string{oper, "1", keys}
if modifyOper == "D" {
handlerSocket.mutex.Lock()
handlerSocket.wrOut <- &hsmodifycommand{command: strconv.Itoa(index), criteria: a, limit: limit, offset: offset, mop: modifyOper}
}
if modifyOper == "U" {
handlerSocket.mutex.Lock()
handlerSocket.wrOut <- &hsmodifycommand{command: strconv.Itoa(index), criteria: a, limit: limit, offset: offset, mop: modifyOper, newvals: newvals}
}
message := <-handlerSocket.wrIn
handlerSocket.mutex.Unlock()
if message.ReturnCode == "1" {
return 0, errors.New("Error Something")
}
return strconv.Atoi(strings.TrimSpace(message.Data[1]))
}
func (handlerSocket *HandlerSocket) Find(index int, oper string, limit int, offset int, vals ...string) (rows []HandlerSocketRow, err error) {
cols := strings.Join(vals, "\t")
strindex := strconv.Itoa(index)
colCount := strconv.Itoa(len(vals))
a := []string{oper, colCount, cols}
handlerSocket.mutex.Lock()
handlerSocket.out <- &hsfindcommand{command: strindex, params: a, limit: limit, offset: offset}
message := <-handlerSocket.in
handlerSocket.mutex.Unlock()
return parseResult(index, message), nil
}
/*
----------------------------------------------------------------------------
Inserting data
The 'insert' request has the following syntax.
<indexid> '+' <vlen> <v1> ... <vn>
- <vlen> indicates the length of the trailing parameters <v1> ... <vn>. This
must be smaller than or equal to the length of <columns> specified by the
corresponding 'open_index' request.
- <v1> ... <vn> specify the column values to set. For columns not in
<columns>, the default values for each column are set.
----------------------------------------------------------------------------
*/
func (handlerSocket *HandlerSocket) Insert(index int, vals ...string) (err error) {
cols := strings.Join(vals, "\t")
strindex := strconv.Itoa(index)
colCount := strconv.Itoa(len(vals))
oper := "+"
a := []string{oper, colCount, cols}
handlerSocket.mutex.Lock()
handlerSocket.wrOut <- &hsinsertcommand{command: strindex, params: a}
message := <-handlerSocket.wrIn
handlerSocket.mutex.Unlock()
if message.ReturnCode == "1" {
return errors.New("INSERT: Data Exists")
}
if message.ReturnCode != "0" {
return errors.New("Error Inserting Data")
}
return nil
}
func parseResult(index int, hs HandlerSocketResponse) (rows []HandlerSocketRow) {
fieldCount, _ := strconv.Atoi(hs.Data[0])
remainingFields := len(hs.Data) - 1
if fieldCount > 0 {
rs := remainingFields / fieldCount
rows = make([]HandlerSocketRow, rs)
offset := 1
for r := 0; r < rs; r++ {
d := make(map[string]interface{}, fieldCount)
for f := 0; f < fieldCount; f++ {
d[indexes[index][f]] = hs.Data[offset+f]
}
rows[r] = HandlerSocketRow{Data: d}
offset += fieldCount
}
}
return
}
/**
* Close the connection to the server
*/
func (handlerSocket *HandlerSocket) Close() (err error) {
if handlerSocket.Logging {
log.Print("Close called")
}
// If not connected return
if !handlerSocket.connected {
err = errors.New("A connection to a MySQL server is required to use this function")
return
}
if handlerSocket.Logging {
log.Print("Sent quit command to server")
}
// Close connection
handlerSocket.conn.Close()
handlerSocket.connected = false
if handlerSocket.Logging {
log.Print("Closed connection to server")
}
return
}
/**
* Reconnect (if connection droppped etc)
*/
func (handlerSocket *HandlerSocket) Reconnect() (err error) {
if handlerSocket.Logging {
log.Print("Reconnect called")
}
// Close connection (force down)
if handlerSocket.connected {
handlerSocket.conn.Close()
handlerSocket.connected = false
}
// Call connect
err = handlerSocket.connect()
return
}
/**
* Connect to a server
*/
func (handlerSocket *HandlerSocket) Connect(params ...interface{}) (err error) {
if handlerSocket.Logging {
log.Print("Connect called")
}
// If already connected return
if handlerSocket.connected {
err = errors.New("Already connected to server")
return
}
// Check min number of params
if len(params) < 2 {
err = errors.New("A hostname and username are required to connect")
return
}
// Parse params
handlerSocket.parseParams(params)
// Connect to server
err = handlerSocket.connect()
return
}
/**
* Create a new instance of the package
*/
func New() (handlerSocket *HandlerSocket) {
// Create and return a new instance of HandlerSocket
handlerSocket = new(HandlerSocket)
// Setup mutex
handlerSocket.mutex = new(sync.Mutex)
return
}
/**
* Create connection to server using unix socket or tcp/ip then setup buffered reader/writer
*/
func (handlerSocket *HandlerSocket) connect() (err error) {
localAddress, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:0")
targetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.readPort)
wrTargetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.writePort)
hsAddress, err := net.ResolveTCPAddr("tcp", targetAddress)
hsWrAddress, err := net.ResolveTCPAddr("tcp", wrTargetAddress)
handlerSocket.conn, err = net.DialTCP("tcp", localAddress, hsAddress)
handlerSocket.wrConn, err = net.DialTCP("tcp", localAddress, hsWrAddress)
if handlerSocket.Logging {
log.Print("Connected using TCP/IP")
}
handlerSocket.in = make(chan HandlerSocketResponse)
handlerSocket.out = make(chan HandlerSocketCommandWriter)
handlerSocket.wrIn = make(chan HandlerSocketResponse)
handlerSocket.wrOut = make(chan HandlerSocketCommandWriter)
go handlerSocket.reader(handlerSocket.conn)
go handlerSocket.writer(handlerSocket.conn)
go handlerSocket.wrreader(handlerSocket.wrConn)
go handlerSocket.wrwriter(handlerSocket.wrConn)
indexes = make(map[int][]string, 10)
handlerSocket.connected = true
return
}
/**
* Parse params given to Connect()
*/
func (handlerSocket *HandlerSocket) parseParams(p []interface{}) {
handlerSocket.auth = new(HandlerSocketAuth)
// Assign default values
handlerSocket.auth.readPort = DefaultReadPort
handlerSocket.auth.writePort = DefaultWritePort
// Host / username are required
handlerSocket.auth.host = p[0].(string)
if len(p) > 1 {
handlerSocket.auth.readPort = p[1].(int)
}
if len(p) > 3 {
handlerSocket.auth.writePort = p[2].(int)
}
return
}
func (f *hsopencommand) write(w io.Writer) error {
if _, err := fmt.Fprintf(w, "%s\t%s\n", f.command, strings.Join(f.params, "\t")); err != nil {
return err
}
return nil
}
func (f *hsfindcommand) write(w io.Writer) error {
if _, err := fmt.Fprintf(w, "%s\t%s\t%d\t%d\n", f.command, strings.Join(f.params, "\t"), f.limit, f.offset); err != nil {
return err
}
return nil
}
func (f *hsmodifycommand) write(w io.Writer) error {
if _, err := fmt.Fprintf(w, "%s\t%s\t%d\t%d\t%s\t%s\n", f.command, strings.Join(f.criteria, "\t"), f.limit, f.offset, f.mop, strings.Join(f.newvals, "\t")); err != nil {
return err
}
return nil
}
func (f *hsinsertcommand) write(w io.Writer) error {
if _, err := fmt.Fprintf(w, "%s\t%s\n", f.command, strings.Join(f.params, "\t")); err != nil {
return err
}
return nil
}
func (c *HandlerSocket) reader(nc net.Conn) {
br := bufio.NewReader(nc)
var retString string
var bytes []byte
for {
b, err := br.ReadByte()
if err != nil {
// TODO(adg) handle error
if err == io.EOF {
break
}
break
}
if string(b) != "\n" {
bytes = append(bytes, b)
} else {
retString = string(bytes)
strs := strings.Split(retString, "\t") //, -1)
hsr := HandlerSocketResponse{ReturnCode: strs[0], Data: strs[1:]}
c.in <- hsr
retString = ""
bytes = []byte{}
}
}
nc.Close()
c.connected = false
}
func (c *HandlerSocket) writer(nc net.Conn) {
bw := bufio.NewWriter(nc)
for f := range c.out {
if err := f.write(bw); err != nil {
panic(err)
}
if err := bw.Flush(); err != nil {
panic(err)
}
}
nc.Close()
c.connected = false
}
func (c *HandlerSocket) wrreader(nc net.Conn) {
br := bufio.NewReader(nc)
var retString string
for {
b, err := br.ReadByte()
if err != nil {
if err == io.EOF {
break
}
}
retString += string(b)
if string(b) == "\n" {
strs := strings.Split(retString, "\t") //, -1)
hsr := HandlerSocketResponse{ReturnCode: strs[0], Data: strs[1:]}
c.wrIn <- hsr
retString = ""
}
}
nc.Close()
c.connected = false
}
func (c *HandlerSocket) wrwriter(nc net.Conn) {
bw := bufio.NewWriter(nc)
for f := range c.wrOut {
if err := f.write(bw); err != nil {
panic(err)
}
if err := bw.Flush(); err != nil {
panic(err)
}
}
nc.Close()
c.connected = false
}