-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathservice.go
executable file
·399 lines (338 loc) · 11.5 KB
/
service.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
/**
* Copyright 2013-2016 Seagate Technology LLC.
*
* This Source Code Form is subject to the terms of the Mozilla
* Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at
* https://mozilla.org/MP:/2.0/.
*
* This program is distributed in the hope that it will be useful,
* but is provided AS-IS, WITHOUT ANY WARRANTY; including without
* the implied warranty of MERCHANTABILITY, NON-INFRINGEMENT or
* FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public
* License for more details.
*
* See www.openkinetic.org for more project information
*/
package kinetic
import (
"crypto/tls"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"sync"
"time"
kproto "github.com/Kinetic/kinetic-go/proto"
proto "github.com/golang/protobuf/proto"
)
const (
defaultConnectionTimeout = 20 * time.Second
defaultRequestTimeout = 60 * time.Second
)
var (
connectionTimeout = defaultConnectionTimeout
requestTimeout = defaultRequestTimeout
)
func newMessage(t kproto.Message_AuthType) *kproto.Message {
msg := &kproto.Message{
AuthType: t.Enum(),
}
if msg.GetAuthType() == kproto.Message_HMACAUTH {
msg.HmacAuth = &kproto.Message_HMACauth{}
}
return msg
}
func newCommand(t kproto.Command_MessageType) *kproto.Command {
return &kproto.Command{
Header: &kproto.Command_Header{
MessageType: t.Enum(),
},
}
}
type networkService struct {
rxMu sync.Mutex
txMu sync.Mutex
mapMu sync.Mutex
conn net.Conn
clusterVersion int64 // Cluster version
seq int64 // Operation sequence ID
connID int64 // current connection ID
option ClientOptions // current connection operation
hmap map[int64]*ResponseHandler // Message handler map
fatal bool // Network has fatal failure
fatalError error // Network fatal error details
device Log // Store device information from handshake package
}
func newNetworkService(op ClientOptions) (*networkService, error) {
var conn net.Conn
var err error
if op.Timeout > 0 {
connectionTimeout = time.Duration(op.Timeout) * time.Millisecond
}
if op.RequestTimeout > 0 {
requestTimeout = time.Duration(op.RequestTimeout) * time.Millisecond
}
target := fmt.Sprintf("%s:%d", op.Host, op.Port)
if op.UseSSL {
// TODO: Need to enable verify certification later
config := tls.Config{InsecureSkipVerify: true}
d := &net.Dialer{Timeout: connectionTimeout}
conn, err = tls.DialWithDialer(d, "tcp", target, &config)
} else {
conn, err = net.DialTimeout("tcp", target, connectionTimeout)
}
if err != nil {
klog.Error("Can't establish connection to ", op.Host, err)
return nil, err
}
ns := &networkService{
conn: conn,
clusterVersion: 0,
seq: 0,
connID: -1,
option: op,
hmap: make(map[int64]*ResponseHandler),
fatal: false,
fatalError: nil,
}
ns.rxMu.Lock()
// Do the handshake.
// Device Configuration and Limits from handshake will be stored in networkService.device
_, _, _, err = ns.receive()
ns.rxMu.Unlock()
if err != nil {
klog.Error("Can't establish connection to %s", op.Host)
return nil, err
}
klog.Debugf("Connected to %s:%d", op.Host, op.Port)
klog.Debugf("\tVendor: %s", ns.device.Configuration.Vendor)
klog.Debugf("\tModel: %s", ns.device.Configuration.Model)
klog.Debugf("\tWorldWideName: %s", ns.device.Configuration.WorldWideName)
klog.Debugf("\tSerial Number: %s", ns.device.Configuration.SerialNumber)
klog.Debugf("\tFirmware Version: %s", ns.device.Configuration.Version)
klog.Debugf("\tKinetic Protocol Version: %s", ns.device.Configuration.ProtocolVersion)
klog.Debugf("\tPort: %d", ns.device.Configuration.Port)
klog.Debugf("\tTlsPort: %d", ns.device.Configuration.TLSPort)
klog.Debugf("\tCurrentPowerLevel : %s", ns.device.Configuration.CurrentPowerLevel.String())
return ns, nil
}
// When client network service has error, call error handling
// from all Messagehandler current in Queue.
func (ns *networkService) clientError(s Status, mh *ResponseHandler) {
ns.mapMu.Lock()
for ack, h := range ns.hmap {
h.fail(s)
delete(ns.hmap, ack)
}
ns.mapMu.Unlock()
if mh != nil {
mh.fail(s)
}
}
func (ns *networkService) listen() error {
if ns.fatal {
return errors.New("Can't listen, network service has fatal error: " + ns.fatalError.Error())
}
ns.mapMu.Lock()
if len(ns.hmap) == 0 {
ns.mapMu.Unlock()
return nil
}
ns.mapMu.Unlock()
ns.rxMu.Lock()
msg, cmd, value, err := ns.receive()
ns.rxMu.Unlock()
if err != nil {
klog.Error("Network Service listen error")
return err
}
if cmd.GetHeader() != nil {
klog.Debug("Kinetic response received ", cmd.GetHeader().GetMessageType().String(),
", AckSeq = ", cmd.GetHeader().GetAckSequence(),
", Code = ", cmd.GetStatus().GetCode())
} else if msg.GetAuthType() == kproto.Message_UNSOLICITEDSTATUS {
klog.Debug("Kinetic UNSOLICITEDSTATUS : ",
"Code = ", cmd.GetStatus().GetCode(),
", StatusMessage = ", cmd.GetStatus().GetStatusMessage())
}
// For UNSOLICITEDSTATUS, command may not have Header or AckSequence, set the ack to -1 so
// no ResponseHandler will be found from hmap table.
var ack int64 = -1
if cmd.GetHeader() != nil {
ack = cmd.GetHeader().GetAckSequence()
}
ns.mapMu.Lock()
h, ok := ns.hmap[ack]
ns.mapMu.Unlock()
if ok == false {
// It's high chance this is an UNSOLICITEDSTATUS message, display the Status.
klog.Errorf("Couldn't find a handler for acksequence %d, status=%s", ack, getStatusFromProto(cmd).String())
// This is an unexpected packet. Each listen() call expect remove one ResponseHandler from hmap.
// So need to fire another listen() to make sure ResponseHandler in hmap got chance to exit.
// Either by receive correct packet, or network read failure.
go ns.listen()
return nil
}
h.handle(cmd, value)
ns.mapMu.Lock()
delete(ns.hmap, ack)
ns.mapMu.Unlock()
return nil
}
// submit will send the message to kinetic device, insert ResponseHandler for this message sequence number.
// ResponseHandler can be nil if the message no require for Ack, eg batch PUT / DELETE.
func (ns *networkService) submit(msg *kproto.Message, cmd *kproto.Command, value []byte, h *ResponseHandler) error {
if ns.fatal {
return errors.New("Can't submit, network service has fatal error: " + ns.fatalError.Error())
}
ns.txMu.Lock()
cmd.GetHeader().ConnectionID = &ns.connID
cmd.GetHeader().Sequence = &ns.seq
cmd.GetHeader().ClusterVersion = &ns.clusterVersion
cmdBytes, err := proto.Marshal(cmd)
if err != nil {
klog.Error("Error marshl Kinetic Command")
s := Status{Code: ClientInternalError, ErrorMsg: "Error marshl Kinetic Command"}
ns.clientError(s, h)
return err
}
msg.CommandBytes = cmdBytes[:]
if msg.GetAuthType() == kproto.Message_HMACAUTH {
msg.GetHmacAuth().Identity = &ns.option.User
msg.GetHmacAuth().Hmac = computeHmac(msg.CommandBytes, ns.option.Hmac)
}
klog.Debug("Kinetic message send ", cmd.GetHeader().GetMessageType().String(), " Seq = ", ns.seq)
err = ns.send(msg, value)
if err != nil {
return err
}
if h != nil {
ns.mapMu.Lock()
ns.hmap[ns.seq] = h
ns.mapMu.Unlock()
}
ns.seq++
ns.txMu.Unlock()
return nil
}
func (ns *networkService) send(msg *kproto.Message, value []byte) error {
msgBytes, err := proto.Marshal(msg)
if err != nil {
s := Status{Code: ClientInternalError, ErrorMsg: "Error marshl Kinetic Message"}
ns.clientError(s, nil)
return err
}
// Set timeout for send packet
ns.conn.SetWriteDeadline(time.Now().Add(requestTimeout))
// Construct message header 9 bytes
header := make([]byte, 9)
header[0] = 'F' // Magic number
binary.BigEndian.PutUint32(header[1:5], uint32(len(msgBytes)))
binary.BigEndian.PutUint32(header[5:9], uint32(len(value)))
packet := append(header, msgBytes...)
if value != nil && len(value) > 0 {
packet = append(packet, value...)
}
_, err = ns.conn.Write(packet)
if err != nil {
klog.Error("Network I/O write error, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O write error, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return err
}
return nil
}
func (ns *networkService) receive() (*kproto.Message, *kproto.Command, []byte, error) {
// Set timeout for receive packet
ns.conn.SetReadDeadline(time.Now().Add(requestTimeout))
header := make([]byte, 9)
_, err := io.ReadFull(ns.conn, header[0:])
if err != nil {
klog.Error("Network I/O read error, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return nil, nil, nil, err
}
magic := header[0]
if magic != 'F' {
klog.Error("Network I/O read error Header wrong magic")
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error Header wrong magic"}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = errors.New("Wrong magic number")
return nil, nil, nil, errors.New("Network I/O read error Header wrong magic")
}
protoLen := int(binary.BigEndian.Uint32(header[1:5]))
valueLen := int(binary.BigEndian.Uint32(header[5:9]))
protoBuf := make([]byte, protoLen)
_, err = io.ReadFull(ns.conn, protoBuf)
if err != nil {
klog.Error("Network I/O read error receive Kinetic Header, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error receive Kinetic Header, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return nil, nil, nil, err
}
msg := &kproto.Message{}
err = proto.Unmarshal(protoBuf, msg)
if err != nil {
klog.Error("Network I/O read error receive Kinetic Header, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error reaceive Kinetic Message, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return nil, nil, nil, err
}
if msg.GetAuthType() == kproto.Message_HMACAUTH && validateHmac(msg, ns.option.Hmac) == false {
klog.Error("Response HMAC mismatch")
s := Status{Code: ClientResponseHMACError, ErrorMsg: "Response HMAC mismatch"}
ns.clientError(s, nil)
return nil, nil, nil, err
}
cmd := &kproto.Command{}
err = proto.Unmarshal(msg.CommandBytes, cmd)
if err != nil {
klog.Error("Network I/O read error parsing Kinetic Command, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error parsing Kinetic Command, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return nil, nil, nil, err
}
if cmd.Header != nil && cmd.Header.ConnectionID != nil {
if ns.connID < 0 {
// This is handshake packet
ns.device = getLogFromProto(cmd)
// Only update client cluster version during Handshake
if cmd.Header.ClusterVersion != nil {
ns.clusterVersion = cmd.GetHeader().GetClusterVersion()
}
}
ns.connID = cmd.GetHeader().GetConnectionID()
}
if valueLen > 0 {
valueBuf := make([]byte, valueLen)
_, err = io.ReadFull(ns.conn, valueBuf)
if err != nil {
klog.Error("Network I/O read error parsing Kinetic Value, " + err.Error())
s := Status{Code: ClientIOError, ErrorMsg: "Network I/O read error parsing Kinetic Value, " + err.Error()}
ns.clientError(s, nil)
ns.fatal = true
ns.fatalError = err
return nil, nil, nil, err
}
return msg, cmd, valueBuf, nil
}
return msg, cmd, nil, nil
}
func (ns *networkService) close() {
ns.conn.Close()
klog.Debugf("Connection to %s closed", ns.option.Host)
}