queryservice.go 14.5 KB
Newer Older
X
xige-16 已提交
1
package queryservice
2

X
xige-16 已提交
3
import (
X
xige-16 已提交
4
	"context"
5
	"fmt"
X
xige-16 已提交
6
	"log"
X
xige-16 已提交
7
	"sort"
X
xige-16 已提交
8 9 10
	"strconv"
	"sync/atomic"

X
xige-16 已提交
11
	nodeclient "github.com/zilliztech/milvus-distributed/internal/distributed/querynode/client"
X
xige-16 已提交
12 13
	"github.com/zilliztech/milvus-distributed/internal/errors"
	"github.com/zilliztech/milvus-distributed/internal/proto/commonpb"
X
xige-16 已提交
14
	"github.com/zilliztech/milvus-distributed/internal/proto/datapb"
X
xige-16 已提交
15
	"github.com/zilliztech/milvus-distributed/internal/proto/internalpb2"
X
xige-16 已提交
16
	"github.com/zilliztech/milvus-distributed/internal/proto/milvuspb"
X
xige-16 已提交
17
	"github.com/zilliztech/milvus-distributed/internal/proto/querypb"
X
xige-16 已提交
18
	"github.com/zilliztech/milvus-distributed/internal/querynode"
X
xige-16 已提交
19
)
20

X
xige-16 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
type MasterServiceInterface interface {
	ShowPartitions(in *milvuspb.ShowPartitionRequest) (*milvuspb.ShowPartitionResponse, error)
	ShowSegments(in *milvuspb.ShowSegmentRequest) (*milvuspb.ShowSegmentResponse, error)
}

type DataServiceInterface interface {
	GetSegmentStates(req *datapb.SegmentStatesRequest) (*datapb.SegmentStatesResponse, error)
}

type QueryNodeInterface interface {
	GetComponentStates() (*internalpb2.ComponentStates, error)

	AddQueryChannel(in *querypb.AddQueryChannelsRequest) (*commonpb.Status, error)
	RemoveQueryChannel(in *querypb.RemoveQueryChannelsRequest) (*commonpb.Status, error)
	WatchDmChannels(in *querypb.WatchDmChannelsRequest) (*commonpb.Status, error)
	LoadSegments(in *querypb.LoadSegmentRequest) (*commonpb.Status, error)
	ReleaseSegments(in *querypb.ReleaseSegmentRequest) (*commonpb.Status, error)
}
X
xige-16 已提交
39

40
type QueryService struct {
X
xige-16 已提交
41 42 43
	loopCtx    context.Context
	loopCancel context.CancelFunc

X
xige-16 已提交
44
	queryServiceID uint64
X
xige-16 已提交
45 46
	replica        metaReplica

X
xige-16 已提交
47 48
	dataServiceClient   DataServiceInterface
	masterServiceClient MasterServiceInterface
49 50 51
	queryNodes          []*queryNodeInfo
	numRegisterNode     uint64
	numQueryChannel     uint64
X
xige-16 已提交
52

X
xige-16 已提交
53 54 55
	stateCode  atomic.Value
	isInit     atomic.Value
	enableGrpc bool
X
xige-16 已提交
56 57
}

N
neza2017 已提交
58
func (qs *QueryService) Init() error {
X
xige-16 已提交
59
	Params.Init()
X
xige-16 已提交
60 61 62 63
	qs.isInit.Store(true)
	return nil
}

N
neza2017 已提交
64
func (qs *QueryService) Start() error {
X
xige-16 已提交
65 66 67 68 69 70
	isInit := qs.isInit.Load().(bool)
	if !isInit {
		return errors.New("call start before init")
	}
	qs.stateCode.Store(internalpb2.StateCode_HEALTHY)
	return nil
X
xige-16 已提交
71 72
}

N
neza2017 已提交
73
func (qs *QueryService) Stop() error {
X
xige-16 已提交
74 75 76
	qs.loopCancel()
	qs.stateCode.Store(internalpb2.StateCode_ABNORMAL)
	return nil
X
xige-16 已提交
77 78
}

