server.go 13.9 KB
Newer Older
S
sunby 已提交
1 2
package dataservice

S
sunby 已提交
3 4 5 6
import (
	"context"
	"fmt"
	"log"
S
sunby 已提交
7
	"sync"
S
sunby 已提交
8 9 10 11 12

	"github.com/zilliztech/milvus-distributed/internal/msgstream"
	"github.com/zilliztech/milvus-distributed/internal/msgstream/pulsarms"

	"github.com/zilliztech/milvus-distributed/internal/distributed/masterservice"
S
sunby 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26

	"github.com/zilliztech/milvus-distributed/internal/proto/milvuspb"

	"github.com/zilliztech/milvus-distributed/internal/timesync"

	etcdkv "github.com/zilliztech/milvus-distributed/internal/kv/etcd"
	"go.etcd.io/etcd/clientv3"

	"github.com/zilliztech/milvus-distributed/internal/proto/commonpb"
	"github.com/zilliztech/milvus-distributed/internal/proto/datapb"
	"github.com/zilliztech/milvus-distributed/internal/proto/internalpb2"
	"github.com/zilliztech/milvus-distributed/internal/util/typeutil"
)

S
sunby 已提交
27 28
const role = "dataservice"

S
sunby 已提交
29 30 31 32 33 34 35 36 37
type DataService interface {
	typeutil.Service
	RegisterNode(req *datapb.RegisterNodeRequest) (*datapb.RegisterNodeResponse, error)
	Flush(req *datapb.FlushRequest) (*commonpb.Status, error)

	AssignSegmentID(req *datapb.AssignSegIDRequest) (*datapb.AssignSegIDResponse, error)
	ShowSegments(req *datapb.ShowSegmentRequest) (*datapb.ShowSegmentResponse, error)
	GetSegmentStates(req *datapb.SegmentStatesRequest) (*datapb.SegmentStatesResponse, error)
	GetInsertBinlogPaths(req *datapb.InsertBinlogPathRequest) (*datapb.InsertBinlogPathsResponse, error)
N
neza2017 已提交
38 39

	GetInsertChannels(req *datapb.InsertChannelRequest) (*internalpb2.StringList, error)
S
sunby 已提交
40 41 42
	GetCollectionStatistics(req *datapb.CollectionStatsRequest) (*datapb.CollectionStatsResponse, error)
	GetPartitionStatistics(req *datapb.PartitionStatsRequest) (*datapb.PartitionStatsResponse, error)
	GetComponentStates() (*internalpb2.ComponentStates, error)
N
neza2017 已提交
43 44
	GetTimeTickChannel() (*milvuspb.StringResponse, error)
	GetStatisticsChannel() (*milvuspb.StringResponse, error)
S
sunby 已提交
45 46 47
}

type (
S
sunby 已提交
48 49 50
	UniqueID  = typeutil.UniqueID
	Timestamp = typeutil.Timestamp
	Server    struct {
N
neza2017 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
		ctx              context.Context
		serverLoopCtx    context.Context
		serverLoopCancel context.CancelFunc
		serverLoopWg     sync.WaitGroup
		state            internalpb2.StateCode
		client           *etcdkv.EtcdKV
		meta             *meta
		segAllocator     segmentAllocator
		statsHandler     *statsHandler
		insertChannelMgr *insertChannelManager
		allocator        allocator
		cluster          *dataNodeCluster
		msgProducer      *timesync.MsgProducer
		registerFinishCh chan struct{}
		masterClient     *masterservice.GrpcClient
		ttMsgStream      msgstream.MsgStream
		ddChannelName    string
S
sunby 已提交
68 69 70
	}
)

S
sunby 已提交
71
func CreateServer(ctx context.Context, client *masterservice.GrpcClient) (*Server, error) {
S
sunby 已提交
72
	ch := make(chan struct{})
S
sunby 已提交
73 74 75 76
	return &Server{
		ctx:              ctx,
		state:            internalpb2.StateCode_INITIALIZING,
		insertChannelMgr: newInsertChannelManager(),
S
sunby 已提交
77 78
		registerFinishCh: ch,
		cluster:          newDataNodeCluster(ch),
S
sunby 已提交
79
		masterClient:     client,
S
sunby 已提交
80 81 82 83 84
	}, nil
}

