This repository has been archived by the owner on Sep 17, 2021. It is now read-only.
forked from c4pt0r/go-hbase
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathconn.go
291 lines (247 loc) · 5.74 KB
/
conn.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
package hbase
import (
"bufio"
"bytes"
"io"
"net"
"strings"
"sync"
pb "github.com/golang/protobuf/proto"
"github.com/juju/errors"
"github.com/ngaut/log"
"github.com/pingcap/go-hbase/iohelper"
"github.com/pingcap/go-hbase/proto"
)
type ServiceType byte
const (
MasterMonitorService = iota + 1
MasterService
MasterAdminService
AdminService
ClientService
RegionServerStatusService
)
// convert above const to protobuf string
var ServiceString = map[ServiceType]string{
MasterMonitorService: "MasterMonitorService",
MasterService: "MasterService",
MasterAdminService: "MasterAdminService",
AdminService: "AdminService",
ClientService: "ClientService",
RegionServerStatusService: "RegionServerStatusService",
}
type idGenerator struct {
n int
mu *sync.RWMutex
}
func newIdGenerator() *idGenerator {
return &idGenerator{
n: 0,
mu: &sync.RWMutex{},
}
}
func (a *idGenerator) get() int {
a.mu.RLock()
v := a.n
a.mu.RUnlock()
return v
}
func (a *idGenerator) incrAndGet() int {
a.mu.Lock()
a.n++
v := a.n
a.mu.Unlock()
return v
}
type connection struct {
mu sync.Mutex
addr string
conn net.Conn
bw *bufio.Writer
idGen *idGenerator
serviceType ServiceType
in chan *iohelper.PbBuffer
ongoingCalls map[int]*call
}
func processMessage(msg []byte) ([][]byte, error) {
buf := pb.NewBuffer(msg)
payloads := make([][]byte, 0)
// Question: why can we ignore this error?
for {
hbytes, err := buf.DecodeRawBytes(true)
if err != nil {
// Check whether error is `unexpected EOF`.
if strings.Contains(err.Error(), "unexpected EOF") {
break
}
log.Errorf("Decode raw bytes error - %v", errors.ErrorStack(err))
return nil, errors.Trace(err)
}
payloads = append(payloads, hbytes)
}
return payloads, nil
}
func readPayloads(r io.Reader) ([][]byte, error) {
nBytesExpecting, err := iohelper.ReadInt32(r)
if err != nil {
return nil, errors.Trace(err)
}
if nBytesExpecting > 0 {
buf, err := iohelper.ReadN(r, nBytesExpecting)
// Question: why should we return error only when we get an io.EOF error?
if err != nil && ErrorEqual(err, io.EOF) {
return nil, errors.Trace(err)
}
payloads, err := processMessage(buf)
if err != nil {
return nil, errors.Trace(err)
}
if len(payloads) > 0 {
return payloads, nil
}
}
return nil, errors.New("unexpected payload")
}
func newConnection(addr string, srvType ServiceType) (*connection, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
return nil, errors.Trace(err)
}
if _, ok := ServiceString[srvType]; !ok {
return nil, errors.Errorf("unexpected service type [serviceType=%d]", srvType)
}
c := &connection{
addr: addr,
bw: bufio.NewWriter(conn),
conn: conn,
in: make(chan *iohelper.PbBuffer, 20),
serviceType: srvType,
idGen: newIdGenerator(),
ongoingCalls: map[int]*call{},
}
err = c.init()
if err != nil {
return nil, errors.Trace(err)
}
return c, nil
}
func (c *connection) init() error {
err := c.writeHead()
if err != nil {
return errors.Trace(err)
}
err = c.writeConnectionHeader()
if err != nil {
return errors.Trace(err)
}
go func() {
err := c.processMessages()
if err != nil {
log.Warnf("process messages failed - %v", errors.ErrorStack(err))
return
}
}()
go c.dispatch()
return nil
}
func (c *connection) processMessages() error {
for {
msgs, err := readPayloads(c.conn)
if err != nil {
return errors.Trace(err)
}
var rh proto.ResponseHeader
err = pb.Unmarshal(msgs[0], &rh)
if err != nil {
return errors.Trace(err)
}
callId := rh.GetCallId()
c.mu.Lock()
call, ok := c.ongoingCalls[int(callId)]
if !ok {
c.mu.Unlock()
return errors.Errorf("Invalid call id: %d", callId)
}
delete(c.ongoingCalls, int(callId))
c.mu.Unlock()
exception := rh.GetException()
if exception != nil {
call.complete(errors.Errorf("Exception returned: %s\n%s", exception.GetExceptionClassName(), exception.GetStackTrace()), nil)
} else if len(msgs) == 2 {
call.complete(nil, msgs[1])
}
}
}
func (c *connection) writeHead() error {
buf := bytes.NewBuffer(nil)
buf.Write(hbaseHeaderBytes)
buf.WriteByte(0)
buf.WriteByte(80)
_, err := c.conn.Write(buf.Bytes())
return errors.Trace(err)
}
func (c *connection) writeConnectionHeader() error {
buf := iohelper.NewPbBuffer()
service := pb.String(ServiceString[c.serviceType])
err := buf.WritePBMessage(&proto.ConnectionHeader{
UserInfo: &proto.UserInformation{
EffectiveUser: pb.String("pingcap"),
},
ServiceName: service,
})
if err != nil {
return errors.Trace(err)
}
err = buf.PrependSize()
if err != nil {
return errors.Trace(err)
}
_, err = c.conn.Write(buf.Bytes())
if err != nil {
return errors.Trace(err)
}
return nil
}
func (c *connection) dispatch() {
for {
select {
case buf := <-c.in:
// TODO: add error check.
c.bw.Write(buf.Bytes())
if len(c.in) == 0 {
c.bw.Flush()
}
}
}
}
func (c *connection) call(request *call) error {
id := c.idGen.incrAndGet()
rh := &proto.RequestHeader{
CallId: pb.Uint32(uint32(id)),
MethodName: pb.String(request.methodName),
RequestParam: pb.Bool(true),
}
request.id = uint32(id)
bfrh := iohelper.NewPbBuffer()
err := bfrh.WritePBMessage(rh)
if err != nil {
return errors.Trace(err)
}
bfr := iohelper.NewPbBuffer()
err = bfr.WritePBMessage(request.request)
if err != nil {
return errors.Trace(err)
}
// Buf =>
// | total size | pb1 size | pb1 | pb2 size | pb2 | ...
buf := iohelper.NewPbBuffer()
buf.WriteDelimitedBuffers(bfrh, bfr)
c.mu.Lock()
c.ongoingCalls[id] = request
c.in <- buf
c.mu.Unlock()
return nil
}
func (c *connection) close() error {
return c.conn.Close()
}