79
func (qs *QueryService) GetComponentStates() (*internalpb2.ComponentStates, error) {
X
xige-16 已提交
80 81 82 83 84
	serviceComponentInfo := &internalpb2.ComponentInfo{
		NodeID:    Params.QueryServiceID,
		StateCode: qs.stateCode.Load().(internalpb2.StateCode),
	}
	subComponentInfos := make([]*internalpb2.ComponentInfo, 0)
X
xige-16 已提交
85 86
	for nodeID, node := range qs.queryNodes {
		componentStates, err := node.GetComponentStates()
X
xige-16 已提交
87 88 89 90 91 92 93 94 95 96
		if err != nil {
			subComponentInfos = append(subComponentInfos, &internalpb2.ComponentInfo{
				NodeID:    int64(nodeID),
				StateCode: internalpb2.StateCode_ABNORMAL,
			})
			continue
		}
		subComponentInfos = append(subComponentInfos, componentStates.State)
	}
	return &internalpb2.ComponentStates{
X
xige-16 已提交
97 98 99
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
X
xige-16 已提交
100 101 102
		State:              serviceComponentInfo,
		SubcomponentStates: subComponentInfos,
	}, nil
X
xige-16 已提交
103 104 105
}

func (qs *QueryService) GetTimeTickChannel() (string, error) {
X
xige-16 已提交
106
	return Params.TimeTickChannelName, nil
X
xige-16 已提交
107 108 109
}

func (qs *QueryService) GetStatisticsChannel() (string, error) {
X
xige-16 已提交
110 111 112
	return Params.StatsChannelName, nil
}

X
xige-16 已提交
113
// TODO:: do addWatchDmChannel to query node after registerNode
X
xige-16 已提交
114
func (qs *QueryService) RegisterNode(req *querypb.RegisterNodeRequest) (*querypb.RegisterNodeResponse, error) {
115
	fmt.Println("register query node =", req.Address)
116
	// TODO:: add mutex
117
	allocatedID := uint64(len(qs.queryNodes))
X
xige-16 已提交
118 119

	registerNodeAddress := req.Address.Ip + ":" + strconv.FormatInt(req.Address.Port, 10)
120
	var node *queryNodeInfo
X
xige-16 已提交
121 122
	if qs.enableGrpc {
		client := nodeclient.NewClient(registerNodeAddress)
123
		node = &queryNodeInfo{
X
xige-16 已提交
124 125 126
			client: client,
			nodeID: allocatedID,
		}
X
xige-16 已提交
127
	} else {
X
xige-16 已提交
128
		client := querynode.NewQueryNode(qs.loopCtx, allocatedID)
129
		node = &queryNodeInfo{
X
xige-16 已提交
130 131 132
			client: client,
			nodeID: allocatedID,
		}
X
xige-16 已提交
133
	}
134
	qs.queryNodes = append(qs.queryNodes, node)
X
xige-16 已提交
135

136
	//TODO::return init params to queryNode
X
xige-16 已提交
137 138 139 140 141 142 143 144 145 146 147 148
	return &querypb.RegisterNodeResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		InitParams: &internalpb2.InitParams{
			NodeID: int64(allocatedID),
		},
	}, nil
}

func (qs *QueryService) ShowCollections(req *querypb.ShowCollectionRequest) (*querypb.ShowCollectionResponse, error) {
	dbID := req.DbID
149 150 151 152 153
	collections, err := qs.replica.getCollections(dbID)
	collectionIDs := make([]UniqueID, 0)
	for _, collection := range collections {
		collectionIDs = append(collectionIDs, collection.id)
	}
X
xige-16 已提交
154
	if err != nil {
155 156 157 158 159 160
		return &querypb.ShowCollectionResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
				Reason:    err.Error(),
			},
		}, err
X
xige-16 已提交
161 162 163 164 165 166 167 168 169 170
	}
	return &querypb.ShowCollectionResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		CollectionIDs: collectionIDs,
	}, nil
}

func (qs *QueryService) LoadCollection(req *querypb.LoadCollectionRequest) (*commonpb.Status, error) {
X
xige-16 已提交
171 172 173
	dbID := req.DbID
	collectionID := req.CollectionID
	fn := func(err error) *commonpb.Status {
174 175 176 177 178 179
		if err != nil {
			return &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
				Reason:    err.Error(),
			}
		}
X
xige-16 已提交
180
		return &commonpb.Status{
181
			ErrorCode: commonpb.ErrorCode_SUCCESS,
X
xige-16 已提交
182 183
		}
	}
