cluster.go 10.6 KB
Newer Older
S
sunby 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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.
11
package datacoord
S
sunby 已提交
12 13

import (
S
sunby 已提交
14
	"fmt"
S
sunby 已提交
15 16
	"sync"

X
Xiangyu Wang 已提交
17 18 19
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/proto/commonpb"
	"github.com/milvus-io/milvus/internal/proto/datapb"
20
	"github.com/milvus-io/milvus/internal/util/retry"
21 22
	"go.uber.org/zap"
	"golang.org/x/net/context"
S
sunby 已提交
23 24
)

25 26 27 28 29
type cluster struct {
	mu             sync.RWMutex
	ctx            context.Context
	dataManager    *clusterNodeManager
	sessionManager sessionManager
30
	posProvider    positionProvider
31 32 33 34

	startupPolicy    clusterStartupPolicy
	registerPolicy   dataNodeRegisterPolicy
	unregisterPolicy dataNodeUnregisterPolicy
S
sunby 已提交
35
	assignPolicy     channelAssignPolicy
N
neza2017 已提交
36
}
37 38 39

type clusterOption struct {
	apply func(c *cluster)
N
neza2017 已提交
40
}
S
sunby 已提交
41

42 43 44 45
func withStartupPolicy(p clusterStartupPolicy) clusterOption {
	return clusterOption{
		apply: func(c *cluster) { c.startupPolicy = p },
	}
S
sunby 已提交
46 47
}

48 49 50
func withRegisterPolicy(p dataNodeRegisterPolicy) clusterOption {
	return clusterOption{
		apply: func(c *cluster) { c.registerPolicy = p },
S
sunby 已提交
51 52 53
	}
}

54 55 56
func withUnregistorPolicy(p dataNodeUnregisterPolicy) clusterOption {
	return clusterOption{
		apply: func(c *cluster) { c.unregisterPolicy = p },
S
sunby 已提交
57 58 59
	}
}

60 61
func withAssignPolicy(p channelAssignPolicy) clusterOption {
	return clusterOption{
S
sunby 已提交
62
		apply: func(c *cluster) { c.assignPolicy = p },
S
sunby 已提交
63 64 65
	}
}

66
func defaultStartupPolicy() clusterStartupPolicy {
S
sunby 已提交
67
	return newWatchRestartsStartupPolicy()
S
sunby 已提交
68 69
}

70
func defaultRegisterPolicy() dataNodeRegisterPolicy {
71
	return newAssiggBufferRegisterPolicy()
72 73 74
}

func defaultUnregisterPolicy() dataNodeUnregisterPolicy {
C
congqixia 已提交
75
	return randomAssignRegisterFunc
76 77 78
}

func defaultAssignPolicy() channelAssignPolicy {
S
sunby 已提交
79
	return newBalancedAssignPolicy()
80 81
}

S
sunby 已提交
82 83 84
func newCluster(ctx context.Context, dataManager *clusterNodeManager,
	sessionManager sessionManager, posProvider positionProvider,
	opts ...clusterOption) *cluster {
85 86 87 88
	c := &cluster{
		ctx:              ctx,
		sessionManager:   sessionManager,
		dataManager:      dataManager,
89
		posProvider:      posProvider,
90 91 92
		startupPolicy:    defaultStartupPolicy(),
		registerPolicy:   defaultRegisterPolicy(),
		unregisterPolicy: defaultUnregisterPolicy(),
S
sunby 已提交
93
		assignPolicy:     defaultAssignPolicy(),
S
sunby 已提交
94
	}
95 96
	for _, opt := range opts {
		opt.apply(c)
S
sunby 已提交
97
	}
98 99 100 101 102 103

	return c
}

func (c *cluster) startup(dataNodes []*datapb.DataNodeInfo) error {
	deltaChange := c.dataManager.updateCluster(dataNodes)
104 105
	nodes, chanBuffer := c.dataManager.getDataNodes(false)
	var rets []*datapb.DataNodeInfo
106
	var err error
107 108
	rets, chanBuffer = c.startupPolicy.apply(nodes, deltaChange, chanBuffer)
	c.dataManager.updateDataNodes(rets, chanBuffer)
109 110 111 112 113
	rets, err = c.watch(rets)
	if err != nil {
		log.Warn("Failed to watch all the status change", zap.Error(err))
		//does not trigger new another refresh, pending evt will do
	}
114
	c.dataManager.updateDataNodes(rets, chanBuffer)
115 116 117
	return nil
}

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
// refresh rough refresh datanode status after event received
func (c *cluster) refresh(dataNodes []*datapb.DataNodeInfo) error {
	deltaChange := c.dataManager.updateCluster(dataNodes)
	nodes, chanBuffer := c.dataManager.getDataNodes(false)
	var rets []*datapb.DataNodeInfo
	var err error
	rets, chanBuffer = c.startupPolicy.apply(nodes, deltaChange, chanBuffer)
	c.dataManager.updateDataNodes(rets, chanBuffer)
	rets, err = c.watch(rets)
	if err != nil {
		log.Warn("Failed to watch all the status change", zap.Error(err))
		//does not trigger new another refresh, pending evt will do
	}
	c.dataManager.updateDataNodes(rets, chanBuffer) // even if some watch failed, status should sync into etcd
	return err
}

