server.go 17.8 KB
Newer Older
Y
yah01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Licensed to the LF AI & Data foundation 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.

B
Bingyi Sun 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29
package querycoordv2

import (
	"context"
	"errors"
	"fmt"
	"os"
	"sort"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

Y
yah01 已提交
30
	"github.com/milvus-io/milvus/internal/metrics"
31 32
	"github.com/milvus-io/milvus/internal/util/timerecord"

S
SimFG 已提交
33 34
	"github.com/milvus-io/milvus-proto/go-api/commonpb"
	"github.com/milvus-io/milvus-proto/go-api/milvuspb"
B
Bingyi Sun 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	"github.com/milvus-io/milvus/internal/allocator"
	"github.com/milvus-io/milvus/internal/common"
	"github.com/milvus-io/milvus/internal/kv"
	etcdkv "github.com/milvus-io/milvus/internal/kv/etcd"
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/querycoordv2/balance"
	"github.com/milvus-io/milvus/internal/querycoordv2/checkers"
	"github.com/milvus-io/milvus/internal/querycoordv2/dist"
	"github.com/milvus-io/milvus/internal/querycoordv2/job"
	"github.com/milvus-io/milvus/internal/querycoordv2/meta"
	"github.com/milvus-io/milvus/internal/querycoordv2/observers"
	"github.com/milvus-io/milvus/internal/querycoordv2/params"
	"github.com/milvus-io/milvus/internal/querycoordv2/session"
	"github.com/milvus-io/milvus/internal/querycoordv2/task"
	"github.com/milvus-io/milvus/internal/types"
	"github.com/milvus-io/milvus/internal/util/metricsinfo"
	"github.com/milvus-io/milvus/internal/util/sessionutil"
	"github.com/milvus-io/milvus/internal/util/tsoutil"
	"github.com/milvus-io/milvus/internal/util/typeutil"
W
wei liu 已提交
54 55 56
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.uber.org/zap"
	"golang.org/x/sync/errgroup"
B
Bingyi Sun 已提交
57 58 59 60
)

var (
	// Only for re-export
E
Enwei Jiao 已提交
61
	Params = params.Params
B
Bingyi Sun 已提交
62 63 64 65 66 67 68 69
)

type Server struct {
	ctx                 context.Context
	cancel              context.CancelFunc
	wg                  sync.WaitGroup
	status              atomic.Value
	etcdCli             *clientv3.Client
E
Enwei Jiao 已提交
70
	address             string
B
Bingyi Sun 已提交
71 72 73 74 75 76
	session             *sessionutil.Session
	kv                  kv.MetaKv
	idAllocator         func() (int64, error)
	metricsCacheManager *metricsinfo.MetricsCacheManager

	// Coordinators
C
cai.zhang 已提交
77 78
	dataCoord types.DataCoord
	rootCoord types.RootCoord
B
Bingyi Sun 已提交
79 80 81 82 83 84 85 86 87

	// Meta
	store     meta.Store
	meta      *meta.Meta
	dist      *meta.DistributionManager
	targetMgr *meta.TargetManager
	broker    meta.Broker

	// Session
W
wayblink 已提交
88 89 90
	cluster          session.Cluster
	nodeMgr          *session.NodeManager
	queryNodeCreator session.QueryNodeCreator
B
Bingyi Sun 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104

	// Schedulers
	jobScheduler  *job.Scheduler
	taskScheduler task.Scheduler

	// HeartBeat
	distController *dist.Controller

	// Checkers
	checkerController *checkers.CheckerController

	// Observers
	collectionObserver *observers.CollectionObserver
	leaderObserver     *observers.LeaderObserver
W
wei liu 已提交
105
	targetObserver     *observers.TargetObserver
B
Bingyi Sun 已提交
106 107

	balancer balance.Balance
108 109 110 111

	// Active-standby
	enableActiveStandBy bool
	activateFunc        func()
B
Bingyi Sun 已提交
112 113
}

114
func NewQueryCoord(ctx context.Context) (*Server, error) {
B
Bingyi Sun 已提交
115 116
	ctx, cancel := context.WithCancel(ctx)
	server := &Server{
117 118
		ctx:    ctx,
		cancel: cancel,
B
Bingyi Sun 已提交
119
	}
120
	server.UpdateStateCode(commonpb.StateCode_Abnormal)
W
wayblink 已提交
121
	server.queryNodeCreator = session.DefaultQueryNodeCreator
B
Bingyi Sun 已提交
122 123 124 125 126
	return server, nil
}