184 185 186 187 188 189 190
	collection, err := qs.replica.loadCollection(dbID, collectionID)
	if err != nil {
		return fn(err), err
	}
	if collection == nil {
		return fn(nil), nil
	}
X
xige-16 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204

	// get partitionIDs
	showPartitionRequest := &milvuspb.ShowPartitionRequest{
		Base: &commonpb.MsgBase{
			MsgType: commonpb.MsgType_kShowPartitions,
		},
		CollectionID: collectionID,
	}

	showPartitionResponse, err := qs.masterServiceClient.ShowPartitions(showPartitionRequest)
	if err != nil {
		return fn(err), err
	}
	if showPartitionResponse.Status.ErrorCode != commonpb.ErrorCode_SUCCESS {
205
		return showPartitionResponse.Status, err
X
xige-16 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218
	}
	partitionIDs := showPartitionResponse.PartitionIDs

	loadPartitionsRequest := &querypb.LoadPartitionRequest{
		Base:         req.Base,
		DbID:         dbID,
		CollectionID: collectionID,
		PartitionIDs: partitionIDs,
	}

	status, err := qs.LoadPartitions(loadPartitionsRequest)

	return status, err
X
xige-16 已提交
219 220
}

X
xige-16 已提交
221
func (qs *QueryService) ReleaseCollection(req *querypb.ReleaseCollectionRequest) (*commonpb.Status, error) {
X
xige-16 已提交
222 223
	dbID := req.DbID
	collectionID := req.CollectionID
224
	partitions, err := qs.replica.getPartitions(dbID, collectionID)
X
xige-16 已提交
225
	if err != nil {
226 227 228 229
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
			Reason:    err.Error(),
		}, err
X
xige-16 已提交
230
	}
231 232 233 234 235 236

	partitionIDs := make([]UniqueID, 0)
	for _, partition := range partitions {
		partitionIDs = append(partitionIDs, partition.id)
	}

X
xige-16 已提交
237 238 239 240
	releasePartitionRequest := &querypb.ReleasePartitionRequest{
		Base:         req.Base,
		DbID:         dbID,
		CollectionID: collectionID,
241
		PartitionIDs: partitionIDs,
X
xige-16 已提交
242 243 244 245 246
	}

	status, err := qs.ReleasePartitions(releasePartitionRequest)

	return status, err
247 248
}

X
xige-16 已提交
249 250 251
func (qs *QueryService) ShowPartitions(req *querypb.ShowPartitionRequest) (*querypb.ShowPartitionResponse, error) {
	dbID := req.DbID
	collectionID := req.CollectionID
252 253 254 255 256
	partitions, err := qs.replica.getPartitions(dbID, collectionID)
	partitionIDs := make([]UniqueID, 0)
	for _, partition := range partitions {
		partitionIDs = append(partitionIDs, partition.id)
	}
X
xige-16 已提交
257
	if err != nil {
258 259 260 261 262 263
		return &querypb.ShowPartitionResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
				Reason:    err.Error(),
			},
		}, err
X
xige-16 已提交
264 265 266 267 268 269 270
	}
	return &querypb.ShowPartitionResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		PartitionIDs: partitionIDs,
	}, nil
271 272
}