// paraRun parallel run, with max Parallel limit
func parraRun(works []func(), maxRunner int) {
	wg := sync.WaitGroup{}
	ch := make(chan func())
	wg.Add(len(works))

	for i := 0; i < maxRunner; i++ {
		go func() {
			work, ok := <-ch
			if !ok {
				return
			}
			work()
			wg.Done()
		}()
	}
	for _, work := range works {
		ch <- work
	}
	wg.Wait()
	close(ch)
}

func (c *cluster) watch(nodes []*datapb.DataNodeInfo) ([]*datapb.DataNodeInfo, error) {
	works := make([]func(), 0, len(nodes))
	mut := sync.Mutex{}
	errs := make([]error, 0, len(nodes))
162
	for _, n := range nodes {
163 164 165 166 167 168 169 170 171 172 173 174 175 176
		works = append(works, func() {
			logMsg := fmt.Sprintf("Begin to watch channels for node %s:", n.Address)
			uncompletes := make([]vchannel, 0, len(n.Channels))
			for _, ch := range n.Channels {
				if ch.State == datapb.ChannelWatchState_Uncomplete {
					if len(uncompletes) == 0 {
						logMsg += ch.Name
					} else {
						logMsg += "," + ch.Name
					}
					uncompletes = append(uncompletes, vchannel{
						CollectionID: ch.CollectionID,
						DmlChannel:   ch.Name,
					})
S
sunby 已提交
177
				}
178
			}
S
sunby 已提交
179

180 181 182 183
			if len(uncompletes) == 0 {
				return // all set, just return
			}
			log.Debug(logMsg)
S
sunby 已提交
184

185 186 187 188 189 190 191
			vchanInfos, err := c.posProvider.GetVChanPositions(uncompletes, true)
			if err != nil {
				log.Warn("get vchannel position failed", zap.Error(err))
				mut.Lock()
				errs = append(errs, err)
				mut.Unlock()
				return
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
			cli, err := c.sessionManager.getOrCreateSession(n.Address) // this might take time if address went offline
			if err != nil {
				log.Warn("get session failed", zap.String("addr", n.Address), zap.Error(err))
				mut.Lock()
				errs = append(errs, err)
				mut.Unlock()
				return
			}
			req := &datapb.WatchDmChannelsRequest{
				Base: &commonpb.MsgBase{
					SourceID: Params.NodeID,
				},
				Vchannels: vchanInfos,
			}
			resp, err := cli.WatchDmChannels(c.ctx, req)
			if err != nil {
				log.Warn("watch dm channel failed", zap.String("addr", n.Address), zap.Error(err))
				mut.Lock()
				errs = append(errs, err)
				mut.Unlock()
			}
			if resp.ErrorCode != commonpb.ErrorCode_Success {
				log.Warn("watch channels failed", zap.String("address", n.Address), zap.Error(err))
				mut.Lock()
				errs = append(errs, fmt.Errorf("watch fail with stat %v, msg:%s", resp.ErrorCode, resp.Reason))
				mut.Unlock()
				return
			}
			for _, ch := range n.Channels {
				if ch.State == datapb.ChannelWatchState_Uncomplete {
					ch.State = datapb.ChannelWatchState_Complete
				}
			}
		})
S
sunby 已提交
227
	}
228 229
	parraRun(works, 3)
	return nodes, retry.ErrorList(errs)
S
sunby 已提交
230 231
}

232 233 234 235
func (c *cluster) register(n *datapb.DataNodeInfo) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.dataManager.register(n)
236 237
	cNodes, chanBuffer := c.dataManager.getDataNodes(true)
	var rets []*datapb.DataNodeInfo
238
	var err error
239
	log.Debug("before register policy applied", zap.Any("n.Channels", n.Channels), zap.Any("buffer", chanBuffer))
240
	rets, chanBuffer = c.registerPolicy.apply(cNodes, n, chanBuffer)
241
	log.Debug("after register policy applied", zap.Any("ret", rets), zap.Any("buffer", chanBuffer))
242
	c.dataManager.updateDataNodes(rets, chanBuffer)
243 244 245 246 247
	rets, err = c.watch(rets)
	if err != nil {
		log.Warn("Failed to watch all the status change", zap.Error(err))
		//does not trigger new another refresh, pending evt will do
	}
248
	c.dataManager.updateDataNodes(rets, chanBuffer)
249 250 251 252 253
}