func (s *Server) Init() error {
	Params.Init()
S
sunby 已提交
85 86 87 88 89
	return nil
}

func (s *Server) Start() error {
	s.allocator = newAllocatorImpl(s.masterClient)
S
sunby 已提交
90 91 92 93
	if err := s.initMeta(); err != nil {
		return err
	}
	s.statsHandler = newStatsHandler(s.meta)
S
sunby 已提交
94
	segAllocator, err := newSegmentAllocator(s.meta, s.allocator)
S
sunby 已提交
95 96 97 98
	if err != nil {
		return err
	}
	s.segAllocator = segAllocator
S
sunby 已提交
99
	s.waitDataNodeRegister()
S
sunby 已提交
100

S
sunby 已提交
101 102 103
	if err = s.loadMetaFromMaster(); err != nil {
		return err
	}
S
sunby 已提交
104 105 106
	if err = s.initMsgProducer(); err != nil {
		return err
	}
S
sunby 已提交
107 108

	s.startServerLoop()
S
sunby 已提交
109 110 111 112 113
	s.state = internalpb2.StateCode_HEALTHY
	log.Println("start success")
	return nil
}

S
sunby 已提交
114 115 116 117 118 119 120
func (s *Server) initMeta() error {
	etcdClient, err := clientv3.New(clientv3.Config{Endpoints: []string{Params.EtcdAddress}})
	if err != nil {
		return err
	}
	etcdKV := etcdkv.NewEtcdKV(etcdClient, Params.MetaRootPath)
	s.client = etcdKV
N
neza2017 已提交
121
	s.meta, err = newMeta(etcdKV, s.allocator)
S
sunby 已提交
122 123 124 125 126 127
	if err != nil {
		return err
	}
	return nil
}

S
sunby 已提交
128 129 130 131 132 133
func (s *Server) waitDataNodeRegister() {
	log.Println("waiting data node to register")
	<-s.registerFinishCh
	log.Println("all data nodes register")
}

S
sunby 已提交
134
func (s *Server) initMsgProducer() error {
N
neza2017 已提交
135
	s.ttMsgStream = pulsarms.NewPulsarTtMsgStream(s.ctx, 1024)
S
sunby 已提交
136 137 138 139
	s.ttMsgStream.Start()
	timeTickBarrier := timesync.NewHardTimeTickBarrier(s.ttMsgStream, s.cluster.GetNodeIDs())
	dataNodeTTWatcher := newDataNodeTimeTickWatcher(s.meta, s.segAllocator, s.cluster)
	producer, err := timesync.NewTimeSyncMsgProducer(timeTickBarrier, dataNodeTTWatcher)
S
sunby 已提交
140 141 142 143 144 145 146
	if err != nil {
		return err
	}
	s.msgProducer = producer
	s.msgProducer.Start(s.ctx)
	return nil
}
S
sunby 已提交
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

func (s *Server) startServerLoop() {
	s.serverLoopCtx, s.serverLoopCancel = context.WithCancel(s.ctx)
	s.serverLoopWg.Add(1)
	go s.startStatsChannel(s.serverLoopCtx)
}

func (s *Server) startStatsChannel(ctx context.Context) {
	defer s.serverLoopWg.Done()
	statsStream := pulsarms.NewPulsarMsgStream(ctx, 1024)
	statsStream.Start()
	defer statsStream.Close()
	for {
		select {
		case <-ctx.Done():
			return
		default:
		}
		msgPack := statsStream.Consume()
		for _, msg := range msgPack.Msgs {
			statistics := msg.(*msgstream.SegmentStatisticsMsg)
			for _, stat := range statistics.SegStats {
				if err := s.statsHandler.HandleSegmentStat(stat); err != nil {
					log.Println(err.Error())
					continue
				}
			}
		}
	}
}

