-
Notifications
You must be signed in to change notification settings - Fork 645
/
wrapper.go
356 lines (308 loc) · 10.3 KB
/
wrapper.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
// 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 wrapper
import (
"fmt"
"net"
"strings"
"sync"
"time"
"github.com/chubaofs/chubaofs/proto"
masterSDK "github.com/chubaofs/chubaofs/sdk/master"
"github.com/chubaofs/chubaofs/util/errors"
"github.com/chubaofs/chubaofs/util/iputil"
"github.com/chubaofs/chubaofs/util/log"
)
var (
LocalIP string
MinWriteAbleDataPartitionCnt = 10
)
type DataPartitionView struct {
DataPartitions []*DataPartition
}
// Wrapper TODO rename. This name does not reflect what it is doing.
type Wrapper struct {
sync.RWMutex
clusterName string
volName string
masters []string
partitions map[uint64]*DataPartition
followerRead bool
followerReadClientCfg bool
nearRead bool
dpSelectorChanged bool
dpSelectorName string
dpSelectorParm string
mc *masterSDK.MasterClient
stopOnce sync.Once
stopC chan struct{}
dpSelector DataPartitionSelector
HostsStatus map[string]bool
}
// NewDataPartitionWrapper returns a new data partition wrapper.
func NewDataPartitionWrapper(volName string, masters []string) (w *Wrapper, err error) {
w = new(Wrapper)
w.stopC = make(chan struct{})
w.masters = masters
w.mc = masterSDK.NewMasterClient(masters, false)
w.volName = volName
w.partitions = make(map[uint64]*DataPartition)
w.HostsStatus = make(map[string]bool)
if err = w.updateClusterInfo(); err != nil {
err = errors.Trace(err, "NewDataPartitionWrapper:")
return
}
if err = w.getSimpleVolView(); err != nil {
err = errors.Trace(err, "NewDataPartitionWrapper:")
return
}
if err = w.initDpSelector(); err != nil {
log.LogErrorf("NewDataPartitionWrapper: init initDpSelector failed, [%v]", err)
}
if err = w.updateDataPartition(true); err != nil {
err = errors.Trace(err, "NewDataPartitionWrapper:")
return
}
if err = w.updateDataNodeStatus(); err != nil {
log.LogErrorf("NewDataPartitionWrapper: init DataNodeStatus failed, [%v]", err)
}
go w.update()
return
}
func (w *Wrapper) Stop() {
w.stopOnce.Do(func() {
close(w.stopC)
})
}
func (w *Wrapper) InitFollowerRead(clientConfig bool) {
w.followerReadClientCfg = clientConfig
w.followerRead = w.followerReadClientCfg || w.followerRead
}
func (w *Wrapper) FollowerRead() bool {
return w.followerRead
}
func (w *Wrapper) updateClusterInfo() (err error) {
var info *proto.ClusterInfo
if info, err = w.mc.AdminAPI().GetClusterInfo(); err != nil {
log.LogWarnf("UpdateClusterInfo: get cluster info fail: err(%v)", err)
return
}
log.LogInfof("UpdateClusterInfo: get cluster info: cluster(%v) localIP(%v)", info.Cluster, info.Ip)
w.clusterName = info.Cluster
LocalIP = info.Ip
return
}
func (w *Wrapper) getSimpleVolView() (err error) {
var view *proto.SimpleVolView
if view, err = w.mc.AdminAPI().GetVolumeSimpleInfo(w.volName); err != nil {
log.LogWarnf("getSimpleVolView: get volume simple info fail: volume(%v) err(%v)", w.volName, err)
return
}
w.followerRead = view.FollowerRead
w.dpSelectorName = view.DpSelectorName
w.dpSelectorParm = view.DpSelectorParm
log.LogInfof("getSimpleVolView: get volume simple info: ID(%v) name(%v) owner(%v) status(%v) capacity(%v) "+
"metaReplicas(%v) dataReplicas(%v) mpCnt(%v) dpCnt(%v) followerRead(%v) createTime(%v) dpSelectorName(%v) "+
"dpSelectorParm(%v)",
view.ID, view.Name, view.Owner, view.Status, view.Capacity, view.MpReplicaNum, view.DpReplicaNum, view.MpCnt,
view.DpCnt, view.FollowerRead, view.CreateTime, view.DpSelectorName, view.DpSelectorParm)
return nil
}
func (w *Wrapper) update() {
ticker := time.NewTicker(time.Minute)
for {
select {
case <-ticker.C:
w.updateSimpleVolView()
w.updateDataPartition(false)
w.updateDataNodeStatus()
case <-w.stopC:
return
}
}
}
func (w *Wrapper) updateSimpleVolView() (err error) {
var view *proto.SimpleVolView
if view, err = w.mc.AdminAPI().GetVolumeSimpleInfo(w.volName); err != nil {
log.LogWarnf("updateSimpleVolView: get volume simple info fail: volume(%v) err(%v)", w.volName, err)
return
}
if w.followerRead != view.FollowerRead && !w.followerReadClientCfg {
log.LogInfof("updateSimpleVolView: update followerRead from old(%v) to new(%v)",
w.followerRead, view.FollowerRead)
w.followerRead = view.FollowerRead
}
if w.dpSelectorName != view.DpSelectorName || w.dpSelectorParm != view.DpSelectorParm {
log.LogInfof("updateSimpleVolView: update dpSelector from old(%v %v) to new(%v %v)",
w.dpSelectorName, w.dpSelectorParm, view.DpSelectorName, view.DpSelectorParm)
w.Lock()
w.dpSelectorName = view.DpSelectorName
w.dpSelectorParm = view.DpSelectorParm
w.dpSelectorChanged = true
w.Unlock()
}
return nil
}
func (w *Wrapper) updateDataPartitionByRsp(isInit bool, DataPartitions []*proto.DataPartitionResponse) (err error) {
var convert = func(response *proto.DataPartitionResponse) *DataPartition {
return &DataPartition{
DataPartitionResponse: *response,
ClientWrapper: w,
}
}
rwPartitionGroups := make([]*DataPartition, 0)
for index, partition := range DataPartitions {
if partition == nil {
log.LogErrorf("action[updateDataPartitionByRsp] index [%v] is nil", index)
continue
}
dp := convert(partition)
if w.followerRead && w.nearRead {
dp.NearHosts = w.sortHostsByDistance(dp.Hosts)
}
log.LogInfof("updateDataPartition: dp(%v)", dp)
w.replaceOrInsertPartition(dp)
if dp.Status == proto.ReadWrite {
dp.MetricsRefresh()
rwPartitionGroups = append(rwPartitionGroups, dp)
}
}
// isInit used to identify whether this call is caused by mount action
if isInit || (len(rwPartitionGroups) >= MinWriteAbleDataPartitionCnt) {
w.refreshDpSelector(rwPartitionGroups)
} else {
err = errors.New("updateDataPartition: no writable data partition")
}
log.LogInfof("updateDataPartition: finish")
return err
}
func (w *Wrapper) updateDataPartition(isInit bool) (err error) {
var dpv *proto.DataPartitionsView
if dpv, err = w.mc.ClientAPI().GetDataPartitions(w.volName); err != nil {
log.LogErrorf("updateDataPartition: get data partitions fail: volume(%v) err(%v)", w.volName, err)
return
}
log.LogInfof("updateDataPartition: get data partitions: volume(%v) partitions(%v)", w.volName, len(dpv.DataPartitions))
return w.updateDataPartitionByRsp(isInit, dpv.DataPartitions)
}
// getDataPartition will call master to get data partition info which not include in cache updated by
// updateDataPartition which may not take effect if nginx be placed for reduce the pressure of master
func (w *Wrapper) getDataPartition(isInit bool, dpId uint64) (err error) {
var dpInfo *proto.DataPartitionInfo
if dpInfo, err = w.mc.AdminAPI().GetDataPartition(w.volName, dpId); err != nil {
log.LogErrorf("getDataPartition: get data partitions fail: volume(%v) err(%v)", w.volName, err)
return
}
log.LogInfof("getDataPartition: get data partitions: volume(%v)", w.volName)
var leaderAddr string
for _, replica := range dpInfo.Replicas {
if replica.IsLeader {
leaderAddr = replica.Addr
}
}
dpr := new(proto.DataPartitionResponse)
dpr.PartitionID = dpId
dpr.Status = dpInfo.Status
dpr.ReplicaNum = dpInfo.ReplicaNum
dpr.Hosts = make([]string, len(dpInfo.Hosts))
copy(dpr.Hosts, dpInfo.Hosts)
dpr.LeaderAddr = leaderAddr
dpr.IsRecover = dpInfo.IsRecover
DataPartitions := make([]*proto.DataPartitionResponse, 1)
DataPartitions = append(DataPartitions, dpr)
return w.updateDataPartitionByRsp(isInit, DataPartitions)
}
func (w *Wrapper) replaceOrInsertPartition(dp *DataPartition) {
var (
oldstatus int8
)
w.Lock()
old, ok := w.partitions[dp.PartitionID]
if ok {
oldstatus = old.Status
old.Status = dp.Status
old.ReplicaNum = dp.ReplicaNum
old.Hosts = dp.Hosts
old.NearHosts = dp.Hosts
dp.Metrics = old.Metrics
} else {
dp.Metrics = NewDataPartitionMetrics()
w.partitions[dp.PartitionID] = dp
}
w.Unlock()
if ok && oldstatus != dp.Status {
log.LogInfof("partition: status change (%v) -> (%v)", old, dp)
}
}
// GetDataPartition returns the data partition based on the given partition ID.
func (w *Wrapper) GetDataPartition(partitionID uint64) (*DataPartition, error) {
w.RLock()
defer w.RUnlock()
dp, ok := w.partitions[partitionID]
if !ok {
err := w.getDataPartition(false, partitionID)
if err == nil {
dp, ok = w.partitions[partitionID]
if !ok {
return nil, fmt.Errorf("partition[%v] not exsit", partitionID)
}
return dp, nil
}
return nil, fmt.Errorf("partition[%v] not exsit", partitionID)
}
return dp, nil
}
// WarningMsg returns the warning message that contains the cluster name.
func (w *Wrapper) WarningMsg() string {
return fmt.Sprintf("%s_client_warning", w.clusterName)
}
func (w *Wrapper) updateDataNodeStatus() (err error) {
var cv *proto.ClusterView
cv, err = w.mc.AdminAPI().GetCluster()
if err != nil {
log.LogErrorf("updateDataNodeStatus: get cluster fail: err(%v)", err)
return
}
newHostsStatus := make(map[string]bool)
for _, node := range cv.DataNodes {
newHostsStatus[node.Addr] = node.Status
}
log.LogInfof("updateDataNodeStatus: update %d hosts status", len(newHostsStatus))
w.HostsStatus = newHostsStatus
return
}
func (w *Wrapper) SetNearRead(nearRead bool) {
w.nearRead = nearRead
log.LogInfof("SetNearRead: set nearRead to %v", w.nearRead)
}
func (w *Wrapper) NearRead() bool {
return w.nearRead
}
// Sort hosts by distance form local
func (w *Wrapper) sortHostsByDistance(srcHosts []string) []string {
hosts := make([]string, len(srcHosts))
copy(hosts, srcHosts)
for i := 0; i < len(hosts); i++ {
for j := i + 1; j < len(hosts); j++ {
if distanceFromLocal(hosts[i]) > distanceFromLocal(hosts[j]) {
hosts[i], hosts[j] = hosts[j], hosts[i]
}
}
}
return hosts
}
func distanceFromLocal(b string) int {
remote := strings.Split(b, ":")[0]
return iputil.GetDistance(net.ParseIP(LocalIP), net.ParseIP(remote))
}