X
xige-16 已提交
273
func (qs *QueryService) LoadPartitions(req *querypb.LoadPartitionRequest) (*commonpb.Status, error) {
274
	//TODO::suggest different partitions have different dm channel
X
xige-16 已提交
275 276 277
	dbID := req.DbID
	collectionID := req.CollectionID
	partitionIDs := req.PartitionIDs
278
	qs.replica.loadPartition(dbID, collectionID, partitionIDs[0])
X
xige-16 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
	fn := func(err error) *commonpb.Status {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
			Reason:    err.Error(),
		}
	}

	// get segments and load segment to query node
	for _, partitionID := range partitionIDs {
		showSegmentRequest := &milvuspb.ShowSegmentRequest{
			Base: &commonpb.MsgBase{
				MsgType: commonpb.MsgType_kShowSegment,
			},
			CollectionID: collectionID,
			PartitionID:  partitionID,
		}
		showSegmentResponse, err := qs.masterServiceClient.ShowSegments(showSegmentRequest)
		if err != nil {
			return fn(err), err
		}
		if showSegmentResponse.Status.ErrorCode != commonpb.ErrorCode_SUCCESS {
			log.Fatal("showSegment fail, v%", showSegmentResponse.Status.Reason)
		}
		segmentIDs := showSegmentResponse.SegmentIDs
Z
zhenshan.cao 已提交
303
		segmentStates := make(map[UniqueID]*datapb.SegmentStateInfo)
X
xige-16 已提交
304
		channel2id := make(map[string]int)
305
		//id2channels := make(map[int][]string)
X
xige-16 已提交
306 307 308
		id2segs := make(map[int][]UniqueID)
		offset := 0

Z
zhenshan.cao 已提交
309 310 311 312 313 314 315 316 317 318
		resp, err := qs.dataServiceClient.GetSegmentStates(&datapb.SegmentStatesRequest{
			SegmentIDs: segmentIDs,
		})

		if err != nil {
			log.Fatal("get segment states fail")
		}

		for _, state := range resp.States {
			segmentID := state.SegmentID
X
xige-16 已提交
319 320
			segmentStates[segmentID] = state
			var flatChannelName string
X
XuanYang-cn 已提交
321 322 323 324 325 326 327 328
			// channelNames := make([]string, 0)
			// for i, str := range state.StartPositions {
			//     flatChannelName += str.ChannelName
			//     channelNames = append(channelNames, str.ChannelName)
			//     if i+1 < len(state.StartPositions) {
			//         flatChannelName += "/"
			//     }
			// }
329 330 331
			if flatChannelName == "" {
				log.Fatal("segmentState's channel name is empty")
			}
X
xige-16 已提交
332 333
			if _, ok := channel2id[flatChannelName]; !ok {
				channel2id[flatChannelName] = offset
334
				//id2channels[offset] = channelNames
X
xige-16 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347
				id2segs[offset] = make([]UniqueID, 0)
				id2segs[offset] = append(id2segs[offset], segmentID)
				offset++
			} else {
				//TODO::check channel name
				id := channel2id[flatChannelName]
				id2segs[id] = append(id2segs[id], segmentID)
			}
		}
		for key, value := range id2segs {
			sort.Slice(value, func(i, j int) bool { return segmentStates[value[i]].CreateTime < segmentStates[value[j]].CreateTime })
			selectedSegs := make([]UniqueID, 0)
			for i, v := range value {
Z
zhenshan.cao 已提交
348
				if segmentStates[v].State == commonpb.SegmentState_SegmentFlushed {
X
xige-16 已提交
349 350
					selectedSegs = append(selectedSegs, v)
				} else {
Z
zhenshan.cao 已提交
351
					if i > 0 && segmentStates[selectedSegs[i-1]].State != commonpb.SegmentState_SegmentFlushed {
X
xige-16 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
						break
					}
					selectedSegs = append(selectedSegs, v)
				}
			}
			id2segs[key] = selectedSegs
		}

		qs.replica.updatePartitionState(dbID, collectionID, partitionID, querypb.PartitionState_PartialInMemory)

		// TODO:: filter channel for query node
		for channels, i := range channel2id {
			for key, node := range qs.queryNodes {
				if channels == node.insertChannels {
					statesID := id2segs[i][len(id2segs[i])-1]
367
					//TODO :: should be start position
X
XuanYang-cn 已提交
368 369
					// position := segmentStates[statesID-1].StartPositions
					// segmentStates[statesID].StartPositions = position
X
xige-16 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
					loadSegmentRequest := &querypb.LoadSegmentRequest{
						CollectionID:     collectionID,
						PartitionID:      partitionID,
						SegmentIDs:       id2segs[i],
						LastSegmentState: segmentStates[statesID],
					}
					status, err := qs.queryNodes[key].LoadSegments(loadSegmentRequest)
					if err != nil {
						return status, err
					}
				}
			}
		}
		qs.replica.updatePartitionState(dbID, collectionID, partitionID, querypb.PartitionState_InMemory)
	}
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_SUCCESS,
	}, nil
