-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
276 lines (228 loc) · 6.25 KB
/
connection.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
package siridb
import (
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"time"
qpack "github.com/transceptor-technology/go-qpack"
)
// Connection is a SiriDB Connection. Port should be the client port.
type Connection struct {
host string
port uint16
pid uint16
buf *Buffer
respMap map[uint16]chan *Pkg
OnClose func()
LogCh chan string
mux sync.Mutex
}
// NewConnection creates a new connection connection
func NewConnection(host string, port uint16) *Connection {
return &Connection{
host: host,
port: port,
pid: 0,
buf: NewBuffer(),
respMap: make(map[uint16]chan *Pkg),
OnClose: nil,
LogCh: nil,
}
}
// ToString returns a string representing the connection and port.
func (conn *Connection) ToString() string {
if strings.Count(conn.host, ":") > 0 {
return fmt.Sprintf("[%s]:%d", conn.host, conn.port)
}
return fmt.Sprintf("%s:%d", conn.host, conn.port)
}
// Info returns siridb info
func (conn *Connection) Info() (interface{}, error) {
err := conn.connect()
if err != nil {
return nil, err
}
return conn.Send(CprotoReqInfo, nil, 10)
}
// Manage send a manage server request.
func (conn *Connection) Manage(username, password string, tp int, options map[string]interface{}) (interface{}, error) {
err := conn.connect()
if err != nil {
return nil, err
}
return conn.Send(CprotoReqAdmin, []interface{}{username, password, tp, options}, 60)
}
// Connect to a SiriDB connection.
func (conn *Connection) Connect(username, password, dbname string) error {
err := conn.connect()
if err != nil {
return err
}
_, err = conn.Send(
CprotoReqAuth,
[]string{username, password, dbname},
10)
return err
}
// IsConnected returns true when connected.
func (conn *Connection) IsConnected() bool {
return conn.buf.conn != nil
}
// Query sends a query and returns the result.
func (conn *Connection) Query(query string, timeout uint16) (interface{}, error) {
return conn.Send(CprotoReqQuery, []interface{}{query, nil}, timeout)
}
// Insert sends data to a SiriDB database.
func (conn *Connection) Insert(data interface{}, timeout uint16) (interface{}, error) {
return conn.Send(CprotoReqInsert, data, timeout)
}
// InsertBin sends binary data to a SiriDB database.
func (conn *Connection) InsertBin(data []byte, timeout uint16) (interface{}, error) {
return conn.SendBin(CprotoReqInsert, data, timeout)
}
func getResult(respCh chan *Pkg, timeoutCh chan bool) (interface{}, error) {
var result interface{}
var err error
select {
case pkg := <-respCh:
switch pkg.tp {
case CprotoResQuery, CprotoResInsert, CprotoResInfo, CprotoAckAdminData:
result, err = qpack.Unpack(pkg.data, qpack.QpFlagStringKeysOnly)
case CprotoResAuthSuccess, CprotoResAck, CprotoAckAdmin:
result = true
case CprotoResFile:
result = pkg.data
case CprotoErrMsg, CprotoErrUserAccess, CprotoErrPool, CprotoErrServer, CprotoErrQuery, CprotoErrInsert, CprotoErrAdmin:
err = NewError(getErrorMsg(pkg.data), pkg.tp)
case CprotoErrAdminInvalidRequest:
err = NewError("invalid request", pkg.tp)
case CprotoErr:
err = NewError("runtime error", pkg.tp)
case CprotoErrNotAuthenticated:
err = NewError("not authenticated", pkg.tp)
case CprotoErrAuthCredentials:
err = NewError("invalid credentials", pkg.tp)
case CprotoErrAuthUnknownDb:
err = NewError("unknown database", pkg.tp)
case CprotoErrLoadingDb:
err = NewError("error loading database", pkg.tp)
case CprotoErrFile:
err = NewError("error while downloading file", pkg.tp)
default:
err = fmt.Errorf("Unknown package type: %d", pkg.tp)
}
case <-timeoutCh:
err = fmt.Errorf("Query timeout reached")
}
return result, err
}
func (conn *Connection) increPid() uint16 {
conn.mux.Lock()
pid := conn.pid
conn.pid++
conn.mux.Unlock()
return pid
}
func (conn *Connection) getRespCh(pid uint16, b []byte, timeout uint16) (interface{}, error) {
respCh := make(chan *Pkg, 1)
conn.mux.Lock()
conn.respMap[pid] = respCh
conn.mux.Unlock()
conn.buf.conn.Write(b)
timeoutCh := make(chan bool, 1)
go func() {
time.Sleep(time.Duration(timeout) * time.Second)
timeoutCh <- true
}()
result, err := getResult(respCh, timeoutCh)
conn.mux.Lock()
delete(conn.respMap, pid)
conn.mux.Unlock()
return result, err
}
// Send is used to send bytes
func (conn *Connection) Send(tp uint8, data interface{}, timeout uint16) (interface{}, error) {
pid := conn.increPid()
b, err := pack(pid, tp, data)
if err != nil {
return nil, err
}
return conn.getRespCh(pid, b, timeout)
}
// SendBin is used to send bytes
func (conn *Connection) SendBin(tp uint8, data []byte, timeout uint16) (interface{}, error) {
pid := conn.increPid()
b, err := packBin(pid, tp, data)
if err != nil {
return nil, err
}
return conn.getRespCh(pid, b, timeout)
}
func niceErr(err error) string {
if err == io.EOF {
return "connection lost"
}
return err.Error()
}
// Listen to data channels
func (conn *Connection) Listen() {
for {
select {
case pkg := <-conn.buf.DataCh:
conn.mux.Lock()
if respCh, ok := conn.respMap[pkg.pid]; ok {
conn.mux.Unlock()
respCh <- pkg
} else {
conn.mux.Unlock()
conn.sendLog("no response channel found for pid %d, probably the task has been cancelled ot timed out.", pkg.pid)
}
case err := <-conn.buf.ErrCh:
conn.sendLog("%s (%s:%d)", niceErr(err), conn.host, conn.port)
conn.buf.conn.Close()
conn.buf.conn = nil
if conn.OnClose != nil {
conn.OnClose()
}
}
}
}
// Close will close an open connection.
func (conn *Connection) Close() {
if conn.buf.conn != nil {
conn.sendLog("closing connection to %s:%d", conn.host, conn.port)
conn.buf.conn.Close()
}
}
func (conn *Connection) sendLog(s string, a ...interface{}) {
msg := fmt.Sprintf(s, a...)
if conn.LogCh == nil {
log.Println(msg)
} else {
conn.LogCh <- msg
}
}
func (conn *Connection) connect() error {
if conn.IsConnected() {
return nil
}
cn, err := net.Dial("tcp", conn.ToString())
if err != nil {
return err
}
conn.sendLog("connected to %s:%d", conn.host, conn.port)
conn.buf.conn = cn
go conn.buf.Read()
go conn.Listen()
return nil
}
func getErrorMsg(b []byte) string {
result, err := qpack.Unpack(b, qpack.QpFlagStringKeysOnly)
if err != nil {
return err.Error()
}
return result.(map[string]interface{})["error_msg"].(string)
}