func (s *Server) Register() error {
	s.session.Register()
127 128 129
	if s.enableActiveStandBy {
		s.session.ProcessActiveStandBy(s.activateFunc)
	}
B
Bingyi Sun 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
	go s.session.LivenessCheck(s.ctx, func() {
		log.Error("QueryCoord disconnected from etcd, process will exit", zap.Int64("serverID", s.session.ServerID))
		if err := s.Stop(); err != nil {
			log.Fatal("failed to stop server", zap.Error(err))
		}
		// manually send signal to starter goroutine
		if s.session.TriggerKill {
			if p, err := os.FindProcess(os.Getpid()); err == nil {
				p.Signal(syscall.SIGINT)
			}
		}
	})
	return nil
}

func (s *Server) Init() error {
	log.Info("QueryCoord start init",
147
		zap.String("meta-root-path", Params.EtcdCfg.MetaRootPath.GetValue()),
E
Enwei Jiao 已提交
148
		zap.String("address", s.address))
B
Bingyi Sun 已提交
149 150

	// Init QueryCoord session
151
	s.session = sessionutil.NewSession(s.ctx, Params.EtcdCfg.MetaRootPath.GetValue(), s.etcdCli)
B
Bingyi Sun 已提交
152 153 154
	if s.session == nil {
		return fmt.Errorf("failed to create session")
	}
E
Enwei Jiao 已提交
155
	s.session.Init(typeutil.QueryCoordRole, s.address, true, true)
156
	s.enableActiveStandBy = Params.QueryCoordCfg.EnableActiveStandby.GetAsBool()
157
	s.session.SetEnableActiveStandBy(s.enableActiveStandBy)
B
Bingyi Sun 已提交
158 159

	// Init KV
160
	etcdKV := etcdkv.NewEtcdKV(s.etcdCli, Params.EtcdCfg.MetaRootPath.GetValue())
B
Bingyi Sun 已提交
161
	s.kv = etcdKV
X
Xiaofan 已提交
162
	log.Info("query coordinator try to connect etcd success")
B
Bingyi Sun 已提交
163 164

	// Init ID allocator
165
	idAllocatorKV := tsoutil.NewTSOKVBase(s.etcdCli, Params.EtcdCfg.KvRootPath.GetValue(), "querycoord-id-allocator")
B
Bingyi Sun 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	idAllocator := allocator.NewGlobalIDAllocator("idTimestamp", idAllocatorKV)
	err := idAllocator.Initialize()
	if err != nil {
		log.Error("query coordinator id allocator initialize failed", zap.Error(err))
		return err
	}
	s.idAllocator = func() (int64, error) {
		return idAllocator.AllocOne()
	}

	// Init metrics cache manager
	s.metricsCacheManager = metricsinfo.NewMetricsCacheManager()

	// Init meta
	err = s.initMeta()
	if err != nil {
		return err
	}
	// Init session
X
Xiaofan 已提交
185
	log.Info("init session")
B
Bingyi Sun 已提交
186
	s.nodeMgr = session.NewNodeManager()
W
wayblink 已提交
187
	s.cluster = session.NewCluster(s.nodeMgr, s.queryNodeCreator)
B
Bingyi Sun 已提交
188 189

	// Init schedulers
X
Xiaofan 已提交
190
	log.Info("init schedulers")
B
Bingyi Sun 已提交
191 192 193 194 195 196 197 198 199 200 201 202
	s.jobScheduler = job.NewScheduler()
	s.taskScheduler = task.NewScheduler(
		s.ctx,
		s.meta,
		s.dist,
		s.targetMgr,
		s.broker,
		s.cluster,
		s.nodeMgr,
	)

	// Init heartbeat
X
Xiaofan 已提交
203
	log.Info("init dist controller")
B
Bingyi Sun 已提交
204 205 206 207 208 209 210 211 212
	s.distController = dist.NewDistController(
		s.cluster,
		s.nodeMgr,
		s.dist,
		s.targetMgr,
		s.taskScheduler,
	)

	// Init balancer
X
Xiaofan 已提交
213
	log.Info("init balancer")
B
Bingyi Sun 已提交
214 215 216 217 218
	s.balancer = balance.NewRowCountBasedBalancer(
		s.taskScheduler,
		s.nodeMgr,
		s.dist,
		s.meta,
219
		s.targetMgr,
B
Bingyi Sun 已提交
220 221 222
	)

	// Init checker controller
X
Xiaofan 已提交
223
	log.Info("init checker controller")
B
Bingyi Sun 已提交
224 225 226 227 228 229 230 231 232 233 234
	s.checkerController = checkers.NewCheckerController(
		s.meta,
		s.dist,
		s.targetMgr,
		s.balancer,
		s.taskScheduler,
	)

	// Init observers
	s.initObserver()

235 236 237
	// Init load status cache
	meta.GlobalFailedLoadCache = meta.NewFailedLoadCache()

B
Bingyi Sun 已提交
238 239 240 241 242
	log.Info("QueryCoord init success")
	return err
}