S
sunby 已提交
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
func (s *Server) loadMetaFromMaster() error {
	log.Println("loading collection meta from master")
	collections, err := s.masterClient.ShowCollections(&milvuspb.ShowCollectionRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_kShowCollections,
			MsgID:     -1, // todo add msg id
			Timestamp: 0,  // todo
			SourceID:  -1, // todo
		},
		DbName: "",
	})
	if err != nil {
		return err
	}
	for _, collectionName := range collections.CollectionNames {
		collection, err := s.masterClient.DescribeCollection(&milvuspb.DescribeCollectionRequest{
			Base: &commonpb.MsgBase{
				MsgType:   commonpb.MsgType_kDescribeCollection,
				MsgID:     -1, // todo
				Timestamp: 0,  // todo
				SourceID:  -1, // todo
			},
			DbName:         "",
			CollectionName: collectionName,
		})
		if err != nil {
			log.Println(err.Error())
			continue
		}
		partitions, err := s.masterClient.ShowPartitions(&milvuspb.ShowPartitionRequest{
			Base: &commonpb.MsgBase{
				MsgType:   commonpb.MsgType_kShowPartitions,
				MsgID:     -1, // todo
				Timestamp: 0,  // todo
				SourceID:  -1, // todo
			},
			DbName:         "",
			CollectionName: collectionName,
			CollectionID:   collection.CollectionID,
		})
		if err != nil {
			log.Println(err.Error())
			continue
		}
		err = s.meta.AddCollection(&collectionInfo{
			ID:         collection.CollectionID,
			Schema:     collection.Schema,
S
sunby 已提交
225
			Partitions: partitions.PartitionIDs,
S
sunby 已提交
226 227 228 229 230 231 232 233
		})
		if err != nil {
			log.Println(err.Error())
			continue
		}
	}
	log.Println("load collection meta from master complete")
	return nil
S
sunby 已提交
234 235 236
}

func (s *Server) Stop() error {
S
sunby 已提交
237
	s.ttMsgStream.Close()
S
sunby 已提交
238
	s.msgProducer.Close()
S
sunby 已提交
239
	s.stopServerLoop()
S
sunby 已提交
240 241 242
	return nil
}

S
sunby 已提交
243 244 245 246 247
func (s *Server) stopServerLoop() {
	s.serverLoopCancel()
	s.serverLoopWg.Wait()
}

S
sunby 已提交
248
func (s *Server) GetComponentStates() (*internalpb2.ComponentStates, error) {
S
sunby 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	resp := &internalpb2.ComponentStates{
		State: &internalpb2.ComponentInfo{
			NodeID:    Params.NodeID,
			Role:      role,
			StateCode: s.state,
		},
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
		},
	}
	dataNodeStates, err := s.cluster.GetDataNodeStates()
	if err != nil {
		resp.Status.Reason = err.Error()
		return resp, nil
	}
	resp.SubcomponentStates = dataNodeStates
	resp.Status.ErrorCode = commonpb.ErrorCode_SUCCESS
	return resp, nil
S
sunby 已提交
267 268
}

N
neza2017 已提交
269 270 271 272 273 274 275
func (s *Server) GetTimeTickChannel() (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		Value: Params.TimeTickChannelName,
	}, nil
S
sunby 已提交
276 277
}

N
neza2017 已提交
278 279 280 281 282 283 284
func (s *Server) GetStatisticsChannel() (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		Value: Params.StatisticsChannelName,
	}, nil
S
sunby 已提交
285 286 287
}