func (c *cluster) unregister(n *datapb.DataNodeInfo) {
	c.mu.Lock()
	defer c.mu.Unlock()
254

S
sunby 已提交
255
	c.sessionManager.releaseSession(n.Address)
256 257 258 259
	oldNode := c.dataManager.unregister(n)
	if oldNode != nil {
		n = oldNode
	}
260
	cNodes, chanBuffer := c.dataManager.getDataNodes(true)
261
	log.Debug("before unregister policy applied", zap.Any("n.Channels", n.Channels), zap.Any("buffer", chanBuffer))
262
	var rets []*datapb.DataNodeInfo
263
	var err error
264 265 266 267 268 269 270 271
	if len(cNodes) == 0 {
		for _, chStat := range n.Channels {
			chStat.State = datapb.ChannelWatchState_Uncomplete
			chanBuffer = append(chanBuffer, chStat)
		}
	} else {
		rets = c.unregisterPolicy.apply(cNodes, n)
	}
272
	log.Debug("after register policy applied", zap.Any("ret", rets), zap.Any("buffer", chanBuffer))
273
	c.dataManager.updateDataNodes(rets, chanBuffer)
274 275 276 277 278
	rets, err = c.watch(rets)
	if err != nil {
		log.Warn("Failed to watch all the status change", zap.Error(err))
		//does not trigger new another refresh, pending evt will do
	}
279
	c.dataManager.updateDataNodes(rets, chanBuffer)
280 281
}

282
func (c *cluster) watchIfNeeded(channel string, collectionID UniqueID) {
283 284
	c.mu.Lock()
	defer c.mu.Unlock()
285 286
	cNodes, chanBuffer := c.dataManager.getDataNodes(true)
	var rets []*datapb.DataNodeInfo
287
	var err error
288 289 290 291 292 293 294 295 296 297
	if len(cNodes) == 0 { // no nodes to assign, put into buffer
		chanBuffer = append(chanBuffer, &datapb.ChannelStatus{
			Name:         channel,
			CollectionID: collectionID,
			State:        datapb.ChannelWatchState_Uncomplete,
		})
	} else {
		rets = c.assignPolicy.apply(cNodes, channel, collectionID)
	}
	c.dataManager.updateDataNodes(rets, chanBuffer)
298 299 300 301 302
	rets, err = c.watch(rets)
	if err != nil {
		log.Warn("Failed to watch all the status change", zap.Error(err))
		//does not trigger new another refresh, pending evt will do
	}
303
	c.dataManager.updateDataNodes(rets, chanBuffer)
304 305 306 307 308 309 310 311 312 313 314
}

func (c *cluster) flush(segments []*datapb.SegmentInfo) {
	c.mu.Lock()
	defer c.mu.Unlock()

	m := make(map[string]map[UniqueID][]UniqueID) // channel-> map[collectionID]segmentIDs

	for _, seg := range segments {
		if _, ok := m[seg.InsertChannel]; !ok {
			m[seg.InsertChannel] = make(map[UniqueID][]UniqueID)
S
sunby 已提交
315
		}
316 317

		m[seg.InsertChannel][seg.CollectionID] = append(m[seg.InsertChannel][seg.CollectionID], seg.ID)
S
sunby 已提交
318 319
	}

320
	dataNodes, _ := c.dataManager.getDataNodes(true)
321 322 323 324 325

	channel2Node := make(map[string]string)
	for _, node := range dataNodes {
		for _, chstatus := range node.Channels {
			channel2Node[chstatus.Name] = node.Address
S
sunby 已提交
326 327
		}
	}
S
sunby 已提交
328

329 330 331 332 333 334 335 336
	for ch, coll2seg := range m {
		node, ok := channel2Node[ch]
		if !ok {
			continue
		}
		cli, err := c.sessionManager.getOrCreateSession(node)
		if err != nil {
			log.Warn("get session failed", zap.String("addr", node), zap.Error(err))
S
sunby 已提交
337 338
			continue
		}
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
		for coll, segs := range coll2seg {
			req := &datapb.FlushSegmentsRequest{
				Base: &commonpb.MsgBase{
					MsgType:  commonpb.MsgType_Flush,
					SourceID: Params.NodeID,
				},
				CollectionID: coll,
				SegmentIDs:   segs,
			}
			resp, err := cli.FlushSegments(c.ctx, req)
			if err != nil {
				log.Warn("flush segment failed", zap.String("addr", node), zap.Error(err))
				continue
			}
			if resp.ErrorCode != commonpb.ErrorCode_Success {
				log.Warn("flush segment failed", zap.String("dataNode", node), zap.Error(err))
				continue
			}
			log.Debug("flush segments succeed", zap.Any("segmentIDs", segs))
		}
S
sunby 已提交
359 360
	}
}
S
sunby 已提交
361

362 363 364 365
func (c *cluster) releaseSessions() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.sessionManager.release()
S
sunby 已提交
366
}