func (s *Server) initMeta() error {
243 244
	record := timerecord.NewTimeRecorder("querycoord")

X
Xiaofan 已提交
245
	log.Info("init meta")
B
Bingyi Sun 已提交
246 247 248
	s.store = meta.NewMetaStore(s.kv)
	s.meta = meta.NewMeta(s.idAllocator, s.store)

X
Xiaofan 已提交
249
	log.Info("recover meta...")
B
Bingyi Sun 已提交
250 251 252 253 254
	err := s.meta.CollectionManager.Recover()
	if err != nil {
		log.Error("failed to recover collections")
		return err
	}
255 256 257
	collections := s.meta.GetAll()
	log.Info("recovering collections...", zap.Int64s("collections", collections))
	metrics.QueryCoordNumCollections.WithLabelValues().Set(float64(len(collections)))
Y
yah01 已提交
258

259
	err = s.meta.ReplicaManager.Recover(collections)
B
Bingyi Sun 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273
	if err != nil {
		log.Error("failed to recover replicas")
		return err
	}

	s.dist = &meta.DistributionManager{
		SegmentDistManager: meta.NewSegmentDistManager(),
		ChannelDistManager: meta.NewChannelDistManager(),
		LeaderViewManager:  meta.NewLeaderViewManager(),
	}
	s.broker = meta.NewCoordinatorBroker(
		s.dataCoord,
		s.rootCoord,
	)
W
wei liu 已提交
274 275
	s.targetMgr = meta.NewTargetManager(s.broker, s.meta)

276
	record.Record("Server initMeta")
B
Bingyi Sun 已提交
277 278 279 280
	return nil
}

func (s *Server) initObserver() {
X
Xiaofan 已提交
281
	log.Info("init observers")
B
Bingyi Sun 已提交
282 283 284 285 286 287
	s.leaderObserver = observers.NewLeaderObserver(
		s.dist,
		s.meta,
		s.targetMgr,
		s.cluster,
	)
W
wei liu 已提交
288
	s.targetObserver = observers.NewTargetObserver(
B
Bingyi Sun 已提交
289 290
		s.meta,
		s.targetMgr,
W
wei liu 已提交
291
		s.dist,
292
		s.broker,
B
Bingyi Sun 已提交
293
	)
294 295 296 297 298 299
	s.collectionObserver = observers.NewCollectionObserver(
		s.dist,
		s.meta,
		s.targetMgr,
		s.targetObserver,
	)
B
Bingyi Sun 已提交
300 301
}

J
Jiquan Long 已提交
302 303 304
func (s *Server) afterStart() {
}

B
Bingyi Sun 已提交
305 306 307 308 309 310 311 312
func (s *Server) Start() error {
	log.Info("start watcher...")
	sessions, revision, err := s.session.GetSessions(typeutil.QueryNodeRole)
	if err != nil {
		return err
	}
	for _, node := range sessions {
		s.nodeMgr.Add(session.NewNodeInfo(node.ServerID, node.Address))
313
		s.taskScheduler.AddExecutor(node.ServerID)
B
Bingyi Sun 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327
	}
	s.checkReplicas()
	for _, node := range sessions {
		s.handleNodeUp(node.ServerID)
	}
	s.wg.Add(1)
	go s.watchNodes(revision)

	log.Info("start recovering dist and target")
	err = s.recover()
	if err != nil {
		return err
	}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	if s.enableActiveStandBy {
		s.activateFunc = func() {
			log.Info("querycoord switch from standby to active, activating")
			s.startServerLoop()
			s.UpdateStateCode(commonpb.StateCode_Healthy)
		}
		s.UpdateStateCode(commonpb.StateCode_StandBy)
	} else {
		s.startServerLoop()
		s.UpdateStateCode(commonpb.StateCode_Healthy)
	}
	log.Info("QueryCoord started")

	s.afterStart()

	return nil
}

