/
stream_conn.go
233 lines (206 loc) · 6.24 KB
/
stream_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
// Copyright 2018 The Chubao Authors.
//
// 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 stream
import (
"fmt"
"net"
"sync/atomic"
"time"
"github.com/chubaofs/chubaofs/sdk/data/wrapper"
"github.com/chubaofs/chubaofs/util"
"github.com/chubaofs/chubaofs/util/errors"
"github.com/chubaofs/chubaofs/util/log"
)
var (
TryOtherAddrError = errors.New("TryOtherAddrError")
)
const (
StreamSendMaxRetry = 200
StreamSendSleepInterval = 100 * time.Millisecond
)
type GetReplyFunc func(conn *net.TCPConn) (err error, again bool)
// StreamConn defines the struct of the stream connection.
type StreamConn struct {
dp *wrapper.DataPartition
currAddr string
}
var (
StreamConnPool = util.NewConnectPool()
)
// NewStreamConn returns a new stream connection.
func NewStreamConn(dp *wrapper.DataPartition, follower bool) (sc *StreamConn) {
if !follower {
sc = &StreamConn{
dp: dp,
currAddr: dp.LeaderAddr,
}
return
}
defer func() {
if sc.currAddr == "" {
/*
* If followerRead is enabled, and there is no preferred choice,
* currAddr can be arbitrarily selected from the hosts.
*/
for _, h := range dp.Hosts {
if h != "" {
sc.currAddr = h
break
}
}
}
}()
if dp.ClientWrapper.NearRead() {
sc = &StreamConn{
dp: dp,
currAddr: getNearestHost(dp),
}
return
}
epoch := atomic.AddUint64(&dp.Epoch, 1)
hosts := sortByStatus(dp, false)
choice := len(hosts)
currAddr := dp.LeaderAddr
if choice > 0 {
index := int(epoch) % choice
currAddr = hosts[index]
}
sc = &StreamConn{
dp: dp,
currAddr: currAddr,
}
return
}
// String returns the string format of the stream connection.
func (sc *StreamConn) String() string {
return fmt.Sprintf("Partition(%v) CurrentAddr(%v) Hosts(%v)", sc.dp.PartitionID, sc.currAddr, sc.dp.Hosts)
}
// Send send the given packet over the network through the stream connection until success
// or the maximum number of retries is reached.
func (sc *StreamConn) Send(req *Packet, getReply GetReplyFunc) (err error) {
for i := 0; i < StreamSendMaxRetry; i++ {
err = sc.sendToPartition(req, getReply)
if err == nil {
return
}
log.LogWarnf("StreamConn Send: err(%v)", err)
time.Sleep(StreamSendSleepInterval)
}
return errors.New(fmt.Sprintf("StreamConn Send: retried %v times and still failed, sc(%v) reqPacket(%v)", StreamSendMaxRetry, sc, req))
}
func (sc *StreamConn) sendToPartition(req *Packet, getReply GetReplyFunc) (err error) {
conn, err := StreamConnPool.GetConnect(sc.currAddr)
if err == nil {
err = sc.sendToConn(conn, req, getReply)
if err == nil {
StreamConnPool.PutConnect(conn, false)
return
}
log.LogWarnf("sendToPartition: send to curr addr failed, addr(%v) reqPacket(%v) err(%v)", sc.currAddr, req, err)
StreamConnPool.PutConnect(conn, true)
if err != TryOtherAddrError {
return
}
} else {
log.LogWarnf("sendToPartition: get connection to curr addr failed, addr(%v) reqPacket(%v) err(%v)", sc.currAddr, req, err)
}
hosts := sortByStatus(sc.dp, true)
for _, addr := range hosts {
log.LogWarnf("sendToPartition: try addr(%v) reqPacket(%v)", addr, req)
conn, err = StreamConnPool.GetConnect(addr)
if err != nil {
log.LogWarnf("sendToPartition: failed to get connection to addr(%v) reqPacket(%v) err(%v)", addr, req, err)
continue
}
sc.currAddr = addr
sc.dp.LeaderAddr = addr
err = sc.sendToConn(conn, req, getReply)
if err == nil {
StreamConnPool.PutConnect(conn, false)
return
}
StreamConnPool.PutConnect(conn, true)
if err != TryOtherAddrError {
return
}
log.LogWarnf("sendToPartition: try addr(%v) failed! reqPacket(%v) err(%v)", addr, req, err)
}
return errors.New(fmt.Sprintf("sendToPatition Failed: sc(%v) reqPacket(%v)", sc, req))
}
func (sc *StreamConn) sendToConn(conn *net.TCPConn, req *Packet, getReply GetReplyFunc) (err error) {
for i := 0; i < StreamSendMaxRetry; i++ {
log.LogDebugf("sendToConn: send to addr(%v), reqPacket(%v)", sc.currAddr, req)
err = req.WriteToConn(conn)
if err != nil {
msg := fmt.Sprintf("sendToConn: failed to write to addr(%v) err(%v)", sc.currAddr, err)
log.LogWarn(msg)
break
}
var again bool
err, again = getReply(conn)
if !again {
if err != nil {
log.LogWarnf("sendToConn: getReply error and RETURN, addr(%v) reqPacket(%v) err(%v)", sc.currAddr, req, err)
}
break
}
log.LogWarnf("sendToConn: getReply error and will RETRY, sc(%v) err(%v)", sc, err)
time.Sleep(StreamSendSleepInterval)
}
log.LogDebugf("sendToConn exit: send to addr(%v) reqPacket(%v) err(%v)", sc.currAddr, req, err)
return
}
// sortByStatus will return hosts list sort by host status for DataPartition.
// If param selectAll is true, hosts with status(true) is in front and hosts with status(false) is in behind.
// If param selectAll is false, only return hosts with status(true).
func sortByStatus(dp *wrapper.DataPartition, selectAll bool) (hosts []string) {
var failedHosts []string
hostsStatus := dp.ClientWrapper.HostsStatus
var dpHosts []string
if dp.ClientWrapper.FollowerRead() && dp.ClientWrapper.NearRead() {
dpHosts = dp.NearHosts
} else {
dpHosts = dp.Hosts
}
for _, addr := range dpHosts {
status, ok := hostsStatus[addr]
if ok {
if status {
hosts = append(hosts, addr)
} else {
failedHosts = append(failedHosts, addr)
}
} else {
failedHosts = append(failedHosts, addr)
log.LogWarnf("sortByStatus: can not find host[%v] in HostsStatus, dp[%d]", addr, dp.PartitionID)
}
}
if selectAll {
hosts = append(hosts, failedHosts...)
}
return
}
func getNearestHost(dp *wrapper.DataPartition) string {
hostsStatus := dp.ClientWrapper.HostsStatus
for _, addr := range dp.NearHosts {
status, ok := hostsStatus[addr]
if ok {
if !status {
continue
}
}
return addr
}
return dp.LeaderAddr
}