388 389
}

X
xige-16 已提交
390
func (qs *QueryService) ReleasePartitions(req *querypb.ReleasePartitionRequest) (*commonpb.Status, error) {
X
xige-16 已提交
391 392 393 394 395
	dbID := req.DbID
	collectionID := req.CollectionID
	partitionIDs := req.PartitionIDs
	segmentIDs := make([]UniqueID, 0)
	for _, partitionID := range partitionIDs {
396
		segments, err := qs.replica.getSegments(dbID, collectionID, partitionID)
X
xige-16 已提交
397
		if err != nil {
398 399 400 401
			return &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
				Reason:    err.Error(),
			}, err
X
xige-16 已提交
402
		}
403 404 405 406 407
		res := make([]UniqueID, 0)
		for _, segment := range segments {
			res = append(res, segment.id)
		}

X
xige-16 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
		segmentIDs = append(segmentIDs, res...)
	}
	releaseSegmentRequest := &querypb.ReleaseSegmentRequest{
		Base:         req.Base,
		DbID:         dbID,
		CollectionID: collectionID,
		PartitionIDs: partitionIDs,
		SegmentIDs:   segmentIDs,
	}

	for _, node := range qs.queryNodes {
		status, err := node.client.ReleaseSegments(releaseSegmentRequest)
		if err != nil {
			return status, err
		}
	}

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_SUCCESS,
	}, nil
428 429
}

X
xige-16 已提交
430 431 432 433 434
func (qs *QueryService) CreateQueryChannel() (*querypb.CreateQueryChannelResponse, error) {
	channelID := qs.numQueryChannel
	qs.numQueryChannel++
	allocatedQueryChannel := "query-" + strconv.FormatInt(int64(channelID), 10)
	allocatedQueryResultChannel := "queryResult-" + strconv.FormatInt(int64(channelID), 10)
435

X
xige-16 已提交
436
	//TODO:: query node watch query channels
X
xige-16 已提交
437 438 439 440 441 442 443
	return &querypb.CreateQueryChannelResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		RequestChannel: allocatedQueryChannel,
		ResultChannel:  allocatedQueryResultChannel,
	}, nil
444 445
}

X
xige-16 已提交
446
func (qs *QueryService) GetPartitionStates(req *querypb.PartitionStatesRequest) (*querypb.PartitionStatesResponse, error) {
X
xige-16 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
	states, err := qs.replica.getPartitionStates(req.DbID, req.CollectionID, req.PartitionIDs)
	if err != nil {
		return &querypb.PartitionStatesResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UNEXPECTED_ERROR,
				Reason:    err.Error(),
			},
			PartitionDescriptions: states,
		}, err
	}
	return &querypb.PartitionStatesResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_SUCCESS,
		},
		PartitionDescriptions: states,
	}, nil
X
xige-16 已提交
463 464
}

X
xige-16 已提交
465
func NewQueryService(ctx context.Context) (*QueryService, error) {
466
	nodes := make([]*queryNodeInfo, 0)
X
xige-16 已提交
467
	ctx1, cancel := context.WithCancel(ctx)
X
xige-16 已提交
468
	replica := newMetaReplica()
X
xige-16 已提交
469 470 471
	service := &QueryService{
		loopCtx:         ctx1,
		loopCancel:      cancel,
X
xige-16 已提交
472 473 474
		queryNodes:      nodes,
		replica:         replica,
		numRegisterNode: 0,
X
xige-16 已提交
475
		numQueryChannel: 0,
X
xige-16 已提交
476
		enableGrpc:      false,
X
xige-16 已提交
477 478 479 480
	}
	service.stateCode.Store(internalpb2.StateCode_INITIALIZING)
	service.isInit.Store(false)
	return service, nil
481
}
X
xige-16 已提交
482 483 484 485 486 487 488 489 490 491 492 493

func (qs *QueryService) SetMasterService(masterService MasterServiceInterface) {
	qs.masterServiceClient = masterService
}

func (qs *QueryService) SetDataService(dataService DataServiceInterface) {
	qs.dataServiceClient = dataService
}

func (qs *QueryService) SetEnableGrpc(en bool) {
	qs.enableGrpc = en
}