func (s *Server) startServerLoop() {
B
Bingyi Sun 已提交
347 348 349 350 351 352
	log.Info("start cluster...")
	s.cluster.Start(s.ctx)

	log.Info("start job scheduler...")
	s.jobScheduler.Start(s.ctx)

353 354 355
	log.Info("start task scheduler...")
	s.taskScheduler.Start(s.ctx)

B
Bingyi Sun 已提交
356 357 358 359 360 361
	log.Info("start checker controller...")
	s.checkerController.Start(s.ctx)

	log.Info("start observers...")
	s.collectionObserver.Start(s.ctx)
	s.leaderObserver.Start(s.ctx)
W
wei liu 已提交
362
	s.targetObserver.Start(s.ctx)
B
Bingyi Sun 已提交
363 364 365 366
}

func (s *Server) Stop() error {
	s.cancel()
B
Bingyi Sun 已提交
367 368 369
	if s.session != nil {
		s.session.Revoke(time.Second)
	}
B
Bingyi Sun 已提交
370

B
Bingyi Sun 已提交
371 372 373 374
	if s.session != nil {
		log.Info("stop cluster...")
		s.cluster.Stop()
	}
B
Bingyi Sun 已提交
375

B
Bingyi Sun 已提交
376 377 378 379
	if s.distController != nil {
		log.Info("stop dist controller...")
		s.distController.Stop()
	}
B
Bingyi Sun 已提交
380

B
Bingyi Sun 已提交
381 382 383 384
	if s.checkerController != nil {
		log.Info("stop checker controller...")
		s.checkerController.Stop()
	}
B
Bingyi Sun 已提交
385

B
Bingyi Sun 已提交
386 387 388 389
	if s.taskScheduler != nil {
		log.Info("stop task scheduler...")
		s.taskScheduler.Stop()
	}
390

B
Bingyi Sun 已提交
391 392 393 394
	if s.jobScheduler != nil {
		log.Info("stop job scheduler...")
		s.jobScheduler.Stop()
	}
B
Bingyi Sun 已提交
395 396

	log.Info("stop observers...")
B
Bingyi Sun 已提交
397 398 399 400 401 402
	if s.collectionObserver != nil {
		s.collectionObserver.Stop()
	}
	if s.leaderObserver != nil {
		s.leaderObserver.Stop()
	}
W
wei liu 已提交
403 404
	if s.targetObserver != nil {
		s.targetObserver.Stop()
B
Bingyi Sun 已提交
405
	}
B
Bingyi Sun 已提交
406 407

	s.wg.Wait()
B
Bingyi Sun 已提交
408
	log.Info("QueryCoord stop successfully")
B
Bingyi Sun 已提交
409 410 411 412
	return nil
}

// UpdateStateCode updates the status of the coord, including healthy, unhealthy
413
func (s *Server) UpdateStateCode(code commonpb.StateCode) {
B
Bingyi Sun 已提交
414 415 416
	s.status.Store(code)
}

417
func (s *Server) GetComponentStates(ctx context.Context) (*milvuspb.ComponentStates, error) {
B
Bingyi Sun 已提交
418 419 420 421
	nodeID := common.NotRegisteredID
	if s.session != nil && s.session.Registered() {
		nodeID = s.session.ServerID
	}
422
	serviceComponentInfo := &milvuspb.ComponentInfo{
B
Bingyi Sun 已提交
423 424
		// NodeID:    Params.QueryCoordID, // will race with QueryCoord.Register()
		NodeID:    nodeID,
425
		StateCode: s.status.Load().(commonpb.StateCode),
B
Bingyi Sun 已提交
426 427
	}

428
	return &milvuspb.ComponentStates{
B
Bingyi Sun 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		State: serviceComponentInfo,
		//SubcomponentStates: subComponentInfos,
	}, nil
}

func (s *Server) GetStatisticsChannel(ctx context.Context) (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}, nil
}

