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

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

	"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 38 39 40 41 42 43 44 45 46 47
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)

	GetInsertChannels(req *datapb.InsertChannelRequest) (*internalpb2.StringList, error)
	GetCollectionStatistics(req *datapb.CollectionStatsRequest) (*datapb.CollectionStatsResponse, error)
	GetPartitionStatistics(req *datapb.PartitionStatsRequest) (*datapb.PartitionStatsResponse, error)
	GetComponentStates() (*internalpb2.ComponentStates, error)
	GetTimeTickChannel() (*milvuspb.StringResponse, error)
	GetStatisticsChannel() (*milvuspb.StringResponse, error)
}

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

func CreateServer(ctx context.Context) (*Server, error) {
S
sunby 已提交
68
	ch := make(chan struct{})
S
sunby 已提交
69 70 71 72
	return &Server{
		ctx:              ctx,
		state:            internalpb2.StateCode_INITIALIZING,
		insertChannelMgr: newInsertChannelManager(),
S
sunby 已提交
73 74
		registerFinishCh: ch,
		cluster:          newDataNodeCluster(ch),
S
sunby 已提交
75 76 77 78 79
	}, nil
}

func (s *Server) Init() error {
	Params.Init()
S
sunby 已提交
80 81 82 83 84 85 86 87
	return nil
}

func (s *Server) Start() error {
	if err := s.connectMaster(); err != nil {
		return err
	}
	s.allocator = newAllocatorImpl(s.masterClient)
S
sunby 已提交
88 89 90 91
	if err := s.initMeta(); err != nil {
		return err
	}
	s.statsHandler = newStatsHandler(s.meta)
S
sunby 已提交
92
	segAllocator, err := newSegmentAllocator(s.meta, s.allocator)
S
sunby 已提交
93 94 95 96
	if err != nil {
		return err
	}
	s.segAllocator = segAllocator
S
sunby 已提交
97 98 99 100
	s.waitDataNodeRegister()
	if err = s.loadMetaFromMaster(); err != nil {
		return err
	}
S
sunby 已提交
101 102 103
	if err = s.initMsgProducer(); err != nil {
		return err
	}
S
sunby 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
	s.state = internalpb2.StateCode_HEALTHY
	log.Println("start success")
	return nil
}

func (s *Server) connectMaster() error {
	log.Println("connecting to master")
	master, err := masterservice.NewGrpcClient(Params.MasterAddress, 30*time.Second)
	if err != nil {
		return err
	}
	if err = master.Init(nil); err != nil {
		return err
	}
	if err = master.Start(); err != nil {
		return err
	}
	s.masterClient = master
	log.Println("connect to master success")
S
sunby 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
	return nil
}

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
	s.meta, err = newMeta(etcdKV, s.allocator)
	if err != nil {
		return err
	}
	return nil
}

S
sunby 已提交
140 141 142 143 144 145
func (s *Server) waitDataNodeRegister() {
	log.Println("waiting data node to register")
	<-s.registerFinishCh
	log.Println("all data nodes register")
}

S
sunby 已提交
146 147
func (s *Server) initMsgProducer() error {
	// todo ttstream and peerids
S
sunby 已提交
148 149 150 151 152
	s.ttMsgStream = pulsarms.NewPulsarTtMsgStream(s.ctx, 1024)
	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 已提交
153 154 155 156 157 158 159
	if err != nil {
		return err
	}
	s.msgProducer = producer
	s.msgProducer.Start(s.ctx)
	return nil
}
S
sunby 已提交
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
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,
			partitions: partitions.PartitionIDs,
		})
		if err != nil {
			log.Println(err.Error())
			continue
		}
	}
	log.Println("load collection meta from master complete")
	return nil
S
sunby 已提交
216 217 218
}

func (s *Server) Stop() error {
S
sunby 已提交
219
	s.ttMsgStream.Close()
S
sunby 已提交
220 221 222 223 224
	s.msgProducer.Close()
	return nil
}

func (s *Server) GetComponentStates() (*internalpb2.ComponentStates, error) {
S
sunby 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	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 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
}

func (s *Server) GetTimeTickChannel() (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		Value: Params.TimeTickChannelName,
	}, nil
}

func (s *Server) GetStatisticsChannel() (*milvuspb.StringResponse, error) {
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		Value: Params.StatisticsChannelName,
	}, nil
}

func (s *Server) RegisterNode(req *datapb.RegisterNodeRequest) (*datapb.RegisterNodeResponse, error) {
S
sunby 已提交
264 265 266
	s.cluster.Register(req.Address.Ip, req.Address.Port, req.Base.SourceID)
	// add init params
	return &datapb.RegisterNodeResponse{
S
sunby 已提交
267
		Status: &commonpb.Status{
S
sunby 已提交
268
			ErrorCode: commonpb.ErrorCode_SUCCESS,
S
sunby 已提交
269
		},
S
sunby 已提交
270
	}, nil
S
sunby 已提交
271 272 273
}

func (s *Server) Flush(req *datapb.FlushRequest) (*commonpb.Status, error) {
S
sunby 已提交
274 275 276 277 278 279 280 281 282 283 284
	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
	}
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_SUCCESS,
	}, nil
S
sunby 已提交
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
}

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
	}
	segmentInfo, err := s.meta.BuildSegment(collectionID, partitionID, group)
	if err != nil {
		return err
	}
	if err = s.meta.AddSegment(segmentInfo); err != nil {
		return err
	}
S
sunby 已提交
351
	if err = s.segAllocator.OpenSegment(segmentInfo); err != nil {
S
sunby 已提交
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 386 387 388 389 390 391 392 393 394 395 396
		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")
}

func (s *Server) GetInsertChannels(req *datapb.InsertChannelRequest) (*internalpb2.StringList, error) {
	resp := &internalpb2.StringList{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
	}
	contains, ret := s.insertChannelMgr.ContainsCollection(req.CollectionID)
	if contains {
		resp.Values = ret
		return resp, nil
	}
S
sunby 已提交
397
	channelGroups, err := s.insertChannelMgr.AllocChannels(req.CollectionID, s.cluster.GetNumOfNodes())
S
sunby 已提交
398 399 400 401 402
	if err != nil {
		resp.Status.ErrorCode = commonpb.ErrorCode_UNEXPECTED_ERROR
		resp.Status.Reason = err.Error()
		return resp, nil
	}
S
sunby 已提交
403

S
sunby 已提交
404 405
	channels := make([]string, Params.InsertChannelNumPerCollection)
	for _, group := range channelGroups {
S
sunby 已提交
406
		channels = append(channels, group...)
S
sunby 已提交
407
	}
S
sunby 已提交
408 409
	s.cluster.WatchInsertChannels(channelGroups)

S
sunby 已提交
410 411 412 413 414 415 416 417 418 419 420 421
	resp.Values = channels
	return resp, nil
}

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 已提交
422
}