func (s *Server) RegisterNode(req *datapb.RegisterNodeRequest) (*datapb.RegisterNodeResponse, error) {
S
sunby 已提交
288
	ret := &datapb.RegisterNodeResponse{
S
sunby 已提交
289
		Status: &commonpb.Status{
S
sunby 已提交
290
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
S
sunby 已提交
291
		},
S
sunby 已提交
292 293
	}
	s.cluster.Register(req.Address.Ip, req.Address.Port, req.Base.SourceID)
N
neza2017 已提交
294
	if len(s.ddChannelName) == 0 {
N
neza2017 已提交
295
		resp, err := s.masterClient.GetDdChannel()
S
sunby 已提交
296 297 298 299
		if err != nil {
			ret.Status.Reason = err.Error()
			return ret, err
		}
N
neza2017 已提交
300
		s.ddChannelName = resp
S
sunby 已提交
301 302 303 304 305 306 307 308
	}
	ret.Status.ErrorCode = commonpb.ErrorCode_SUCCESS
	ret.InitParams = &internalpb2.InitParams{
		NodeID: Params.NodeID,
		StartParams: []*commonpb.KeyValuePair{
			{Key: "DDChannelName", Value: s.ddChannelName},
			{Key: "SegmentStatisticsChannelName", Value: Params.StatisticsChannelName},
			{Key: "TimeTickChannelName", Value: Params.TimeTickChannelName},
N
neza2017 已提交
309
			{Key: "CompleteFlushChannelName", Value: Params.SegmentChannelName},
S
sunby 已提交
310 311 312
		},
	}
	return ret, nil
S
sunby 已提交
313 314 315
}

func (s *Server) Flush(req *datapb.FlushRequest) (*commonpb.Status, error) {
N
neza2017 已提交
316 317 318 319 320 321 322 323
	success, fails := s.segAllocator.SealAllSegments(req.CollectionID)
	log.Printf("sealing failed segments: %v", fails)
	if !success {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
			Reason:    fmt.Sprintf("flush failed, %d segment can not be sealed", len(fails)),
		}, nil
	}
S
sunby 已提交
324 325 326
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_SUCCESS,
	}, nil
S
sunby 已提交
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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
}

func (s *Server) AssignSegmentID(req *datapb.AssignSegIDRequest) (*datapb.AssignSegIDResponse, error) {
	resp := &datapb.AssignSegIDResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		SegIDAssignments: make([]*datapb.SegIDAssignment, 0),
	}
	for _, r := range req.SegIDRequests {
		result := &datapb.SegIDAssignment{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
			},
		}
		segmentID, retCount, expireTs, err := s.segAllocator.AllocSegment(r.CollectionID, r.PartitionID, r.ChannelName, int(r.Count))
		if err != nil {
			if _, ok := err.(errRemainInSufficient); !ok {
				result.Status.Reason = fmt.Sprintf("allocation of Collection %d, Partition %d, Channel %s, Count %d error:  %s",
					r.CollectionID, r.PartitionID, r.ChannelName, r.Count, err.Error())
				resp.SegIDAssignments = append(resp.SegIDAssignments, result)
				continue
			}

			log.Printf("no enough space for allocation of Collection %d, Partition %d, Channel %s, Count %d",
				r.CollectionID, r.PartitionID, r.ChannelName, r.Count)
			if err = s.openNewSegment(r.CollectionID, r.PartitionID, r.ChannelName); err != nil {
				result.Status.Reason = fmt.Sprintf("open new segment of Collection %d, Partition %d, Channel %s, Count %d error:  %s",
					r.CollectionID, r.PartitionID, r.ChannelName, r.Count, err.Error())
				resp.SegIDAssignments = append(resp.SegIDAssignments, result)
				continue
			}

			segmentID, retCount, expireTs, err = s.segAllocator.AllocSegment(r.CollectionID, r.PartitionID, r.ChannelName, int(r.Count))
			if err != nil {
				result.Status.Reason = fmt.Sprintf("retry allocation of Collection %d, Partition %d, Channel %s, Count %d error:  %s",
					r.CollectionID, r.PartitionID, r.ChannelName, r.Count, err.Error())
				resp.SegIDAssignments = append(resp.SegIDAssignments, result)
				continue
			}
		}

		result.Status.ErrorCode = commonpb.ErrorCode_SUCCESS
		result.CollectionID = r.CollectionID
		result.SegID = segmentID
		result.PartitionID = r.PartitionID
		result.Count = uint32(retCount)
		result.ExpireTime = expireTs
		result.ChannelName = r.ChannelName
		resp.SegIDAssignments = append(resp.SegIDAssignments, result)
	}
	return resp, nil
}