func (s *Server) GetTimeTickChannel(ctx context.Context) (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
452
		Value: Params.CommonCfg.QueryCoordTimeTick.GetValue(),
B
Bingyi Sun 已提交
453 454 455
	}, nil
}

E
Enwei Jiao 已提交
456 457 458 459
func (s *Server) SetAddress(address string) {
	s.address = address
}

B
Bingyi Sun 已提交
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
// SetEtcdClient sets etcd's client
func (s *Server) SetEtcdClient(etcdClient *clientv3.Client) {
	s.etcdCli = etcdClient
}

// SetRootCoord sets root coordinator's client
func (s *Server) SetRootCoord(rootCoord types.RootCoord) error {
	if rootCoord == nil {
		return errors.New("null RootCoord interface")
	}

	s.rootCoord = rootCoord
	return nil
}

// SetDataCoord sets data coordinator's client
func (s *Server) SetDataCoord(dataCoord types.DataCoord) error {
	if dataCoord == nil {
		return errors.New("null DataCoord interface")
	}

	s.dataCoord = dataCoord
	return nil
}

W
wayblink 已提交
485 486 487 488
func (s *Server) SetQueryNodeCreator(f func(ctx context.Context, addr string) (types.QueryNode, error)) {
	s.queryNodeCreator = f
}

B
Bingyi Sun 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
func (s *Server) recover() error {
	// Recover target managers
	group, ctx := errgroup.WithContext(s.ctx)
	for _, collection := range s.meta.GetAll() {
		collection := collection
		group.Go(func() error {
			return s.recoverCollectionTargets(ctx, collection)
		})
	}
	err := group.Wait()
	if err != nil {
		return err
	}

	// Recover dist
	s.distController.SyncAll(s.ctx)

	return nil
}

func (s *Server) recoverCollectionTargets(ctx context.Context, collection int64) error {
W
wei liu 已提交
510
	err := s.targetMgr.UpdateCollectionNextTarget(collection)
B
Bingyi Sun 已提交
511
	if err != nil {
512 513 514 515 516 517
		s.meta.CollectionManager.RemoveCollection(collection)
		s.meta.ReplicaManager.RemoveCollection(collection)
		log.Error("failed to recover collection due to update next target failed",
			zap.Int64("collectionID", collection),
			zap.Error(err),
		)
B
Bingyi Sun 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
	}
	return nil
}

func (s *Server) watchNodes(revision int64) {
	defer s.wg.Done()

	eventChan := s.session.WatchServices(typeutil.QueryNodeRole, revision+1, nil)
	for {
		select {
		case <-s.ctx.Done():
			log.Info("stop watching nodes, QueryCoord stopped")
			return

		case event, ok := <-eventChan:
			if !ok {
				// ErrCompacted is handled inside SessionWatcher
				log.Error("Session Watcher channel closed", zap.Int64("serverID", s.session.ServerID))
				go s.Stop()
				if s.session.TriggerKill {
					if p, err := os.FindProcess(os.Getpid()); err == nil {
						p.Signal(syscall.SIGINT)
					}
				}
				return
			}

			switch event.EventType {
			case sessionutil.SessionAddEvent:
				nodeID := event.Session.ServerID
				addr := event.Session.Address
				log.Info("add node to NodeManager",
					zap.Int64("nodeID", nodeID),
					zap.String("nodeAddr", addr),
				)
				s.nodeMgr.Add(session.NewNodeInfo(nodeID, addr))
				s.handleNodeUp(nodeID)
				s.metricsCacheManager.InvalidateSystemInfoMetrics()

557 558 559 560 561 562 563 564 565 566
			case sessionutil.SessionUpdateEvent:
				nodeID := event.Session.ServerID
				addr := event.Session.Address
				log.Info("stopping the node",
					zap.Int64("nodeID", nodeID),
					zap.String("nodeAddr", addr),
				)
				s.nodeMgr.Stopping(nodeID)
				s.checkerController.Check()

B
Bingyi Sun 已提交
567 568 569 570 571 572 573 574 575 576 577 578 579
			case sessionutil.SessionDelEvent:
				nodeID := event.Session.ServerID
				log.Info("a node down, remove it", zap.Int64("nodeID", nodeID))
				s.nodeMgr.Remove(nodeID)
				s.handleNodeDown(nodeID)
				s.metricsCacheManager.InvalidateSystemInfoMetrics()
			}
		}
	}
}

