-
Notifications
You must be signed in to change notification settings - Fork 798
/
cluster_manager.go
369 lines (339 loc) · 12.4 KB
/
cluster_manager.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 cluster
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"sync"
"time"
"mosn.io/mosn/pkg/admin/store"
v2 "mosn.io/mosn/pkg/api/v2"
"mosn.io/mosn/pkg/log"
"mosn.io/mosn/pkg/network"
"mosn.io/mosn/pkg/types"
)
var errNilCluster = errors.New("cannot update nil cluster")
// refreshHostsConfig refresh the stored config for admin api
func refreshHostsConfig(c types.Cluster) {
// use new cluster snapshot to get new cluster config
name := c.Snapshot().ClusterInfo().Name()
hosts := c.Snapshot().HostSet().Hosts()
hostsConfig := make([]v2.Host, 0, len(hosts))
for _, h := range hosts {
hostsConfig = append(hostsConfig, h.Config())
}
store.SetHosts(name, hostsConfig)
if log.DefaultLogger.GetLogLevel() >= log.INFO {
log.DefaultLogger.Infof("[cluster] [primaryCluster] [UpdateHosts] cluster %s update hosts: %d", name, len(hosts))
}
if log.DefaultLogger.GetLogLevel() >= log.DEBUG {
log.DefaultLogger.Infof("[cluster] [primaryCluster] [UpdateHosts] cluster %s update hosts: %v", name, hosts)
}
}
// types.ClusterManager
type clusterManager struct {
clustersMap sync.Map
protocolConnPool sync.Map
mux sync.Mutex
}
type clusterManagerSingleton struct {
instanceMutex sync.Mutex
*clusterManager
}
func (singleton *clusterManagerSingleton) Destroy() {
clusterMangerInstance.instanceMutex.Lock()
defer clusterMangerInstance.instanceMutex.Unlock()
clusterMangerInstance.clusterManager = nil
}
var clusterMangerInstance = &clusterManagerSingleton{}
func NewClusterManagerSingleton(clusters []v2.Cluster, clusterMap map[string][]v2.Host) types.ClusterManager {
clusterMangerInstance.instanceMutex.Lock()
defer clusterMangerInstance.instanceMutex.Unlock()
if clusterMangerInstance.clusterManager != nil {
return clusterMangerInstance
}
clusterMangerInstance.clusterManager = &clusterManager{}
for k := range types.ConnPoolFactories {
clusterMangerInstance.protocolConnPool.Store(k, &sync.Map{})
}
//Add cluster to cm
for _, cluster := range clusters {
if err := clusterMangerInstance.AddOrUpdatePrimaryCluster(cluster); err != nil {
log.DefaultLogger.Errorf("[upstream] [cluster manager] NewClusterManager: AddOrUpdatePrimaryCluster failure, cluster name = %s, error: %v", cluster.Name, err)
}
}
// Add cluster host
for clusterName, hosts := range clusterMap {
if err := clusterMangerInstance.UpdateClusterHosts(clusterName, hosts); err != nil {
log.DefaultLogger.Errorf("[upstream] [cluster manager] NewClusterManager: UpdateClusterHosts failure, cluster name = %s, error: %v", clusterName, err)
}
}
return clusterMangerInstance
}
// AddOrUpdatePrimaryCluster will always create a new cluster without the hosts config
// if the same name cluster is already exists, we will keep the exists hosts, and use rcu to update it.
func (cm *clusterManager) AddOrUpdatePrimaryCluster(cluster v2.Cluster) error {
// new cluster
newCluster := NewCluster(cluster)
if newCluster == nil || reflect.ValueOf(newCluster).IsNil() {
log.DefaultLogger.Errorf("[cluster] [cluster manager] [AddOrUpdatePrimaryCluster] update cluster %s failed", cluster.Name)
return errNilCluster
}
// check update or new
clusterName := cluster.Name
// set config
store.SetClusterConfig(clusterName, cluster)
// add or update
ci, exists := cm.clustersMap.Load(clusterName)
if exists {
c := ci.(types.Cluster)
//FIXME: cluster info in hosts should be updated too
hosts := c.Snapshot().HostSet().Hosts()
// update hosts, refresh
newCluster.UpdateHosts(hosts)
refreshHostsConfig(c)
}
cm.clustersMap.Store(clusterName, newCluster)
log.DefaultLogger.Infof("[cluster] [cluster manager] [AddOrUpdatePrimaryCluster] cluster %s updated", clusterName)
return nil
}
// AddClusterHealthCheckCallbacks adds a health check callback function into cluster
func (cm *clusterManager) AddClusterHealthCheckCallbacks(name string, cb types.HealthCheckCb) error {
ci, ok := cm.clustersMap.Load(name)
if ok {
c := ci.(types.Cluster)
c.AddHealthCheckCallbacks(cb)
return nil
}
return fmt.Errorf("cluster %s is not exists", name)
}
func (cm *clusterManager) ClusterExist(clusterName string) bool {
_, ok := cm.clustersMap.Load(clusterName)
return ok
}
// RemovePrimaryCluster removes clusters from cluster manager
// If the cluster is more than one, all of them should be exists, or no one will be deleted
func (cm *clusterManager) RemovePrimaryCluster(clusterNames ...string) error {
// check all clutsers in cluster manager
for _, clusterName := range clusterNames {
if _, ok := cm.clustersMap.Load(clusterName); !ok {
log.DefaultLogger.Errorf("[upstream] [cluster manager] Remove Primary Cluster, cluster %s not exists", clusterName)
return fmt.Errorf("remove cluster failed, cluster %s is not exists", clusterName)
}
}
// delete all of them
for _, clusterName := range clusterNames {
cm.clustersMap.Delete(clusterName)
store.RemoveClusterConfig(clusterName)
if log.DefaultLogger.GetLogLevel() >= log.INFO {
log.DefaultLogger.Infof("[upstream] [cluster manager] Remove Primary Cluster, Cluster Name = %s", clusterName)
}
}
return nil
}
// UpdateClusterHosts update all hosts in the cluster
func (cm *clusterManager) UpdateClusterHosts(clusterName string, hostConfigs []v2.Host) error {
ci, ok := cm.clustersMap.Load(clusterName)
if !ok {
log.DefaultLogger.Errorf("[upstream] [cluster manager] UpdateClusterHosts cluster %s not found", clusterName)
return fmt.Errorf("cluster %s is not exists", clusterName)
}
c := ci.(types.Cluster)
snap := c.Snapshot()
hosts := make([]types.Host, 0, len(hostConfigs))
for _, hc := range hostConfigs {
hosts = append(hosts, NewSimpleHost(hc, snap.ClusterInfo()))
}
c.UpdateHosts(hosts)
refreshHostsConfig(c)
return nil
}
// AppendClusterHosts adds new hosts into cluster
func (cm *clusterManager) AppendClusterHosts(clusterName string, hostConfigs []v2.Host) error {
ci, ok := cm.clustersMap.Load(clusterName)
if !ok {
log.DefaultLogger.Errorf("[upstream] [cluster manager] AppendClusterHosts cluster %s not found", clusterName)
return fmt.Errorf("cluster %s is not exists", clusterName)
}
c := ci.(types.Cluster)
snap := c.Snapshot()
hosts := make([]types.Host, 0, len(hostConfigs))
for _, hc := range hostConfigs {
hosts = append(hosts, NewSimpleHost(hc, snap.ClusterInfo()))
}
hosts = append(hosts, snap.HostSet().Hosts()...)
c.UpdateHosts(hosts)
refreshHostsConfig(c)
return nil
}
// RemoveClusterHosts removes hosts from cluster by address string
func (cm *clusterManager) RemoveClusterHosts(clusterName string, addrs []string) error {
ci, ok := cm.clustersMap.Load(clusterName)
if !ok {
log.DefaultLogger.Errorf("[upstream] [cluster manager] RemoveClusterHosts cluster %s not found", clusterName)
return fmt.Errorf("cluster %s is not exists", clusterName)
}
c := ci.(types.Cluster)
snap := c.Snapshot()
hosts := snap.HostSet().Hosts()
newHosts := make([]types.Host, len(hosts))
copy(newHosts, hosts)
sortedHosts := types.SortedHosts(newHosts)
sort.Sort(sortedHosts)
for _, addr := range addrs {
i := sort.Search(sortedHosts.Len(), func(i int) bool {
return sortedHosts[i].AddressString() >= addr
})
// found it, delete it
if i < sortedHosts.Len() && sortedHosts[i].AddressString() == addr {
sortedHosts = append(sortedHosts[:i], sortedHosts[i+1:]...)
}
}
c.UpdateHosts(sortedHosts)
refreshHostsConfig(c)
return nil
}
// GetClusterSnapshot returns cluster snap
// do not needs PutClusterSnapshot any more
func (cm *clusterManager) GetClusterSnapshot(ctx context.Context, clusterName string) types.ClusterSnapshot {
ci, ok := cm.clustersMap.Load(clusterName)
if !ok {
return nil
}
return ci.(types.Cluster).Snapshot()
}
func (cm *clusterManager) PutClusterSnapshot(snap types.ClusterSnapshot) {
}
func (cm *clusterManager) TCPConnForCluster(lbCtx types.LoadBalancerContext, snapshot types.ClusterSnapshot) types.CreateConnectionData {
if snapshot == nil || reflect.ValueOf(snapshot).IsNil() {
return types.CreateConnectionData{}
}
host := snapshot.LoadBalancer().ChooseHost(lbCtx)
if host == nil {
return types.CreateConnectionData{}
}
return host.CreateConnection(context.Background())
}
func (cm *clusterManager) ConnPoolForCluster(balancerContext types.LoadBalancerContext, snapshot types.ClusterSnapshot, protocol types.Protocol) types.ConnectionPool {
if snapshot == nil || reflect.ValueOf(snapshot).IsNil() {
log.DefaultLogger.Errorf("[upstream] [cluster manager] %s ConnPool For Cluster is nil", protocol)
return nil
}
pool, err := cm.getActiveConnectionPool(balancerContext, snapshot, protocol)
if err != nil {
log.DefaultLogger.Errorf("[upstream] [cluster manager] ConnPoolForCluster Failed; %v", err)
}
return pool
}
const cycleTimes = 3
var (
errNilHostChoose = errors.New("cluster snapshot choose host is nil")
errUnknownProtocol = errors.New("protocol pool can not found protocol")
errNoHealthyHost = errors.New("no health hosts")
)
func (cm *clusterManager) getActiveConnectionPool(balancerContext types.LoadBalancerContext, clusterSnapshot types.ClusterSnapshot, protocol types.Protocol) (types.ConnectionPool, error) {
factory, ok := network.ConnNewPoolFactories[protocol]
if !ok {
return nil, fmt.Errorf("protocol %v is not registered is pool factory", protocol)
}
var pools [cycleTimes]types.ConnectionPool
try := clusterSnapshot.HostNum(balancerContext.MetadataMatchCriteria())
if try == 0 {
return nil, errNilHostChoose
}
if try > cycleTimes {
try = cycleTimes
}
for i := 0; i < try; i++ {
host := clusterSnapshot.LoadBalancer().ChooseHost(balancerContext)
if host == nil {
return nil, errNilHostChoose
}
addr := host.AddressString()
if log.DefaultLogger.GetLogLevel() >= log.DEBUG {
log.DefaultLogger.Debugf("[upstream] [cluster manager] clusterSnapshot.loadbalancer.ChooseHost result is %s, cluster name = %s", addr, clusterSnapshot.ClusterInfo().Name())
}
value, ok := cm.protocolConnPool.Load(protocol)
if !ok {
return nil, errUnknownProtocol
}
connectionPool := value.(*sync.Map)
// we cannot use sync.Map.LoadOrStore directly, becasue we do not want to new a connpool every time
loadOrStoreConnPool := func() (types.ConnectionPool, bool) {
// avoid locking if it is already exists
if connPool, ok := connectionPool.Load(addr); ok {
pool := connPool.(types.ConnectionPool)
return pool, true
}
cm.mux.Lock()
defer cm.mux.Unlock()
if connPool, ok := connectionPool.Load(addr); ok {
pool := connPool.(types.ConnectionPool)
return pool, true
}
pool := factory(host)
connectionPool.Store(addr, pool)
return pool, false
}
pool, loaded := loadOrStoreConnPool()
if loaded {
if pool.SupportTLS() != host.SupportTLS() {
if log.DefaultLogger.GetLogLevel() >= log.INFO {
log.DefaultLogger.Infof("[upstream] [cluster manager] %s tls state changed", addr)
}
func() {
// lock the load and delete
cm.mux.Lock()
defer cm.mux.Unlock()
// recheck whether the pool is changed
if connPool, ok := connectionPool.Load(addr); ok {
pool = connPool.(types.ConnectionPool)
if pool.SupportTLS() == host.SupportTLS() {
return
}
connectionPool.Delete(addr)
pool.Shutdown()
pool = factory(host)
connectionPool.Store(addr, pool)
}
}()
}
}
if pool.CheckAndInit(balancerContext.DownstreamContext()) {
return pool, nil
}
pools[i] = pool
}
// perhaps the first request, wait for tcp handshaking. total wait time is 1ms + 10ms + 100ms
waitTime := time.Millisecond
for t := 0; t < cycleTimes; t++ {
time.Sleep(waitTime)
for i := 0; i < try; i++ {
if pools[i] == nil {
continue
}
if pools[i].CheckAndInit(balancerContext.DownstreamContext()) {
return pools[i], nil
}
}
waitTime *= 10
}
return nil, errNoHealthyHost
}