func (s *Server) openNewSegment(collectionID UniqueID, partitionID UniqueID, channelName string) error {
	group, err := s.insertChannelMgr.GetChannelGroup(collectionID, channelName)
	if err != nil {
		return err
	}
N
neza2017 已提交
386
	segmentInfo, err := s.meta.BuildSegment(collectionID, partitionID, group)
S
sunby 已提交
387 388 389 390 391 392
	if err != nil {
		return err
	}
	if err = s.meta.AddSegment(segmentInfo); err != nil {
		return err
	}
S
sunby 已提交
393
	if err = s.segAllocator.OpenSegment(segmentInfo); err != nil {
S
sunby 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
		return err
	}
	return nil
}

func (s *Server) ShowSegments(req *datapb.ShowSegmentRequest) (*datapb.ShowSegmentResponse, error) {
	ids := s.meta.GetSegmentsByCollectionAndPartitionID(req.CollectionID, req.PartitionID)
	return &datapb.ShowSegmentResponse{SegmentIDs: ids}, nil
}

func (s *Server) GetSegmentStates(req *datapb.SegmentStatesRequest) (*datapb.SegmentStatesResponse, error) {
	resp := &datapb.SegmentStatesResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
		},
	}

	segmentInfo, err := s.meta.GetSegment(req.SegmentID)
	if err != nil {
		resp.Status.Reason = "get segment states error: " + err.Error()
		return resp, nil
	}
	resp.State = segmentInfo.State
	resp.CreateTime = segmentInfo.OpenTime
	resp.SealedTime = segmentInfo.SealedTime
	resp.FlushedTime = segmentInfo.FlushedTime
	// TODO start/end positions
	return resp, nil
}

func (s *Server) GetInsertBinlogPaths(req *datapb.InsertBinlogPathRequest) (*datapb.InsertBinlogPathsResponse, error) {
	panic("implement me")
}

N
neza2017 已提交
428 429 430 431 432 433
func (s *Server) GetInsertChannels(req *datapb.InsertChannelRequest) (*internalpb2.StringList, error) {
	resp := &internalpb2.StringList{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
	}
S
sunby 已提交
434 435
	contains, ret := s.insertChannelMgr.ContainsCollection(req.CollectionID)
	if contains {
N
neza2017 已提交
436 437
		resp.Values = ret
		return resp, nil
S
sunby 已提交
438
	}
S
sunby 已提交
439
	channelGroups, err := s.insertChannelMgr.AllocChannels(req.CollectionID, s.cluster.GetNumOfNodes())
S
sunby 已提交
440
	if err != nil {
N
neza2017 已提交
441 442 443
		resp.Status.ErrorCode = commonpb.ErrorCode_UNEXPECTED_ERROR
		resp.Status.Reason = err.Error()
		return resp, nil
S
sunby 已提交
444
	}
S
sunby 已提交
445

S
sunby 已提交
446 447
	channels := make([]string, Params.InsertChannelNumPerCollection)
	for _, group := range channelGroups {
S
sunby 已提交
448
		channels = append(channels, group...)
S
sunby 已提交
449
	}
S
sunby 已提交
450 451
	s.cluster.WatchInsertChannels(channelGroups)

N
neza2017 已提交
452 453
	resp.Values = channels
	return resp, nil
S
sunby 已提交
454 455 456 457 458 459 460 461 462 463
}

func (s *Server) GetCollectionStatistics(req *datapb.CollectionStatsRequest) (*datapb.CollectionStatsResponse, error) {
	// todo implement
	return nil, nil
}

func (s *Server) GetPartitionStatistics(req *datapb.PartitionStatsRequest) (*datapb.PartitionStatsResponse, error) {
	// todo implement
	return nil, nil
S
sunby 已提交
464
}