func (s *Server) handleNodeUp(node int64) {
	log := log.With(zap.Int64("nodeID", node))
580
	s.taskScheduler.AddExecutor(node)
B
Bingyi Sun 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
	s.distController.StartDistInstance(s.ctx, node)

	for _, collection := range s.meta.CollectionManager.GetAll() {
		log := log.With(zap.Int64("collectionID", collection))
		replica := s.meta.ReplicaManager.GetByCollectionAndNode(collection, node)
		if replica == nil {
			replicas := s.meta.ReplicaManager.GetByCollection(collection)
			sort.Slice(replicas, func(i, j int) bool {
				return replicas[i].Nodes.Len() < replicas[j].Nodes.Len()
			})
			replica := replicas[0]
			// TODO(yah01): this may fail, need a component to check whether a node is assigned
			err := s.meta.ReplicaManager.AddNode(replica.GetID(), node)
			if err != nil {
				log.Warn("failed to assign node to replicas",
					zap.Int64("replicaID", replica.GetID()),
					zap.Error(err),
				)
			}
			log.Info("assign node to replica",
				zap.Int64("replicaID", replica.GetID()))
		}
	}
}

func (s *Server) handleNodeDown(node int64) {
	log := log.With(zap.Int64("nodeID", node))
608
	s.taskScheduler.RemoveExecutor(node)
B
Bingyi Sun 已提交
609 610 611 612 613 614 615
	s.distController.Remove(node)

	// Refresh the targets, to avoid consuming messages too early from channel
	// FIXME(yah01): the leads to miss data, the segments flushed between the two check points
	// are missed, it will recover for a while.
	channels := s.dist.ChannelDistManager.GetByNode(node)
	for _, channel := range channels {
616
		_, err := s.targetObserver.UpdateNextTarget(channel.GetCollectionID())
B
Bingyi Sun 已提交
617
		if err != nil {
W
wei liu 已提交
618 619
			msg := "failed to update next targets for collection"
			log.Error(msg,
B
Bingyi Sun 已提交
620
				zap.Error(err))
W
wei liu 已提交
621
			continue
B
Bingyi Sun 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
		}
	}

	// Clear dist
	s.dist.LeaderViewManager.Update(node)
	s.dist.ChannelDistManager.Update(node)
	s.dist.SegmentDistManager.Update(node)

	// Clear meta
	for _, collection := range s.meta.CollectionManager.GetAll() {
		log := log.With(zap.Int64("collectionID", collection))
		replica := s.meta.ReplicaManager.GetByCollectionAndNode(collection, node)
		if replica == nil {
			continue
		}
		err := s.meta.ReplicaManager.RemoveNode(replica.GetID(), node)
		if err != nil {
			log.Warn("failed to remove node from collection's replicas",
				zap.Int64("replicaID", replica.GetID()),
				zap.Error(err),
			)
		}
		log.Info("remove node from replica",
			zap.Int64("replicaID", replica.GetID()))
	}

	// Clear tasks
	s.taskScheduler.RemoveByNode(node)
}

// checkReplicas checks whether replica contains offline node, and remove those nodes
func (s *Server) checkReplicas() {
	for _, collection := range s.meta.CollectionManager.GetAll() {
		log := log.With(zap.Int64("collectionID", collection))
		replicas := s.meta.ReplicaManager.GetByCollection(collection)
		for _, replica := range replicas {
			replica := replica.Clone()
			toRemove := make([]int64, 0)
			for node := range replica.Nodes {
				if s.nodeMgr.Get(node) == nil {
					toRemove = append(toRemove, node)
				}
			}

			if len(toRemove) > 0 {
Y
yah01 已提交
667 668 669 670
				log := log.With(
					zap.Int64("replicaID", replica.GetID()),
					zap.Int64s("offlineNodes", toRemove),
				)
X
Xiaofan 已提交
671
				log.Info("some nodes are offline, remove them from replica", zap.Any("toRemove", toRemove))
B
Bingyi Sun 已提交
672 673 674 675 676 677 678 679 680
				replica.RemoveNode(toRemove...)
				err := s.meta.ReplicaManager.Put(replica)
				if err != nil {
					log.Warn("failed to remove offline nodes from replica")
				}
			}
		}
	}
}