task.go 115.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// 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.

C
Cai Yudong 已提交
12
package proxy
Z
zhenshan.cao 已提交
13 14

import (
15
	"bytes"
G
godchen 已提交
16
	"context"
17
	"encoding/binary"
18
	"errors"
19
	"fmt"
N
neza2017 已提交
20
	"math"
21
	"reflect"
Z
zhenshan.cao 已提交
22
	"regexp"
23
	"runtime"
24
	"sort"
N
neza2017 已提交
25
	"strconv"
26
	"time"
27
	"unsafe"
28

29 30
	"github.com/milvus-io/milvus/internal/util/indexparamcheck"

31 32
	"github.com/milvus-io/milvus/internal/proto/planpb"

X
Xiangyu Wang 已提交
33
	"github.com/milvus-io/milvus/internal/util/funcutil"
N
neza2017 已提交
34

35
	"go.uber.org/zap"
S
sunby 已提交
36

N
neza2017 已提交
37
	"github.com/golang/protobuf/proto"
X
Xiangyu Wang 已提交
38 39 40 41 42 43 44 45 46 47 48 49
	"github.com/milvus-io/milvus/internal/allocator"
	"github.com/milvus-io/milvus/internal/log"
	"github.com/milvus-io/milvus/internal/msgstream"
	"github.com/milvus-io/milvus/internal/proto/commonpb"
	"github.com/milvus-io/milvus/internal/proto/datapb"
	"github.com/milvus-io/milvus/internal/proto/indexpb"
	"github.com/milvus-io/milvus/internal/proto/internalpb"
	"github.com/milvus-io/milvus/internal/proto/milvuspb"
	"github.com/milvus-io/milvus/internal/proto/querypb"
	"github.com/milvus-io/milvus/internal/proto/schemapb"
	"github.com/milvus-io/milvus/internal/types"
	"github.com/milvus-io/milvus/internal/util/typeutil"
Z
zhenshan.cao 已提交
50 51
)

S
sunby 已提交
52 53 54 55 56
const (
	InsertTaskName                  = "InsertTask"
	CreateCollectionTaskName        = "CreateCollectionTask"
	DropCollectionTaskName          = "DropCollectionTask"
	SearchTaskName                  = "SearchTask"
57
	RetrieveTaskName                = "RetrieveTask"
58 59 60 61
	AnnsFieldKey                    = "anns_field"
	TopKKey                         = "topk"
	MetricTypeKey                   = "metric_type"
	SearchParamsKey                 = "params"
S
sunby 已提交
62 63 64
	HasCollectionTaskName           = "HasCollectionTask"
	DescribeCollectionTaskName      = "DescribeCollectionTask"
	GetCollectionStatisticsTaskName = "GetCollectionStatisticsTask"
65
	GetPartitionStatisticsTaskName  = "GetPartitionStatisticsTask"
S
sunby 已提交
66 67 68 69 70 71 72 73 74
	ShowCollectionTaskName          = "ShowCollectionTask"
	CreatePartitionTaskName         = "CreatePartitionTask"
	DropPartitionTaskName           = "DropPartitionTask"
	HasPartitionTaskName            = "HasPartitionTask"
	ShowPartitionTaskName           = "ShowPartitionTask"
	CreateIndexTaskName             = "CreateIndexTask"
	DescribeIndexTaskName           = "DescribeIndexTask"
	DropIndexTaskName               = "DropIndexTask"
	GetIndexStateTaskName           = "GetIndexStateTask"
75
	GetIndexBuildProgressTaskName   = "GetIndexBuildProgressTask"
S
sunby 已提交
76 77 78 79 80 81 82
	FlushTaskName                   = "FlushTask"
	LoadCollectionTaskName          = "LoadCollectionTask"
	ReleaseCollectionTaskName       = "ReleaseCollectionTask"
	LoadPartitionTaskName           = "LoadPartitionTask"
	ReleasePartitionTaskName        = "ReleasePartitionTask"
)

Z
zhenshan.cao 已提交
83
type task interface {
84
	TraceCtx() context.Context
85 86
	ID() UniqueID       // return ReqID
	SetID(uid UniqueID) // set ReqID
S
sunby 已提交
87
	Name() string
88
	Type() commonpb.MsgType
89 90
	BeginTs() Timestamp
	EndTs() Timestamp
Z
zhenshan.cao 已提交
91
	SetTs(ts Timestamp)
92
	OnEnqueue() error
S
sunby 已提交
93 94 95
	PreExecute(ctx context.Context) error
	Execute(ctx context.Context) error
	PostExecute(ctx context.Context) error
Z
zhenshan.cao 已提交
96
	WaitToFinish() error
97
	Notify(err error)
Z
zhenshan.cao 已提交
98 99
}

100 101
type dmlTask interface {
	task
102 103
	getChannels() ([]vChan, error)
	getPChanStats() (map[pChan]pChanStatistics, error)
104 105
}

106
type BaseInsertTask = msgstream.InsertMsg
107 108

type InsertTask struct {
109
	BaseInsertTask
110
	req *milvuspb.InsertRequest
D
dragondriver 已提交
111
	Condition
112 113
	ctx context.Context

114
	result         *milvuspb.MutationResult
115
	dataCoord      types.DataCoord
T
ThreadDao 已提交
116
	rowIDAllocator *allocator.IDAllocator
117
	segIDAssigner  *SegIDAssigner
118
	chMgr          channelsMgr
119
	chTicker       channelsTimeTicker
120 121
	vChannels      []vChan
	pChannels      []pChan
122
	schema         *schemapb.CollectionSchema
123 124
}

125
func (it *InsertTask) TraceCtx() context.Context {
S
sunby 已提交
126 127 128 129 130
	return it.ctx
}

func (it *InsertTask) ID() UniqueID {
	return it.Base.MsgID
131 132
}

133
func (it *InsertTask) SetID(uid UniqueID) {
134
	it.Base.MsgID = uid
135 136
}

S
sunby 已提交
137 138 139 140 141 142 143 144 145 146 147 148
func (it *InsertTask) Name() string {
	return InsertTaskName
}

func (it *InsertTask) Type() commonpb.MsgType {
	return it.Base.MsgType
}

func (it *InsertTask) BeginTs() Timestamp {
	return it.BeginTimestamp
}

149
func (it *InsertTask) SetTs(ts Timestamp) {
N
neza2017 已提交
150 151
	it.BeginTimestamp = ts
	it.EndTimestamp = ts
152 153 154
}

func (it *InsertTask) EndTs() Timestamp {
N
neza2017 已提交
155
	return it.EndTimestamp
156 157
}

158 159 160 161
func (it *InsertTask) getPChanStats() (map[pChan]pChanStatistics, error) {
	ret := make(map[pChan]pChanStatistics)

	channels, err := it.getChannels()
162
	if err != nil {
163
		return ret, err
164 165
	}

166 167 168 169 170 171 172
	beginTs := it.BeginTs()
	endTs := it.EndTs()

	for _, channel := range channels {
		ret[channel] = pChanStatistics{
			minTs: beginTs,
			maxTs: endTs,
173 174
		}
	}
175 176 177 178 179
	return ret, nil
}

func (it *InsertTask) getChannels() ([]pChan, error) {
	collID, err := globalMetaCache.GetCollectionID(it.ctx, it.CollectionName)
180
	if err != nil {
181
		return nil, err
182
	}
183 184 185 186 187 188
	var channels []pChan
	channels, err = it.chMgr.getChannels(collID)
	if err != nil {
		err = it.chMgr.createDMLMsgStream(collID)
		if err != nil {
			return nil, err
189
		}
190
		channels, err = it.chMgr.getChannels(collID)
191
	}
192
	return channels, err
193 194
}

S
sunby 已提交
195
func (it *InsertTask) OnEnqueue() error {
D
dragondriver 已提交
196
	it.BaseInsertTask.InsertRequest.Base = &commonpb.MsgBase{}
S
sunby 已提交
197
	return nil
198 199
}

200
// TODO(dragondriver): ignore the order of fields in request, use the order of CollectionSchema to reorganize data
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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 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 351 352 353 354 355
func (it *InsertTask) transferColumnBasedRequestToRowBasedData() error {
	dTypes := make([]schemapb.DataType, 0, len(it.req.FieldsData))
	datas := make([][]interface{}, 0, len(it.req.FieldsData))
	rowNum := 0

	appendScalarField := func(getDataFunc func() interface{}) error {
		fieldDatas := reflect.ValueOf(getDataFunc())
		if rowNum != 0 && rowNum != fieldDatas.Len() {
			return errors.New("the row num of different column is not equal")
		}
		rowNum = fieldDatas.Len()
		datas = append(datas, make([]interface{}, 0, rowNum))
		idx := len(datas) - 1
		for i := 0; i < rowNum; i++ {
			datas[idx] = append(datas[idx], fieldDatas.Index(i).Interface())
		}

		return nil
	}

	appendFloatVectorField := func(fDatas []float32, dim int64) error {
		l := len(fDatas)
		if int64(l)%dim != 0 {
			return errors.New("invalid vectors")
		}
		r := int64(l) / dim
		if rowNum != 0 && rowNum != int(r) {
			return errors.New("the row num of different column is not equal")
		}
		rowNum = int(r)
		datas = append(datas, make([]interface{}, 0, rowNum))
		idx := len(datas) - 1
		vector := make([]float32, 0, dim)
		for i := 0; i < l; i++ {
			vector = append(vector, fDatas[i])
			if int64(i+1)%dim == 0 {
				datas[idx] = append(datas[idx], vector)
				vector = make([]float32, 0, dim)
			}
		}

		return nil
	}

	appendBinaryVectorField := func(bDatas []byte, dim int64) error {
		l := len(bDatas)
		if dim%8 != 0 {
			return errors.New("invalid dim")
		}
		if (8*int64(l))%dim != 0 {
			return errors.New("invalid vectors")
		}
		r := (8 * int64(l)) / dim
		if rowNum != 0 && rowNum != int(r) {
			return errors.New("the row num of different column is not equal")
		}
		rowNum = int(r)
		datas = append(datas, make([]interface{}, 0, rowNum))
		idx := len(datas) - 1
		vector := make([]byte, 0, dim)
		for i := 0; i < l; i++ {
			vector = append(vector, bDatas[i])
			if (8*int64(i+1))%dim == 0 {
				datas[idx] = append(datas[idx], vector)
				vector = make([]byte, 0, dim)
			}
		}

		return nil
	}

	for _, field := range it.req.FieldsData {
		switch field.Field.(type) {
		case *schemapb.FieldData_Scalars:
			scalarField := field.GetScalars()
			switch scalarField.Data.(type) {
			case *schemapb.ScalarField_BoolData:
				err := appendScalarField(func() interface{} {
					return scalarField.GetBoolData().Data
				})
				if err != nil {
					return err
				}
			case *schemapb.ScalarField_IntData:
				err := appendScalarField(func() interface{} {
					return scalarField.GetIntData().Data
				})
				if err != nil {
					return err
				}
			case *schemapb.ScalarField_LongData:
				err := appendScalarField(func() interface{} {
					return scalarField.GetLongData().Data
				})
				if err != nil {
					return err
				}
			case *schemapb.ScalarField_FloatData:
				err := appendScalarField(func() interface{} {
					return scalarField.GetFloatData().Data
				})
				if err != nil {
					return err
				}
			case *schemapb.ScalarField_DoubleData:
				err := appendScalarField(func() interface{} {
					return scalarField.GetDoubleData().Data
				})
				if err != nil {
					return err
				}
			case *schemapb.ScalarField_BytesData:
				return errors.New("bytes field is not supported now")
			case *schemapb.ScalarField_StringData:
				return errors.New("string field is not supported now")
			case nil:
				continue
			default:
				continue
			}
		case *schemapb.FieldData_Vectors:
			vectorField := field.GetVectors()
			switch vectorField.Data.(type) {
			case *schemapb.VectorField_FloatVector:
				floatVectorFieldData := vectorField.GetFloatVector().Data
				dim := vectorField.GetDim()
				err := appendFloatVectorField(floatVectorFieldData, dim)
				if err != nil {
					return err
				}
			case *schemapb.VectorField_BinaryVector:
				binaryVectorFieldData := vectorField.GetBinaryVector()
				dim := vectorField.GetDim()
				err := appendBinaryVectorField(binaryVectorFieldData, dim)
				if err != nil {
					return err
				}
			case nil:
				continue
			default:
				continue
			}
		case nil:
			continue
		default:
			continue
		}

		dTypes = append(dTypes, field.Type)
	}

	it.RowData = make([]*commonpb.Blob, 0, rowNum)
	l := len(dTypes)
	// TODO(dragondriver): big endian or little endian?
	endian := binary.LittleEndian
356
	printed := false
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
	for i := 0; i < rowNum; i++ {
		blob := &commonpb.Blob{
			Value: make([]byte, 0),
		}

		for j := 0; j < l; j++ {
			var buffer bytes.Buffer
			switch dTypes[j] {
			case schemapb.DataType_Bool:
				d := datas[j][i].(bool)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Int8:
D
dragondriver 已提交
373
				d := int8(datas[j][i].(int32))
374 375 376 377 378 379
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Int16:
D
dragondriver 已提交
380
				d := int16(datas[j][i].(int32))
381 382 383 384 385 386 387 388 389 390 391 392 393 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 428 429 430 431
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Int32:
				d := datas[j][i].(int32)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Int64:
				d := datas[j][i].(int64)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Float:
				d := datas[j][i].(float32)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_Double:
				d := datas[j][i].(float64)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_FloatVector:
				d := datas[j][i].([]float32)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			case schemapb.DataType_BinaryVector:
				d := datas[j][i].([]byte)
				err := binary.Write(&buffer, endian, d)
				if err != nil {
					log.Warn("ConvertData", zap.Error(err))
				}
				blob.Value = append(blob.Value, buffer.Bytes()...)
			default:
				log.Warn("unsupported data type")
			}
		}
432
		if !printed {
C
Cai Yudong 已提交
433
			log.Debug("Proxy, transform", zap.Any("ID", it.ID()), zap.Any("BlobLen", len(blob.Value)), zap.Any("dTypes", dTypes))
434 435
			printed = true
		}
436 437 438 439 440 441
		it.RowData = append(it.RowData, blob)
	}

	return nil
}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
func (it *InsertTask) checkFieldAutoID() error {
	// TODO(dragondriver): in fact, NumRows is not trustable, we should check all input fields
	rowNums := it.req.NumRows
	if len(it.req.FieldsData) == 0 || rowNums == 0 {
		return fmt.Errorf("do not contain any data")
	}

	primaryFieldName := ""
	autoIDFieldName := ""
	autoIDLoc := -1
	primaryLoc := -1
	fields := it.schema.Fields

	for loc, field := range fields {
		if field.AutoID {
			autoIDLoc = loc
			autoIDFieldName = field.Name
		}
		if field.IsPrimaryKey {
			primaryLoc = loc
			primaryFieldName = field.Name
		}
	}

	if primaryLoc < 0 {
		return fmt.Errorf("primary field is not found")
	}

	if autoIDLoc >= 0 && autoIDLoc != primaryLoc {
		return fmt.Errorf("currently auto id field is only supported on primary field")
	}

	var primaryField *schemapb.FieldData
	var primaryData []int64
	for _, field := range it.req.FieldsData {
		if field.FieldName == autoIDFieldName {
			return fmt.Errorf("autoID field (%v) does not require data", autoIDFieldName)
		}
		if field.FieldName == primaryFieldName {
			primaryField = field
		}
	}

	if primaryField != nil {
		if primaryField.Type != schemapb.DataType_Int64 {
			return fmt.Errorf("currently only support DataType Int64 as PrimaryField and Enable autoID")
		}
		switch primaryField.Field.(type) {
		case *schemapb.FieldData_Scalars:
			scalarField := primaryField.GetScalars()
			switch scalarField.Data.(type) {
			case *schemapb.ScalarField_LongData:
				primaryData = scalarField.GetLongData().Data
			default:
				return fmt.Errorf("currently only support DataType Int64 as PrimaryField and Enable autoID")
			}
		default:
			return fmt.Errorf("currently only support DataType Int64 as PrimaryField and Enable autoID")
		}
		it.result.IDs.IdField = &schemapb.IDs_IntId{
			IntId: &schemapb.LongArray{
				Data: primaryData,
			},
		}
	}

	var rowIDBegin UniqueID
	var rowIDEnd UniqueID

	rowIDBegin, rowIDEnd, _ = it.rowIDAllocator.Alloc(rowNums)

	it.BaseInsertTask.RowIDs = make([]UniqueID, rowNums)
	for i := rowIDBegin; i < rowIDEnd; i++ {
		offset := i - rowIDBegin
		it.BaseInsertTask.RowIDs[offset] = i
	}

	if autoIDLoc >= 0 {
		fieldData := schemapb.FieldData{
			FieldName: primaryFieldName,
522
			Type:      schemapb.DataType_Int64,
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 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
			Field: &schemapb.FieldData_Scalars{
				Scalars: &schemapb.ScalarField{
					Data: &schemapb.ScalarField_LongData{
						LongData: &schemapb.LongArray{
							Data: it.BaseInsertTask.RowIDs,
						},
					},
				},
			},
		}

		// TODO(dragondriver): when we can ignore the order of input fields, use append directly
		// it.req.FieldsData = append(it.req.FieldsData, &fieldData)

		it.req.FieldsData = append(it.req.FieldsData, &schemapb.FieldData{})
		copy(it.req.FieldsData[autoIDLoc+1:], it.req.FieldsData[autoIDLoc:])
		it.req.FieldsData[autoIDLoc] = &fieldData

		it.result.IDs.IdField = &schemapb.IDs_IntId{
			IntId: &schemapb.LongArray{
				Data: it.BaseInsertTask.RowIDs,
			},
		}

		// TODO(dragondriver): in this case, should we directly overwrite the hash?

		if len(it.HashValues) != 0 && len(it.HashValues) != len(it.BaseInsertTask.RowIDs) {
			return fmt.Errorf("invalid length of input hash values")
		}
		if it.HashValues == nil || len(it.HashValues) <= 0 {
			it.HashValues = make([]uint32, 0, len(it.BaseInsertTask.RowIDs))
			for _, rowID := range it.BaseInsertTask.RowIDs {
				hash, _ := typeutil.Hash32Int64(rowID)
				it.HashValues = append(it.HashValues, hash)
			}
		}
	} else {
		// use primary keys as hash if hash is not provided
		// in this case, primary field is required, we have already checked this
		if uint32(len(it.HashValues)) != 0 && uint32(len(it.HashValues)) != rowNums {
			return fmt.Errorf("invalid length of input hash values")
		}
		if it.HashValues == nil || len(it.HashValues) <= 0 {
			it.HashValues = make([]uint32, 0, len(primaryData))
			for _, pk := range primaryData {
				hash, _ := typeutil.Hash32Int64(pk)
				it.HashValues = append(it.HashValues, hash)
			}
		}
	}

	sliceIndex := make([]uint32, rowNums)
	for i := uint32(0); i < rowNums; i++ {
		sliceIndex[i] = i
	}
	it.result.SuccIndex = sliceIndex

	return nil
}

S
sunby 已提交
583
func (it *InsertTask) PreExecute(ctx context.Context) error {
584
	it.Base.MsgType = commonpb.MsgType_Insert
585
	it.Base.SourceID = Params.ProxyID
586

587 588 589 590 591 592 593 594 595 596
	it.result = &milvuspb.MutationResult{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		IDs: &schemapb.IDs{
			IdField: nil,
		},
		Timestamp: it.BeginTs(),
	}

N
neza2017 已提交
597 598 599 600
	collectionName := it.BaseInsertTask.CollectionName
	if err := ValidateCollectionName(collectionName); err != nil {
		return err
	}
601

602
	partitionTag := it.BaseInsertTask.PartitionName
N
neza2017 已提交
603 604 605 606
	if err := ValidatePartitionTag(partitionTag, true); err != nil {
		return err
	}

607
	collSchema, err := globalMetaCache.GetCollectionSchema(ctx, collectionName)
C
Cai Yudong 已提交
608
	log.Debug("Proxy Insert PreExecute", zap.Any("collSchema", collSchema))
609 610 611 612 613 614 615 616 617 618 619
	if err != nil {
		return err
	}
	it.schema = collSchema

	err = it.checkFieldAutoID()
	if err != nil {
		return err
	}

	err = it.transferColumnBasedRequestToRowBasedData()
620 621 622 623 624 625 626 627 628 629
	if err != nil {
		return err
	}

	rowNum := len(it.RowData)
	it.Timestamps = make([]uint64, rowNum)
	for index := range it.Timestamps {
		it.Timestamps[index] = it.BeginTimestamp
	}

630 631 632
	return nil
}

633 634 635 636 637 638 639 640 641 642 643 644 645
func (it *InsertTask) _assignSegmentID(stream msgstream.MsgStream, pack *msgstream.MsgPack) (*msgstream.MsgPack, error) {
	newPack := &msgstream.MsgPack{
		BeginTs:        pack.BeginTs,
		EndTs:          pack.EndTs,
		StartPositions: pack.StartPositions,
		EndPositions:   pack.EndPositions,
		Msgs:           nil,
	}
	tsMsgs := pack.Msgs
	hashKeys := stream.ComputeProduceChannelIndexes(tsMsgs)
	reqID := it.Base.MsgID
	channelCountMap := make(map[int32]uint32)    //   channelID to count
	channelMaxTSMap := make(map[int32]Timestamp) //  channelID to max Timestamp
646 647 648 649
	channelNames, err := it.chMgr.getVChannels(it.GetCollectionID())
	if err != nil {
		return nil, err
	}
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
	log.Debug("_assignSemgentID, produceChannels:", zap.Any("Channels", channelNames))

	for i, request := range tsMsgs {
		if request.Type() != commonpb.MsgType_Insert {
			return nil, fmt.Errorf("msg's must be Insert")
		}
		insertRequest, ok := request.(*msgstream.InsertMsg)
		if !ok {
			return nil, fmt.Errorf("msg's must be Insert")
		}

		keys := hashKeys[i]
		timestampLen := len(insertRequest.Timestamps)
		rowIDLen := len(insertRequest.RowIDs)
		rowDataLen := len(insertRequest.RowData)
		keysLen := len(keys)

		if keysLen != timestampLen || keysLen != rowIDLen || keysLen != rowDataLen {
			return nil, fmt.Errorf("the length of hashValue, timestamps, rowIDs, RowData are not equal")
		}

		for idx, channelID := range keys {
			channelCountMap[channelID]++
			if _, ok := channelMaxTSMap[channelID]; !ok {
				channelMaxTSMap[channelID] = typeutil.ZeroTimestamp
			}
			ts := insertRequest.Timestamps[idx]
			if channelMaxTSMap[channelID] < ts {
				channelMaxTSMap[channelID] = ts
			}
		}
	}

	reqSegCountMap := make(map[int32]map[UniqueID]uint32)

	for channelID, count := range channelCountMap {
		ts, ok := channelMaxTSMap[channelID]
		if !ok {
			ts = typeutil.ZeroTimestamp
			log.Debug("Warning: did not get max Timestamp!")
		}
		channelName := channelNames[channelID]
		if channelName == "" {
C
Cai Yudong 已提交
693
			return nil, fmt.Errorf("Proxy, repack_func, can not found channelName")
694 695 696 697 698 699 700
		}
		mapInfo, err := it.segIDAssigner.GetSegmentID(it.CollectionID, it.PartitionID, channelName, count, ts)
		if err != nil {
			return nil, err
		}
		reqSegCountMap[channelID] = make(map[UniqueID]uint32)
		reqSegCountMap[channelID] = mapInfo
C
Cai Yudong 已提交
701
		log.Debug("Proxy", zap.Int64("repackFunc, reqSegCountMap, reqID", reqID), zap.Any("mapinfo", mapInfo))
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	}

	reqSegAccumulateCountMap := make(map[int32][]uint32)
	reqSegIDMap := make(map[int32][]UniqueID)
	reqSegAllocateCounter := make(map[int32]uint32)

	for channelID, segInfo := range reqSegCountMap {
		reqSegAllocateCounter[channelID] = 0
		keys := make([]UniqueID, len(segInfo))
		i := 0
		for key := range segInfo {
			keys[i] = key
			i++
		}
		sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
		accumulate := uint32(0)
		for _, key := range keys {
			accumulate += segInfo[key]
			if _, ok := reqSegAccumulateCountMap[channelID]; !ok {
				reqSegAccumulateCountMap[channelID] = make([]uint32, 0)
			}
			reqSegAccumulateCountMap[channelID] = append(
				reqSegAccumulateCountMap[channelID],
				accumulate,
			)
			if _, ok := reqSegIDMap[channelID]; !ok {
				reqSegIDMap[channelID] = make([]UniqueID, 0)
			}
			reqSegIDMap[channelID] = append(
				reqSegIDMap[channelID],
				key,
			)
		}
	}

	var getSegmentID = func(channelID int32) UniqueID {
		reqSegAllocateCounter[channelID]++
		cur := reqSegAllocateCounter[channelID]
		accumulateSlice := reqSegAccumulateCountMap[channelID]
		segIDSlice := reqSegIDMap[channelID]
		for index, count := range accumulateSlice {
			if cur <= count {
				return segIDSlice[index]
			}
		}
		log.Warn("Can't Found SegmentID")
		return 0
	}

	factor := 10
	threshold := Params.PulsarMaxMessageSize / factor
C
Cai Yudong 已提交
753
	log.Debug("Proxy", zap.Int("threshold of message size: ", threshold))
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
	// not accurate
	getFixedSizeOfInsertMsg := func(msg *msgstream.InsertMsg) int {
		size := 0

		size += int(unsafe.Sizeof(*msg.Base))
		size += int(unsafe.Sizeof(msg.DbName))
		size += int(unsafe.Sizeof(msg.CollectionName))
		size += int(unsafe.Sizeof(msg.PartitionName))
		size += int(unsafe.Sizeof(msg.DbID))
		size += int(unsafe.Sizeof(msg.CollectionID))
		size += int(unsafe.Sizeof(msg.PartitionID))
		size += int(unsafe.Sizeof(msg.SegmentID))
		size += int(unsafe.Sizeof(msg.ChannelID))
		size += int(unsafe.Sizeof(msg.Timestamps))
		size += int(unsafe.Sizeof(msg.RowIDs))
		return size
	}

	result := make(map[int32]msgstream.TsMsg)
	curMsgSizeMap := make(map[int32]int)

	for i, request := range tsMsgs {
		insertRequest := request.(*msgstream.InsertMsg)
		keys := hashKeys[i]
		collectionName := insertRequest.CollectionName
		collectionID := insertRequest.CollectionID
		partitionID := insertRequest.PartitionID
		partitionName := insertRequest.PartitionName
		proxyID := insertRequest.Base.SourceID
		for index, key := range keys {
			ts := insertRequest.Timestamps[index]
			rowID := insertRequest.RowIDs[index]
			row := insertRequest.RowData[index]
			segmentID := getSegmentID(key)
			_, ok := result[key]
			if !ok {
				sliceRequest := internalpb.InsertRequest{
					Base: &commonpb.MsgBase{
						MsgType:   commonpb.MsgType_Insert,
						MsgID:     reqID,
						Timestamp: ts,
						SourceID:  proxyID,
					},
					CollectionID:   collectionID,
					PartitionID:    partitionID,
					CollectionName: collectionName,
					PartitionName:  partitionName,
					SegmentID:      segmentID,
					// todo rename to ChannelName
					ChannelID: channelNames[key],
				}
				insertMsg := &msgstream.InsertMsg{
					BaseMsg: msgstream.BaseMsg{
						Ctx: request.TraceCtx(),
					},
					InsertRequest: sliceRequest,
				}
				result[key] = insertMsg
				curMsgSizeMap[key] = getFixedSizeOfInsertMsg(insertMsg)
			}
			curMsg := result[key].(*msgstream.InsertMsg)
			curMsgSize := curMsgSizeMap[key]
			curMsg.HashValues = append(curMsg.HashValues, insertRequest.HashValues[index])
			curMsg.Timestamps = append(curMsg.Timestamps, ts)
			curMsg.RowIDs = append(curMsg.RowIDs, rowID)
			curMsg.RowData = append(curMsg.RowData, row)
			curMsgSize += 4 + 8 + int(unsafe.Sizeof(row.Value))
			curMsgSize += len(row.Value)

			if curMsgSize >= threshold {
				newPack.Msgs = append(newPack.Msgs, curMsg)
				delete(result, key)
				curMsgSize = 0
			}

			curMsgSizeMap[key] = curMsgSize
		}
	}
	for _, msg := range result {
		if msg != nil {
			newPack.Msgs = append(newPack.Msgs, msg)
		}
	}

	return newPack, nil
}

S
sunby 已提交
841
func (it *InsertTask) Execute(ctx context.Context) error {
842
	collectionName := it.BaseInsertTask.CollectionName
G
godchen 已提交
843
	collID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
G
godchen 已提交
844
	if err != nil {
845 846
		return err
	}
G
godchen 已提交
847
	it.CollectionID = collID
848 849
	var partitionID UniqueID
	if len(it.PartitionName) > 0 {
G
godchen 已提交
850
		partitionID, err = globalMetaCache.GetPartitionID(ctx, collectionName, it.PartitionName)
851 852 853 854
		if err != nil {
			return err
		}
	} else {
855
		partitionID, err = globalMetaCache.GetPartitionID(ctx, collectionName, Params.DefaultPartitionName)
856 857 858
		if err != nil {
			return err
		}
G
godchen 已提交
859 860
	}
	it.PartitionID = partitionID
861

862
	var tsMsg msgstream.TsMsg = &it.BaseInsertTask
863 864
	it.BaseMsg.Ctx = ctx
	msgPack := msgstream.MsgPack{
865 866
		BeginTs: it.BeginTs(),
		EndTs:   it.EndTs(),
X
xige-16 已提交
867
		Msgs:    make([]msgstream.TsMsg, 1),
868
	}
G
godchen 已提交
869

870 871
	msgPack.Msgs[0] = tsMsg

872
	stream, err := it.chMgr.getDMLStream(collID)
873
	if err != nil {
874
		err = it.chMgr.createDMLMsgStream(collID)
875
		if err != nil {
876 877 878 879 880 881 882 883
			it.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			it.result.Status.Reason = err.Error()
			return err
		}
		stream, err = it.chMgr.getDMLStream(collID)
		if err != nil {
			it.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			it.result.Status.Reason = err.Error()
884 885 886 887
			return err
		}
	}

888 889 890 891 892
	pchans, err := it.chMgr.getChannels(collID)
	if err != nil {
		return err
	}
	for _, pchan := range pchans {
C
Cai Yudong 已提交
893
		log.Debug("Proxy InsertTask add pchan", zap.Any("pchan", pchan))
894 895 896
		_ = it.chTicker.addPChan(pchan)
	}

897 898 899 900 901 902 903 904
	// Assign SegmentID
	var pack *msgstream.MsgPack
	pack, err = it._assignSegmentID(stream, &msgPack)
	if err != nil {
		return err
	}

	err = stream.Produce(pack)
905
	if err != nil {
906
		it.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
907
		it.result.Status.Reason = err.Error()
908
		return err
909
	}
910

911 912 913
	return nil
}

S
sunby 已提交
914
func (it *InsertTask) PostExecute(ctx context.Context) error {
915 916 917 918
	return nil
}

type CreateCollectionTask struct {
D
dragondriver 已提交
919
	Condition
920
	*milvuspb.CreateCollectionRequest
921 922 923 924 925
	ctx             context.Context
	rootCoord       types.RootCoord
	dataCoordClient types.DataCoord
	result          *commonpb.Status
	schema          *schemapb.CollectionSchema
926 927
}

928
func (cct *CreateCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
929
	return cct.ctx
930 931
}

C
cai.zhang 已提交
932
func (cct *CreateCollectionTask) ID() UniqueID {
933
	return cct.Base.MsgID
934 935
}

936
func (cct *CreateCollectionTask) SetID(uid UniqueID) {
937
	cct.Base.MsgID = uid
938 939
}

S
sunby 已提交
940 941 942 943
func (cct *CreateCollectionTask) Name() string {
	return CreateCollectionTaskName
}

944
func (cct *CreateCollectionTask) Type() commonpb.MsgType {
945
	return cct.Base.MsgType
946 947 948
}

func (cct *CreateCollectionTask) BeginTs() Timestamp {
949
	return cct.Base.Timestamp
950 951 952
}

func (cct *CreateCollectionTask) EndTs() Timestamp {
953
	return cct.Base.Timestamp
954 955 956
}

func (cct *CreateCollectionTask) SetTs(ts Timestamp) {
957
	cct.Base.Timestamp = ts
958 959
}

S
sunby 已提交
960 961 962 963 964 965
func (cct *CreateCollectionTask) OnEnqueue() error {
	cct.Base = &commonpb.MsgBase{}
	return nil
}

func (cct *CreateCollectionTask) PreExecute(ctx context.Context) error {
966
	cct.Base.MsgType = commonpb.MsgType_CreateCollection
967
	cct.Base.SourceID = Params.ProxyID
968 969 970

	cct.schema = &schemapb.CollectionSchema{}
	err := proto.Unmarshal(cct.Schema, cct.schema)
971 972
	cct.schema.AutoID = false
	cct.CreateCollectionRequest.Schema, _ = proto.Marshal(cct.schema)
973 974 975 976
	if err != nil {
		return err
	}

977
	if int64(len(cct.schema.Fields)) > Params.MaxFieldNum {
S
sunby 已提交
978
		return fmt.Errorf("maximum field's number should be limited to %d", Params.MaxFieldNum)
N
neza2017 已提交
979 980 981 982 983 984 985
	}

	// validate collection name
	if err := ValidateCollectionName(cct.schema.Name); err != nil {
		return err
	}

N
neza2017 已提交
986 987 988 989 990 991 992 993
	if err := ValidateDuplicatedFieldName(cct.schema.Fields); err != nil {
		return err
	}

	if err := ValidatePrimaryKey(cct.schema); err != nil {
		return err
	}

994 995 996 997
	if err := ValidateFieldAutoID(cct.schema); err != nil {
		return err
	}

N
neza2017 已提交
998 999 1000 1001 1002
	// validate field name
	for _, field := range cct.schema.Fields {
		if err := ValidateFieldName(field.Name); err != nil {
			return err
		}
G
godchen 已提交
1003
		if field.DataType == schemapb.DataType_FloatVector || field.DataType == schemapb.DataType_BinaryVector {
N
neza2017 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
			exist := false
			var dim int64 = 0
			for _, param := range field.TypeParams {
				if param.Key == "dim" {
					exist = true
					tmp, err := strconv.ParseInt(param.Value, 10, 64)
					if err != nil {
						return err
					}
					dim = tmp
					break
				}
			}
			if !exist {
				return errors.New("dimension is not defined in field type params")
			}
G
godchen 已提交
1020
			if field.DataType == schemapb.DataType_FloatVector {
N
neza2017 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
				if err := ValidateDimension(dim, false); err != nil {
					return err
				}
			} else {
				if err := ValidateDimension(dim, true); err != nil {
					return err
				}
			}
		}
	}

1032
	return nil
Z
zhenshan.cao 已提交
1033 1034
}

S
sunby 已提交
1035
func (cct *CreateCollectionTask) Execute(ctx context.Context) error {
1036
	var err error
1037
	cct.result, err = cct.rootCoord.CreateCollection(ctx, cct.CreateCollectionRequest)
1038
	return err
Z
zhenshan.cao 已提交
1039 1040
}

S
sunby 已提交
1041
func (cct *CreateCollectionTask) PostExecute(ctx context.Context) error {
1042
	return nil
Z
zhenshan.cao 已提交
1043 1044
}

1045
type DropCollectionTask struct {
D
dragondriver 已提交
1046
	Condition
1047
	*milvuspb.DropCollectionRequest
1048 1049 1050 1051 1052
	ctx       context.Context
	rootCoord types.RootCoord
	result    *commonpb.Status
	chMgr     channelsMgr
	chTicker  channelsTimeTicker
1053 1054
}

1055
func (dct *DropCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
1056
	return dct.ctx
1057 1058
}

C
cai.zhang 已提交
1059
func (dct *DropCollectionTask) ID() UniqueID {
1060
	return dct.Base.MsgID
1061 1062
}

1063
func (dct *DropCollectionTask) SetID(uid UniqueID) {
1064
	dct.Base.MsgID = uid
1065 1066
}

S
sunby 已提交
1067 1068 1069 1070
func (dct *DropCollectionTask) Name() string {
	return DropCollectionTaskName
}

1071
func (dct *DropCollectionTask) Type() commonpb.MsgType {
1072
	return dct.Base.MsgType
1073 1074 1075
}

func (dct *DropCollectionTask) BeginTs() Timestamp {
1076
	return dct.Base.Timestamp
1077 1078 1079
}

func (dct *DropCollectionTask) EndTs() Timestamp {
1080
	return dct.Base.Timestamp
1081 1082 1083
}

func (dct *DropCollectionTask) SetTs(ts Timestamp) {
1084
	dct.Base.Timestamp = ts
1085 1086
}

S
sunby 已提交
1087 1088 1089 1090 1091 1092
func (dct *DropCollectionTask) OnEnqueue() error {
	dct.Base = &commonpb.MsgBase{}
	return nil
}

func (dct *DropCollectionTask) PreExecute(ctx context.Context) error {
1093
	dct.Base.MsgType = commonpb.MsgType_DropCollection
1094
	dct.Base.SourceID = Params.ProxyID
1095

1096
	if err := ValidateCollectionName(dct.CollectionName); err != nil {
N
neza2017 已提交
1097 1098
		return err
	}
1099 1100 1101
	return nil
}

S
sunby 已提交
1102
func (dct *DropCollectionTask) Execute(ctx context.Context) error {
G
godchen 已提交
1103
	collID, err := globalMetaCache.GetCollectionID(ctx, dct.CollectionName)
1104 1105 1106
	if err != nil {
		return err
	}
S
sunby 已提交
1107

1108
	dct.result, err = dct.rootCoord.DropCollection(ctx, dct.DropCollectionRequest)
S
sunby 已提交
1109 1110
	if err != nil {
		return err
1111
	}
S
sunby 已提交
1112

S
sunby 已提交
1113 1114 1115
	pchans, _ := dct.chMgr.getChannels(collID)
	for _, pchan := range pchans {
		_ = dct.chTicker.removePChan(pchan)
G
godchen 已提交
1116
	}
S
sunby 已提交
1117

S
sunby 已提交
1118
	_ = dct.chMgr.removeDMLStream(collID)
1119
	_ = dct.chMgr.removeDQLStream(collID)
S
sunby 已提交
1120

G
godchen 已提交
1121
	return nil
1122 1123
}

S
sunby 已提交
1124
func (dct *DropCollectionTask) PostExecute(ctx context.Context) error {
G
godchen 已提交
1125
	globalMetaCache.RemoveCollection(ctx, dct.CollectionName)
Z
zhenshan.cao 已提交
1126
	return nil
1127 1128
}

1129
type SearchTask struct {
D
dragondriver 已提交
1130
	Condition
G
godchen 已提交
1131
	*internalpb.SearchRequest
1132 1133 1134 1135 1136
	ctx       context.Context
	resultBuf chan []*internalpb.SearchResults
	result    *milvuspb.SearchResults
	query     *milvuspb.SearchRequest
	chMgr     channelsMgr
1137
	qc        types.QueryCoord
1138 1139
}

1140
func (st *SearchTask) TraceCtx() context.Context {
S
sunby 已提交
1141
	return st.ctx
1142 1143
}

1144 1145
func (st *SearchTask) ID() UniqueID {
	return st.Base.MsgID
1146 1147
}

1148 1149
func (st *SearchTask) SetID(uid UniqueID) {
	st.Base.MsgID = uid
1150 1151
}

S
sunby 已提交
1152 1153 1154 1155
func (st *SearchTask) Name() string {
	return SearchTaskName
}

1156 1157
func (st *SearchTask) Type() commonpb.MsgType {
	return st.Base.MsgType
1158 1159
}

1160 1161
func (st *SearchTask) BeginTs() Timestamp {
	return st.Base.Timestamp
1162 1163
}

1164 1165
func (st *SearchTask) EndTs() Timestamp {
	return st.Base.Timestamp
1166 1167
}

1168 1169
func (st *SearchTask) SetTs(ts Timestamp) {
	st.Base.Timestamp = ts
1170 1171
}

S
sunby 已提交
1172
func (st *SearchTask) OnEnqueue() error {
D
dragondriver 已提交
1173
	st.Base = &commonpb.MsgBase{}
S
sunby 已提交
1174 1175 1176
	return nil
}

1177
func (st *SearchTask) getChannels() ([]pChan, error) {
1178 1179 1180 1181 1182 1183 1184 1185
	collID, err := globalMetaCache.GetCollectionID(st.ctx, st.query.CollectionName)
	if err != nil {
		return nil, err
	}

	return st.chMgr.getChannels(collID)
}

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
func (st *SearchTask) getVChannels() ([]vChan, error) {
	collID, err := globalMetaCache.GetCollectionID(st.ctx, st.query.CollectionName)
	if err != nil {
		return nil, err
	}

	_, err = st.chMgr.getChannels(collID)
	if err != nil {
		err := st.chMgr.createDMLMsgStream(collID)
		if err != nil {
			return nil, err
		}
	}

	return st.chMgr.getVChannels(collID)
}

S
sunby 已提交
1203
func (st *SearchTask) PreExecute(ctx context.Context) error {
1204
	st.Base.MsgType = commonpb.MsgType_Search
1205
	st.Base.SourceID = Params.ProxyID
1206

1207
	collectionName := st.query.CollectionName
1208
	collID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
1209 1210 1211 1212
	if err != nil { // err is not nil if collection not exists
		return err
	}

1213
	if err := ValidateCollectionName(st.query.CollectionName); err != nil {
N
neza2017 已提交
1214 1215 1216
		return err
	}

1217
	for _, tag := range st.query.PartitionNames {
N
neza2017 已提交
1218 1219 1220 1221
		if err := ValidatePartitionTag(tag, false); err != nil {
			return err
		}
	}
1222 1223

	// check if collection was already loaded into query node
1224
	showResp, err := st.qc.ShowCollections(st.ctx, &querypb.ShowCollectionsRequest{
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowCollections,
			MsgID:     st.Base.MsgID,
			Timestamp: st.Base.Timestamp,
			SourceID:  Params.ProxyID,
		},
		DbID: 0, // TODO(dragondriver)
	})
	if err != nil {
		return err
	}
	if showResp.Status.ErrorCode != commonpb.ErrorCode_Success {
		return errors.New(showResp.Status.Reason)
	}
1239
	log.Debug("query coordinator show collections",
1240
		zap.Any("collID", collID),
1241
		zap.Any("collections", showResp.CollectionIDs),
1242
	)
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
	collectionLoaded := false
	for _, collectionID := range showResp.CollectionIDs {
		if collectionID == collID {
			collectionLoaded = true
			break
		}
	}
	if !collectionLoaded {
		return fmt.Errorf("collection %v was not loaded into memory", collectionName)
	}

	// TODO(dragondriver): necessary to check if partition was loaded into query node?

1256
	st.Base.MsgType = commonpb.MsgType_Search
1257

1258 1259 1260 1261
	schema, err := globalMetaCache.GetCollectionSchema(ctx, collectionName)
	if err != nil { // err is not nil if collection not exists
		return err
	}
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
	if st.query.GetDslType() == commonpb.DslType_BoolExprV1 {
		annsField, err := GetAttrByKeyFromRepeatedKV(AnnsFieldKey, st.query.SearchParams)
		if err != nil {
			return errors.New(AnnsFieldKey + " not found in search_params")
		}

		topKStr, err := GetAttrByKeyFromRepeatedKV(TopKKey, st.query.SearchParams)
		if err != nil {
			return errors.New(TopKKey + " not found in search_params")
		}
		topK, err := strconv.Atoi(topKStr)
		if err != nil {
			return errors.New(TopKKey + " " + topKStr + " is not invalid")
		}

		metricType, err := GetAttrByKeyFromRepeatedKV(MetricTypeKey, st.query.SearchParams)
		if err != nil {
			return errors.New(MetricTypeKey + " not found in search_params")
		}

		searchParams, err := GetAttrByKeyFromRepeatedKV(SearchParamsKey, st.query.SearchParams)
		if err != nil {
			return errors.New(SearchParamsKey + " not found in search_params")
		}

		queryInfo := &planpb.QueryInfo{
			Topk:         int64(topK),
			MetricType:   metricType,
			SearchParams: searchParams,
		}

C
cai.zhang 已提交
1293
		plan, err := CreateQueryPlan(schema, st.query.Dsl, annsField, queryInfo)
1294
		if err != nil {
1295 1296
			//return errors.New("invalid expression: " + st.query.Dsl)
			return err
1297
		}
Y
yukun 已提交
1298 1299
		for _, name := range st.query.OutputFields {
			for _, field := range schema.Fields {
1300
				if field.Name == name {
Y
yukun 已提交
1301 1302 1303 1304
					if field.DataType == schemapb.DataType_BinaryVector || field.DataType == schemapb.DataType_FloatVector {
						return errors.New("Search doesn't support vector field as output_fields")
					}

1305 1306 1307 1308 1309 1310
					st.SearchRequest.OutputFieldsId = append(st.SearchRequest.OutputFieldsId, field.FieldID)
					plan.OutputFieldIds = append(plan.OutputFieldIds, field.FieldID)
				}
			}
		}

1311
		st.SearchRequest.DslType = commonpb.DslType_BoolExprV1
1312 1313 1314 1315
		st.SearchRequest.SerializedExprPlan, err = proto.Marshal(plan)
		if err != nil {
			return err
		}
1316
	}
1317 1318 1319 1320
	travelTimestamp := st.query.TravelTimestamp
	if travelTimestamp == 0 {
		travelTimestamp = st.BeginTs()
	}
1321 1322 1323 1324
	guaranteeTimestamp := st.query.GuaranteeTimestamp
	if guaranteeTimestamp == 0 {
		guaranteeTimestamp = st.BeginTs()
	}
1325
	st.SearchRequest.TravelTimestamp = travelTimestamp
1326
	st.SearchRequest.GuaranteeTimestamp = guaranteeTimestamp
1327

1328 1329
	st.SearchRequest.ResultChannelID = Params.SearchResultChannelNames[0]
	st.SearchRequest.DbID = 0 // todo
G
godchen 已提交
1330
	collectionID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
1331 1332 1333
	if err != nil { // err is not nil if collection not exists
		return err
	}
1334 1335
	st.SearchRequest.CollectionID = collectionID
	st.SearchRequest.PartitionIDs = make([]UniqueID, 0)
Z
zhenshan.cao 已提交
1336 1337 1338 1339 1340 1341 1342

	partitionsMap, err := globalMetaCache.GetPartitions(ctx, collectionName)
	if err != nil {
		return err
	}

	partitionsRecord := make(map[UniqueID]bool)
1343
	for _, partitionName := range st.query.PartitionNames {
Z
zhenshan.cao 已提交
1344 1345
		pattern := fmt.Sprintf("^%s$", partitionName)
		re, err := regexp.Compile(pattern)
1346
		if err != nil {
Z
zhenshan.cao 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
			return errors.New("invalid partition names")
		}
		found := false
		for name, pID := range partitionsMap {
			if re.MatchString(name) {
				if _, exist := partitionsRecord[pID]; !exist {
					st.PartitionIDs = append(st.PartitionIDs, pID)
					partitionsRecord[pID] = true
				}
				found = true
			}
		}
		if !found {
			errMsg := fmt.Sprintf("PartitonName: %s not found", partitionName)
			return errors.New(errMsg)
1362 1363
		}
	}
Z
zhenshan.cao 已提交
1364

1365 1366
	st.SearchRequest.Dsl = st.query.Dsl
	st.SearchRequest.PlaceholderGroup = st.query.PlaceholderGroup
1367

1368 1369 1370
	return nil
}

S
sunby 已提交
1371
func (st *SearchTask) Execute(ctx context.Context) error {
1372
	var tsMsg msgstream.TsMsg = &msgstream.SearchMsg{
S
sunby 已提交
1373
		SearchRequest: *st.SearchRequest,
1374
		BaseMsg: msgstream.BaseMsg{
1375
			Ctx:            ctx,
1376
			HashValues:     []uint32{uint32(Params.ProxyID)},
1377 1378
			BeginTimestamp: st.Base.Timestamp,
			EndTimestamp:   st.Base.Timestamp,
1379 1380
		},
	}
1381
	msgPack := msgstream.MsgPack{
1382 1383
		BeginTs: st.Base.Timestamp,
		EndTs:   st.Base.Timestamp,
X
xige-16 已提交
1384
		Msgs:    make([]msgstream.TsMsg, 1),
1385
	}
X
xige-16 已提交
1386
	msgPack.Msgs[0] = tsMsg
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

	collectionName := st.query.CollectionName
	collID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
	if err != nil { // err is not nil if collection not exists
		return err
	}

	stream, err := st.chMgr.getDQLStream(collID)
	if err != nil {
		err = st.chMgr.createDQLStream(collID)
		if err != nil {
			st.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			st.result.Status.Reason = err.Error()
			return err
		}
		stream, err = st.chMgr.getDQLStream(collID)
		if err != nil {
			st.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			st.result.Status.Reason = err.Error()
			return err
		}
	}
	err = stream.Produce(&msgPack)
C
Cai Yudong 已提交
1410 1411
	log.Debug("proxy", zap.Int("length of searchMsg", len(msgPack.Msgs)))
	log.Debug("proxy sent one searchMsg",
1412
		zap.Any("collectionID", st.CollectionID),
Z
zhenshan.cao 已提交
1413
		zap.Any("msgID", tsMsg.ID()),
1414
	)
C
cai.zhang 已提交
1415
	if err != nil {
C
Cai Yudong 已提交
1416
		log.Debug("proxy", zap.String("send search request failed", err.Error()))
C
cai.zhang 已提交
1417 1418
	}
	return err
1419 1420
}

1421 1422 1423 1424
// TODO: add benchmark to compare with serial implementation
func decodeSearchResultsParallel(searchResults []*internalpb.SearchResults, maxParallel int) ([][]*milvuspb.Hits, error) {
	log.Debug("decodeSearchResultsParallel", zap.Any("NumOfGoRoutines", maxParallel))

1425
	hits := make([][]*milvuspb.Hits, 0)
1426
	// necessary to parallel this?
1427 1428 1429 1430 1431
	for _, partialSearchResult := range searchResults {
		if partialSearchResult.Hits == nil || len(partialSearchResult.Hits) <= 0 {
			continue
		}

1432 1433
		nq := len(partialSearchResult.Hits)
		partialHits := make([]*milvuspb.Hits, nq)
1434

1435 1436
		f := func(idx int) error {
			partialHit := &milvuspb.Hits{}
1437

1438 1439 1440 1441
			err := proto.Unmarshal(partialSearchResult.Hits[idx], partialHit)
			if err != nil {
				return err
			}
1442

1443
			partialHits[idx] = partialHit
1444

1445
			return nil
1446 1447
		}

1448
		err := funcutil.ProcessFuncParallel(nq, maxParallel, f, "decodePartialSearchResult")
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

		if err != nil {
			return nil, err
		}

		hits = append(hits, partialHits)
	}

	return hits, nil
}

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
func decodeSearchResultsSerial(searchResults []*internalpb.SearchResults) ([]*schemapb.SearchResultData, error) {
	results := make([]*schemapb.SearchResultData, 0)
	// necessary to parallel this?
	for _, partialSearchResult := range searchResults {
		if partialSearchResult.SlicedBlob == nil {
			continue
		}

		var partialResultData schemapb.SearchResultData
		err := proto.Unmarshal(partialSearchResult.SlicedBlob, &partialResultData)
		if err != nil {
			return nil, err
		}

		results = append(results, &partialResultData)
	}

	return results, nil
1478
}
1479

1480 1481 1482 1483
// TODO: add benchmark to compare with serial implementation
func decodeSearchResultsParallelByNq(searchResults []*internalpb.SearchResults) ([][]*milvuspb.Hits, error) {
	if len(searchResults) <= 0 {
		return nil, errors.New("no need to decode empty search results")
1484
	}
1485 1486 1487
	nq := len(searchResults[0].Hits)
	return decodeSearchResultsParallel(searchResults, nq)
}
1488

1489 1490 1491
// TODO: add benchmark to compare with serial implementation
func decodeSearchResultsParallelByCPU(searchResults []*internalpb.SearchResults) ([][]*milvuspb.Hits, error) {
	return decodeSearchResultsParallel(searchResults, runtime.NumCPU())
1492 1493
}

1494
func decodeSearchResults(searchResults []*internalpb.SearchResults) ([]*schemapb.SearchResultData, error) {
1495 1496 1497 1498
	t := time.Now()
	defer func() {
		log.Debug("decodeSearchResults", zap.Any("time cost", time.Since(t)))
	}()
1499 1500
	return decodeSearchResultsSerial(searchResults)
	// return decodeSearchResultsParallelByCPU(searchResults)
1501 1502
}

1503 1504 1505
func reduceSearchResultsParallel(hits [][]*milvuspb.Hits, nq, availableQueryNodeNum, topk int, metricType string, maxParallel int) *milvuspb.SearchResults {
	log.Debug("reduceSearchResultsParallel", zap.Any("NumOfGoRoutines", maxParallel))

1506 1507 1508 1509 1510 1511 1512 1513
	ret := &milvuspb.SearchResults{
		Status: &commonpb.Status{
			ErrorCode: 0,
		},
	}

	const minFloat32 = -1 * float32(math.MaxFloat32)

1514 1515 1516 1517 1518 1519 1520
	f := func(idx int) error {
		locs := make([]int, availableQueryNodeNum)
		reducedHits := &milvuspb.Hits{
			IDs:     make([]int64, 0),
			RowData: make([][]byte, 0),
			Scores:  make([]float32, 0),
		}
1521

1522 1523 1524 1525 1526 1527
		for j := 0; j < topk; j++ {
			valid := false
			choice, maxDistance := 0, minFloat32
			for q, loc := range locs { // query num, the number of ways to merge
				if loc >= len(hits[q][idx].IDs) {
					continue
1528
				}
1529 1530 1531 1532 1533
				distance := hits[q][idx].Scores[loc]
				if distance > maxDistance || (math.Abs(float64(distance-maxDistance)) < math.SmallestNonzeroFloat32 && choice != q) {
					choice = q
					maxDistance = distance
					valid = true
1534 1535
				}
			}
1536 1537
			if !valid {
				break
1538
			}
1539 1540 1541 1542 1543
			choiceOffset := locs[choice]
			// check if distance is valid, `invalid` here means very very big,
			// in this process, distance here is the smallest, so the rest of distance are all invalid
			if hits[choice][idx].Scores[choiceOffset] <= minFloat32 {
				break
1544
			}
1545 1546 1547
			reducedHits.IDs = append(reducedHits.IDs, hits[choice][idx].IDs[choiceOffset])
			if hits[choice][idx].RowData != nil && len(hits[choice][idx].RowData) > 0 {
				reducedHits.RowData = append(reducedHits.RowData, hits[choice][idx].RowData[choiceOffset])
1548
			}
1549 1550 1551
			reducedHits.Scores = append(reducedHits.Scores, hits[choice][idx].Scores[choiceOffset])
			locs[choice]++
		}
1552

1553 1554 1555
		if metricType != "IP" {
			for k := range reducedHits.Scores {
				reducedHits.Scores[k] *= -1
1556
			}
1557
		}
1558

1559 1560 1561 1562
		// reducedHitsBs, err := proto.Marshal(reducedHits)
		// if err != nil {
		// return err
		// }
1563

1564
		// ret.Hits[idx] = reducedHitsBs
1565

1566
		return nil
1567 1568
	}

1569 1570 1571 1572
	err := funcutil.ProcessFuncParallel(nq, maxParallel, f, "reduceSearchResults")
	if err != nil {
		return nil
	}
1573 1574 1575 1576

	return ret
}

1577
func reduceSearchResultDataParallel(searchResultData []*schemapb.SearchResultData, nq, availableQueryNodeNum, topk int, metricType string, maxParallel int) (*milvuspb.SearchResults, error) {
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
	log.Debug("reduceSearchResultDataParallel", zap.Any("NumOfGoRoutines", maxParallel))

	ret := &milvuspb.SearchResults{
		Status: &commonpb.Status{
			ErrorCode: 0,
		},
		Results: &schemapb.SearchResultData{
			NumQueries: int64(nq),
			TopK:       int64(topk),
			FieldsData: make([]*schemapb.FieldData, len(searchResultData[0].FieldsData)),
			Scores:     make([]float32, 0),
			Ids: &schemapb.IDs{
				IdField: &schemapb.IDs_IntId{
					IntId: &schemapb.LongArray{
						Data: make([]int64, 0),
					},
				},
			},
Y
yukun 已提交
1596
			Topks: make([]int64, 0),
1597 1598 1599 1600 1601 1602
		},
	}

	const minFloat32 = -1 * float32(math.MaxFloat32)

	// TODO(yukun): Use parallel function
1603
	realTopK := -1
1604 1605 1606
	for idx := 0; idx < nq; idx++ {
		locs := make([]int, availableQueryNodeNum)

1607 1608
		j := 0
		for ; j < topk; j++ {
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
			valid := false
			choice, maxDistance := 0, minFloat32
			for q, loc := range locs { // query num, the number of ways to merge
				if loc >= topk {
					continue
				}
				distance := searchResultData[q].Scores[idx*topk+loc]
				if distance > maxDistance || (math.Abs(float64(distance-maxDistance)) < math.SmallestNonzeroFloat32 && choice != q) {
					choice = q
					maxDistance = distance
					valid = true
				}
			}
			if !valid {
				break
			}
			choiceOffset := locs[choice]
			// check if distance is valid, `invalid` here means very very big,
			// in this process, distance here is the smallest, so the rest of distance are all invalid
			if searchResultData[choice].Scores[idx*topk+choiceOffset] <= minFloat32 {
				break
			}
			curIdx := idx*topk + choiceOffset
			ret.Results.Ids.GetIntId().Data = append(ret.Results.Ids.GetIntId().Data, searchResultData[choice].Ids.GetIntId().Data[curIdx])
			// TODO(yukun): Process searchResultData.FieldsData
			for k, fieldData := range searchResultData[choice].FieldsData {
				switch fieldType := fieldData.Field.(type) {
				case *schemapb.FieldData_Scalars:
					if ret.Results.FieldsData[k].GetScalars() == nil {
						ret.Results.FieldsData[k] = &schemapb.FieldData{
							FieldName: fieldData.FieldName,
							Field: &schemapb.FieldData_Scalars{
								Scalars: &schemapb.ScalarField{},
							},
						}
					}
					switch scalarType := fieldType.Scalars.Data.(type) {
					case *schemapb.ScalarField_BoolData:
						if ret.Results.FieldsData[k].GetScalars().GetBoolData() == nil {
							ret.Results.FieldsData[k].Field.(*schemapb.FieldData_Scalars).Scalars = &schemapb.ScalarField{
								Data: &schemapb.ScalarField_BoolData{
									BoolData: &schemapb.BoolArray{
										Data: []bool{scalarType.BoolData.Data[curIdx]},
									},
								},
							}
						} else {
							ret.Results.FieldsData[k].GetScalars().GetBoolData().Data = append(ret.Results.FieldsData[k].GetScalars().GetBoolData().Data, scalarType.BoolData.Data[curIdx])
						}
					case *schemapb.ScalarField_IntData:
						if ret.Results.FieldsData[k].GetScalars().GetIntData() == nil {
							ret.Results.FieldsData[k].Field.(*schemapb.FieldData_Scalars).Scalars = &schemapb.ScalarField{
								Data: &schemapb.ScalarField_IntData{
									IntData: &schemapb.IntArray{
										Data: []int32{scalarType.IntData.Data[curIdx]},
									},
								},
							}
						} else {
							ret.Results.FieldsData[k].GetScalars().GetIntData().Data = append(ret.Results.FieldsData[k].GetScalars().GetIntData().Data, scalarType.IntData.Data[curIdx])
						}
					case *schemapb.ScalarField_LongData:
						if ret.Results.FieldsData[k].GetScalars().GetLongData() == nil {
							ret.Results.FieldsData[k].Field.(*schemapb.FieldData_Scalars).Scalars = &schemapb.ScalarField{
								Data: &schemapb.ScalarField_LongData{
									LongData: &schemapb.LongArray{
										Data: []int64{scalarType.LongData.Data[curIdx]},
									},
								},
							}
						} else {
							ret.Results.FieldsData[k].GetScalars().GetLongData().Data = append(ret.Results.FieldsData[k].GetScalars().GetLongData().Data, scalarType.LongData.Data[curIdx])
						}
					case *schemapb.ScalarField_FloatData:
						if ret.Results.FieldsData[k].GetScalars().GetFloatData() == nil {
							ret.Results.FieldsData[k].Field.(*schemapb.FieldData_Scalars).Scalars = &schemapb.ScalarField{
								Data: &schemapb.ScalarField_FloatData{
									FloatData: &schemapb.FloatArray{
										Data: []float32{scalarType.FloatData.Data[curIdx]},
									},
								},
							}
						} else {
							ret.Results.FieldsData[k].GetScalars().GetFloatData().Data = append(ret.Results.FieldsData[k].GetScalars().GetFloatData().Data, scalarType.FloatData.Data[curIdx])
						}
					case *schemapb.ScalarField_DoubleData:
						if ret.Results.FieldsData[k].GetScalars().GetDoubleData() == nil {
							ret.Results.FieldsData[k].Field.(*schemapb.FieldData_Scalars).Scalars = &schemapb.ScalarField{
								Data: &schemapb.ScalarField_DoubleData{
									DoubleData: &schemapb.DoubleArray{
										Data: []float64{scalarType.DoubleData.Data[curIdx]},
									},
								},
							}
						} else {
							ret.Results.FieldsData[k].GetScalars().GetDoubleData().Data = append(ret.Results.FieldsData[k].GetScalars().GetDoubleData().Data, scalarType.DoubleData.Data[curIdx])
						}
					default:
						log.Debug("Not supported field type")
1708
						return nil, fmt.Errorf("not supported field type: %s", fieldData.Type.String())
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
					}
				case *schemapb.FieldData_Vectors:
					dim := fieldType.Vectors.Dim
					if ret.Results.FieldsData[k].GetVectors() == nil {
						ret.Results.FieldsData[k] = &schemapb.FieldData{
							FieldName: fieldData.FieldName,
							Field: &schemapb.FieldData_Vectors{
								Vectors: &schemapb.VectorField{
									Dim: dim,
								},
							},
						}
					}
					switch vectorType := fieldType.Vectors.Data.(type) {
					case *schemapb.VectorField_BinaryVector:
						if ret.Results.FieldsData[k].GetVectors().GetBinaryVector() == nil {
N
neza2017 已提交
1725 1726 1727 1728
							bvec := &schemapb.VectorField_BinaryVector{
								BinaryVector: vectorType.BinaryVector[curIdx*int((dim/8)) : (curIdx+1)*int((dim/8))],
							}
							ret.Results.FieldsData[k].GetVectors().Data = bvec
1729 1730 1731 1732 1733
						} else {
							ret.Results.FieldsData[k].GetVectors().Data.(*schemapb.VectorField_BinaryVector).BinaryVector = append(ret.Results.FieldsData[k].GetVectors().Data.(*schemapb.VectorField_BinaryVector).BinaryVector, vectorType.BinaryVector[curIdx*int((dim/8)):(curIdx+1)*int((dim/8))]...)
						}
					case *schemapb.VectorField_FloatVector:
						if ret.Results.FieldsData[k].GetVectors().GetFloatVector() == nil {
N
neza2017 已提交
1734 1735 1736 1737 1738 1739
							fvec := &schemapb.VectorField_FloatVector{
								FloatVector: &schemapb.FloatArray{
									Data: vectorType.FloatVector.Data[curIdx*int(dim) : (curIdx+1)*int(dim)],
								},
							}
							ret.Results.FieldsData[k].GetVectors().Data = fvec
1740 1741 1742 1743 1744 1745 1746 1747 1748
						} else {
							ret.Results.FieldsData[k].GetVectors().GetFloatVector().Data = append(ret.Results.FieldsData[k].GetVectors().GetFloatVector().Data, vectorType.FloatVector.Data[curIdx*int(dim):(curIdx+1)*int(dim)]...)
						}
					}
				}
			}
			ret.Results.Scores = append(ret.Results.Scores, searchResultData[choice].Scores[idx*topk+choiceOffset])
			locs[choice]++
		}
1749 1750 1751 1752 1753
		if realTopK != -1 && realTopK != j {
			log.Warn("Proxy Reduce Search Result", zap.Error(errors.New("the length (topk) between all result of query is different")))
			// return nil, errors.New("the length (topk) between all result of query is different")
		}
		realTopK = j
Y
yukun 已提交
1754
		ret.Results.Topks = append(ret.Results.Topks, int64(realTopK))
1755 1756
	}

1757 1758
	ret.Results.TopK = int64(realTopK)

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
	if metricType != "IP" {
		for k := range ret.Results.Scores {
			ret.Results.Scores[k] *= -1
		}
	}
	// err := funcutil.ProcessFuncParallel(nq, maxParallel, f, "reduceSearchResults")
	// if err != nil {
	// 	return nil
	// }

1769
	return ret, nil
1770 1771
}

1772 1773 1774
func reduceSearchResultsSerial(hits [][]*milvuspb.Hits, nq, availableQueryNodeNum, topk int, metricType string) *milvuspb.SearchResults {
	return reduceSearchResultsParallel(hits, nq, availableQueryNodeNum, topk, metricType, 1)
}
1775

1776 1777 1778 1779
// TODO: add benchmark to compare with serial implementation
func reduceSearchResultsParallelByNq(hits [][]*milvuspb.Hits, nq, availableQueryNodeNum, topk int, metricType string) *milvuspb.SearchResults {
	return reduceSearchResultsParallel(hits, nq, availableQueryNodeNum, topk, metricType, nq)
}
1780

1781 1782 1783
// TODO: add benchmark to compare with serial implementation
func reduceSearchResultsParallelByCPU(hits [][]*milvuspb.Hits, nq, availableQueryNodeNum, topk int, metricType string) *milvuspb.SearchResults {
	return reduceSearchResultsParallel(hits, nq, availableQueryNodeNum, topk, metricType, runtime.NumCPU())
1784 1785 1786
}

func reduceSearchResults(hits [][]*milvuspb.Hits, nq, availableQueryNodeNum, topk int, metricType string) *milvuspb.SearchResults {
1787 1788 1789 1790 1791
	t := time.Now()
	defer func() {
		log.Debug("reduceSearchResults", zap.Any("time cost", time.Since(t)))
	}()
	return reduceSearchResultsParallelByCPU(hits, nq, availableQueryNodeNum, topk, metricType)
1792 1793
}

1794
func reduceSearchResultData(searchResultData []*schemapb.SearchResultData, nq, availableQueryNodeNum, topk int, metricType string) (*milvuspb.SearchResults, error) {
1795 1796 1797 1798 1799 1800 1801
	t := time.Now()
	defer func() {
		log.Debug("reduceSearchResults", zap.Any("time cost", time.Since(t)))
	}()
	return reduceSearchResultDataParallel(searchResultData, nq, availableQueryNodeNum, topk, metricType, runtime.NumCPU())
}

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
func printSearchResult(partialSearchResult *internalpb.SearchResults) {
	for i := 0; i < len(partialSearchResult.Hits); i++ {
		testHits := milvuspb.Hits{}
		err := proto.Unmarshal(partialSearchResult.Hits[i], &testHits)
		if err != nil {
			panic(err)
		}
		fmt.Println(testHits.IDs)
		fmt.Println(testHits.Scores)
	}
}

S
sunby 已提交
1814
func (st *SearchTask) PostExecute(ctx context.Context) error {
1815 1816 1817 1818
	t0 := time.Now()
	defer func() {
		log.Debug("WaitAndPostExecute", zap.Any("time cost", time.Since(t0)))
	}()
1819 1820
	for {
		select {
1821
		case <-st.TraceCtx().Done():
C
Cai Yudong 已提交
1822
			log.Debug("Proxy", zap.Int64("SearchTask PostExecute Loop exit caused by ctx.Done", st.ID()))
S
sunby 已提交
1823
			return fmt.Errorf("SearchTask:wait to finish failed, timeout: %d", st.ID())
1824
		case searchResults := <-st.resultBuf:
1825
			// fmt.Println("searchResults: ", searchResults)
G
godchen 已提交
1826
			filterSearchResult := make([]*internalpb.SearchResults, 0)
Z
zhenshan.cao 已提交
1827
			var filterReason string
1828
			for _, partialSearchResult := range searchResults {
1829
				if partialSearchResult.Status.ErrorCode == commonpb.ErrorCode_Success {
1830
					filterSearchResult = append(filterSearchResult, partialSearchResult)
1831
					// For debugging, please don't delete.
1832
					// printSearchResult(partialSearchResult)
Z
zhenshan.cao 已提交
1833 1834
				} else {
					filterReason += partialSearchResult.Status.Reason + "\n"
1835 1836 1837
				}
			}

1838
			availableQueryNodeNum := len(filterSearchResult)
C
Cai Yudong 已提交
1839
			log.Debug("Proxy Search PostExecute stage1", zap.Any("availableQueryNodeNum", availableQueryNodeNum))
1840
			if availableQueryNodeNum <= 0 {
C
Cai Yudong 已提交
1841
				log.Debug("Proxy Search PostExecute failed", zap.Any("filterReason", filterReason))
1842
				st.result = &milvuspb.SearchResults{
Z
zhenshan.cao 已提交
1843
					Status: &commonpb.Status{
1844
						ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
1845 1846 1847 1848
						Reason:    filterReason,
					},
				}
				return errors.New(filterReason)
1849
			}
C
cai.zhang 已提交
1850

1851
			availableQueryNodeNum = 0
1852
			for _, partialSearchResult := range filterSearchResult {
1853
				if partialSearchResult.SlicedBlob == nil {
1854 1855 1856
					filterReason += "nq is zero\n"
					continue
				}
1857
				availableQueryNodeNum++
1858
			}
C
Cai Yudong 已提交
1859
			log.Debug("Proxy Search PostExecute stage2", zap.Any("availableQueryNodeNum", availableQueryNodeNum))
1860 1861

			if availableQueryNodeNum <= 0 {
C
Cai Yudong 已提交
1862
				log.Debug("Proxy Search PostExecute stage2 failed", zap.Any("filterReason", filterReason))
1863

1864
				st.result = &milvuspb.SearchResults{
1865
					Status: &commonpb.Status{
1866
						ErrorCode: commonpb.ErrorCode_Success,
1867 1868 1869 1870 1871 1872
						Reason:    filterReason,
					},
				}
				return nil
			}

1873
			results, err := decodeSearchResults(filterSearchResult)
C
Cai Yudong 已提交
1874
			log.Debug("Proxy Search PostExecute decodeSearchResults", zap.Error(err))
1875 1876 1877 1878
			if err != nil {
				return err
			}

1879
			nq := results[0].NumQueries
1880 1881 1882 1883
			topk := 0
			for _, partialResult := range results {
				topk = getMax(topk, int(partialResult.TopK))
			}
1884
			if nq <= 0 {
1885
				st.result = &milvuspb.SearchResults{
1886
					Status: &commonpb.Status{
1887
						ErrorCode: commonpb.ErrorCode_Success,
1888 1889
						Reason:    filterReason,
					},
N
neza2017 已提交
1890
				}
1891
				return nil
N
neza2017 已提交
1892
			}
C
cai.zhang 已提交
1893

1894 1895 1896 1897
			st.result, err = reduceSearchResultData(results, int(nq), availableQueryNodeNum, topk, searchResults[0].MetricType)
			if err != nil {
				return err
			}
1898 1899 1900 1901 1902

			schema, err := globalMetaCache.GetCollectionSchema(ctx, st.query.CollectionName)
			if err != nil {
				return err
			}
Y
yukun 已提交
1903 1904 1905 1906 1907 1908 1909
			if len(st.query.OutputFields) != 0 {
				for k, fieldName := range st.query.OutputFields {
					for _, field := range schema.Fields {
						if field.Name == fieldName {
							st.result.Results.FieldsData[k].FieldName = fieldName
							st.result.Results.FieldsData[k].Type = field.DataType
						}
1910 1911
					}
				}
B
bigsheeper 已提交
1912
			}
C
Cai Yudong 已提交
1913
			log.Debug("Proxy Search PostExecute Done")
C
cai.zhang 已提交
1914
			return nil
1915 1916
		}
	}
D
dragondriver 已提交
1917 1918
}

Y
yukun 已提交
1919 1920 1921
type RetrieveTask struct {
	Condition
	*internalpb.RetrieveRequest
1922 1923 1924 1925 1926
	ctx       context.Context
	resultBuf chan []*internalpb.RetrieveResults
	result    *milvuspb.RetrieveResults
	retrieve  *milvuspb.RetrieveRequest
	chMgr     channelsMgr
1927
	qc        types.QueryCoord
Y
yukun 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
}

func (rt *RetrieveTask) TraceCtx() context.Context {
	return rt.ctx
}

func (rt *RetrieveTask) ID() UniqueID {
	return rt.Base.MsgID
}

func (rt *RetrieveTask) SetID(uid UniqueID) {
	rt.Base.MsgID = uid
}

func (rt *RetrieveTask) Name() string {
	return RetrieveTaskName
}

func (rt *RetrieveTask) Type() commonpb.MsgType {
	return rt.Base.MsgType
}

func (rt *RetrieveTask) BeginTs() Timestamp {
	return rt.Base.Timestamp
}

func (rt *RetrieveTask) EndTs() Timestamp {
	return rt.Base.Timestamp
}

func (rt *RetrieveTask) SetTs(ts Timestamp) {
	rt.Base.Timestamp = ts
}

func (rt *RetrieveTask) OnEnqueue() error {
	rt.Base.MsgType = commonpb.MsgType_Retrieve
	return nil
}

1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
func (rt *RetrieveTask) getChannels() ([]pChan, error) {
	collID, err := globalMetaCache.GetCollectionID(rt.ctx, rt.retrieve.CollectionName)
	if err != nil {
		return nil, err
	}

	return rt.chMgr.getChannels(collID)
}

func (rt *RetrieveTask) getVChannels() ([]vChan, error) {
	collID, err := globalMetaCache.GetCollectionID(rt.ctx, rt.retrieve.CollectionName)
	if err != nil {
		return nil, err
	}

	_, err = rt.chMgr.getChannels(collID)
	if err != nil {
		err := rt.chMgr.createDMLMsgStream(collID)
		if err != nil {
			return nil, err
		}
	}

	return rt.chMgr.getVChannels(collID)
}

Y
yukun 已提交
1993 1994 1995 1996 1997 1998 1999
func (rt *RetrieveTask) PreExecute(ctx context.Context) error {
	rt.Base.MsgType = commonpb.MsgType_Retrieve
	rt.Base.SourceID = Params.ProxyID

	collectionName := rt.retrieve.CollectionName
	collectionID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
	if err != nil {
2000 2001
		log.Debug("Failed to get collection id.", zap.Any("collectionName", collectionName),
			zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2002 2003
		return err
	}
2004 2005
	log.Info("Get collection id by name.", zap.Any("collectionName", collectionName),
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2006 2007

	if err := ValidateCollectionName(rt.retrieve.CollectionName); err != nil {
2008 2009
		log.Debug("Invalid collection name.", zap.Any("collectionName", collectionName),
			zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2010 2011
		return err
	}
2012 2013
	log.Info("Validate collection name.", zap.Any("collectionName", collectionName),
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2014 2015 2016

	for _, tag := range rt.retrieve.PartitionNames {
		if err := ValidatePartitionTag(tag, false); err != nil {
2017 2018
			log.Debug("Invalid partition name.", zap.Any("partitionName", tag),
				zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2019 2020 2021
			return err
		}
	}
2022 2023
	log.Info("Validate partition names.",
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2024

2025
	// check if collection was already loaded into query node
2026
	showResp, err := rt.qc.ShowCollections(rt.ctx, &querypb.ShowCollectionsRequest{
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowCollections,
			MsgID:     rt.Base.MsgID,
			Timestamp: rt.Base.Timestamp,
			SourceID:  Params.ProxyID,
		},
		DbID: 0, // TODO(dragondriver)
	})
	if err != nil {
		return err
	}
	if showResp.Status.ErrorCode != commonpb.ErrorCode_Success {
		return errors.New(showResp.Status.Reason)
	}
2041
	log.Debug("query coordinator show collections",
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
		zap.Any("collections", showResp.CollectionIDs),
		zap.Any("collID", collectionID))
	collectionLoaded := false
	for _, collID := range showResp.CollectionIDs {
		if collectionID == collID {
			collectionLoaded = true
			break
		}
	}
	if !collectionLoaded {
		return fmt.Errorf("collection %v was not loaded into memory", collectionName)
	}

	// TODO(dragondriver): necessary to check if partition was loaded into query node?

Y
yukun 已提交
2057
	rt.Base.MsgType = commonpb.MsgType_Retrieve
2058 2059 2060 2061
	if rt.retrieve.Ids == nil {
		errMsg := "Retrieve ids is nil"
		return errors.New(errMsg)
	}
Y
yukun 已提交
2062
	rt.Ids = rt.retrieve.Ids
Y
yukun 已提交
2063 2064 2065 2066
	schema, err := globalMetaCache.GetCollectionSchema(ctx, collectionName)
	if err != nil {
		return err
	}
2067 2068
	if len(rt.retrieve.OutputFields) == 0 {
		for _, field := range schema.Fields {
2069
			if field.FieldID >= 100 && field.DataType != schemapb.DataType_FloatVector && field.DataType != schemapb.DataType_BinaryVector {
2070 2071
				rt.OutputFields = append(rt.OutputFields, field.Name)
			}
2072 2073
		}
	} else {
2074
		for _, reqField := range rt.retrieve.OutputFields {
Y
yukun 已提交
2075 2076
			findField := false
			addPrimaryKey := false
2077 2078
			for _, field := range schema.Fields {
				if reqField == field.Name {
Y
yukun 已提交
2079 2080 2081
					if field.DataType == schemapb.DataType_FloatVector || field.DataType == schemapb.DataType_BinaryVector {
						errMsg := "Query does not support vector field currently"
						return errors.New(errMsg)
2082 2083
					}
					if field.IsPrimaryKey {
Y
yukun 已提交
2084 2085 2086 2087 2088 2089
						addPrimaryKey = true
					}
					findField = true
					rt.OutputFields = append(rt.OutputFields, reqField)
				} else {
					if field.IsPrimaryKey && !addPrimaryKey {
2090
						rt.OutputFields = append(rt.OutputFields, field.Name)
Y
yukun 已提交
2091
						addPrimaryKey = true
Y
yukun 已提交
2092 2093 2094
					}
				}
			}
Y
yukun 已提交
2095 2096 2097 2098
			if !findField {
				errMsg := "Field " + reqField + " not exist"
				return errors.New(errMsg)
			}
Y
yukun 已提交
2099
		}
2100
	}
Y
yukun 已提交
2101

2102 2103 2104 2105
	travelTimestamp := rt.retrieve.TravelTimestamp
	if travelTimestamp == 0 {
		travelTimestamp = rt.BeginTs()
	}
2106 2107 2108 2109
	guaranteeTimestamp := rt.retrieve.GuaranteeTimestamp
	if guaranteeTimestamp == 0 {
		guaranteeTimestamp = rt.BeginTs()
	}
2110
	rt.RetrieveRequest.TravelTimestamp = travelTimestamp
2111
	rt.RetrieveRequest.GuaranteeTimestamp = guaranteeTimestamp
2112

2113
	rt.ResultChannelID = Params.RetrieveResultChannelNames[0]
Y
yukun 已提交
2114 2115 2116 2117 2118 2119 2120
	rt.DbID = 0 // todo(yukun)

	rt.CollectionID = collectionID
	rt.PartitionIDs = make([]UniqueID, 0)

	partitionsMap, err := globalMetaCache.GetPartitions(ctx, collectionName)
	if err != nil {
2121 2122
		log.Debug("Failed to get partitions in collection.", zap.Any("collectionName", collectionName),
			zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2123 2124
		return err
	}
2125 2126
	log.Info("Get partitions in collection.", zap.Any("collectionName", collectionName),
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2127 2128 2129 2130 2131 2132

	partitionsRecord := make(map[UniqueID]bool)
	for _, partitionName := range rt.retrieve.PartitionNames {
		pattern := fmt.Sprintf("^%s$", partitionName)
		re, err := regexp.Compile(pattern)
		if err != nil {
2133 2134
			log.Debug("Failed to compile partition name regex expression.", zap.Any("partitionName", partitionName),
				zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
			return errors.New("invalid partition names")
		}
		found := false
		for name, pID := range partitionsMap {
			if re.MatchString(name) {
				if _, exist := partitionsRecord[pID]; !exist {
					rt.PartitionIDs = append(rt.PartitionIDs, pID)
					partitionsRecord[pID] = true
				}
				found = true
			}
		}
		if !found {
2148
			// FIXME(wxyu): undefined behavior
Y
yukun 已提交
2149 2150 2151 2152 2153
			errMsg := fmt.Sprintf("PartitonName: %s not found", partitionName)
			return errors.New(errMsg)
		}
	}

2154 2155
	log.Info("Retrieve PreExecute done.",
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
	return nil
}

func (rt *RetrieveTask) Execute(ctx context.Context) error {
	var tsMsg msgstream.TsMsg = &msgstream.RetrieveMsg{
		RetrieveRequest: *rt.RetrieveRequest,
		BaseMsg: msgstream.BaseMsg{
			Ctx:            ctx,
			HashValues:     []uint32{uint32(Params.ProxyID)},
			BeginTimestamp: rt.Base.Timestamp,
			EndTimestamp:   rt.Base.Timestamp,
		},
	}
	msgPack := msgstream.MsgPack{
		BeginTs: rt.Base.Timestamp,
		EndTs:   rt.Base.Timestamp,
		Msgs:    make([]msgstream.TsMsg, 1),
	}
	msgPack.Msgs[0] = tsMsg
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197

	collectionName := rt.retrieve.CollectionName
	collID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
	if err != nil {
		return err
	}

	stream, err := rt.chMgr.getDQLStream(collID)
	if err != nil {
		err = rt.chMgr.createDQLStream(collID)
		if err != nil {
			rt.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			rt.result.Status.Reason = err.Error()
			return err
		}
		stream, err = rt.chMgr.getDQLStream(collID)
		if err != nil {
			rt.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
			rt.result.Status.Reason = err.Error()
			return err
		}
	}
	err = stream.Produce(&msgPack)
C
Cai Yudong 已提交
2198
	log.Debug("proxy", zap.Int("length of retrieveMsg", len(msgPack.Msgs)))
Y
yukun 已提交
2199
	if err != nil {
2200 2201
		log.Debug("Failed to send retrieve request.",
			zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2202
	}
2203 2204 2205

	log.Info("Retrieve Execute done.",
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
Y
yukun 已提交
2206 2207 2208
	return err
}

2209 2210 2211 2212 2213
func (rt *RetrieveTask) PostExecute(ctx context.Context) error {
	t0 := time.Now()
	defer func() {
		log.Debug("WaitAndPostExecute", zap.Any("time cost", time.Since(t0)))
	}()
2214 2215
	select {
	case <-rt.TraceCtx().Done():
C
Cai Yudong 已提交
2216
		log.Debug("proxy", zap.Int64("Retrieve: wait to finish failed, timeout!, taskID:", rt.ID()))
2217 2218 2219 2220 2221 2222 2223 2224 2225
		return fmt.Errorf("RetrieveTask:wait to finish failed, timeout : %d", rt.ID())
	case retrieveResults := <-rt.resultBuf:
		retrieveResult := make([]*internalpb.RetrieveResults, 0)
		var reason string
		for _, partialRetrieveResult := range retrieveResults {
			if partialRetrieveResult.Status.ErrorCode == commonpb.ErrorCode_Success {
				retrieveResult = append(retrieveResult, partialRetrieveResult)
			} else {
				reason += partialRetrieveResult.Status.Reason + "\n"
2226
			}
2227
		}
2228

2229 2230 2231 2232 2233 2234
		if len(retrieveResult) == 0 {
			rt.result = &milvuspb.RetrieveResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    reason,
				},
2235
			}
2236 2237 2238 2239
			log.Debug("Retrieve failed on all querynodes.",
				zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
			return errors.New(reason)
		}
2240

2241
		availableQueryNodeNum := 0
Y
yukun 已提交
2242 2243
		rt.result = &milvuspb.RetrieveResults{
			Status: &commonpb.Status{
2244
				ErrorCode: commonpb.ErrorCode_Success,
Y
yukun 已提交
2245 2246 2247 2248 2249 2250
			},
			Ids:        &schemapb.IDs{},
			FieldsData: make([]*schemapb.FieldData, 0),
		}
		for idx, partialRetrieveResult := range retrieveResult {
			log.Debug("Index-" + strconv.Itoa(idx))
2251
			availableQueryNodeNum++
2252 2253 2254 2255 2256 2257 2258 2259
			if partialRetrieveResult.Ids == nil {
				reason += "ids is nil\n"
				continue
			} else {
				intIds, intOk := partialRetrieveResult.Ids.IdField.(*schemapb.IDs_IntId)
				strIds, strOk := partialRetrieveResult.Ids.IdField.(*schemapb.IDs_StrId)
				if !intOk && !strOk {
					reason += "ids is empty\n"
2260
					continue
2261
				}
2262

2263
				if !intOk {
Y
yukun 已提交
2264 2265 2266 2267 2268 2269 2270 2271 2272
					if idsStr, ok := rt.result.Ids.IdField.(*schemapb.IDs_StrId); ok {
						idsStr.StrId.Data = append(idsStr.StrId.Data, strIds.StrId.Data...)
					} else {
						rt.result.Ids.IdField = &schemapb.IDs_StrId{
							StrId: &schemapb.StringArray{
								Data: strIds.StrId.Data,
							},
						}
					}
2273
				} else {
Y
yukun 已提交
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
					if idsInt, ok := rt.result.Ids.IdField.(*schemapb.IDs_IntId); ok {
						idsInt.IntId.Data = append(idsInt.IntId.Data, intIds.IntId.Data...)
					} else {
						rt.result.Ids.IdField = &schemapb.IDs_IntId{
							IntId: &schemapb.LongArray{
								Data: intIds.IntId.Data,
							},
						}
					}
				}
2284

Y
yukun 已提交
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
				if idx == 0 {
					rt.result.FieldsData = append(rt.result.FieldsData, partialRetrieveResult.FieldsData...)
				} else {
					for k, fieldData := range partialRetrieveResult.FieldsData {
						switch fieldType := fieldData.Field.(type) {
						case *schemapb.FieldData_Scalars:
							switch scalarType := fieldType.Scalars.Data.(type) {
							case *schemapb.ScalarField_BoolData:
								rt.result.FieldsData[k].GetScalars().GetBoolData().Data = append(rt.result.FieldsData[k].GetScalars().GetBoolData().Data, scalarType.BoolData.Data...)
							case *schemapb.ScalarField_IntData:
								rt.result.FieldsData[k].GetScalars().GetIntData().Data = append(rt.result.FieldsData[k].GetScalars().GetIntData().Data, scalarType.IntData.Data...)
							case *schemapb.ScalarField_LongData:
								rt.result.FieldsData[k].GetScalars().GetLongData().Data = append(rt.result.FieldsData[k].GetScalars().GetLongData().Data, scalarType.LongData.Data...)
							case *schemapb.ScalarField_FloatData:
								rt.result.FieldsData[k].GetScalars().GetFloatData().Data = append(rt.result.FieldsData[k].GetScalars().GetFloatData().Data, scalarType.FloatData.Data...)
							case *schemapb.ScalarField_DoubleData:
								rt.result.FieldsData[k].GetScalars().GetDoubleData().Data = append(rt.result.FieldsData[k].GetScalars().GetDoubleData().Data, scalarType.DoubleData.Data...)
							default:
								log.Debug("Retrieve received not supported data type")
							}
						case *schemapb.FieldData_Vectors:
							switch vectorType := fieldType.Vectors.Data.(type) {
							case *schemapb.VectorField_BinaryVector:
								rt.result.FieldsData[k].GetVectors().Data.(*schemapb.VectorField_BinaryVector).BinaryVector = append(rt.result.FieldsData[k].GetVectors().Data.(*schemapb.VectorField_BinaryVector).BinaryVector, vectorType.BinaryVector...)
							case *schemapb.VectorField_FloatVector:
								rt.result.FieldsData[k].GetVectors().GetFloatVector().Data = append(rt.result.FieldsData[k].GetVectors().GetFloatVector().Data, vectorType.FloatVector.Data...)
							}
						default:
						}
					}
				}
				// rt.result.FieldsData = append(rt.result.FieldsData, partialRetrieveResult.FieldsData...)
2317
			}
2318
		}
2319

2320 2321 2322 2323 2324 2325 2326 2327
		if availableQueryNodeNum == 0 {
			log.Info("Not any valid result found.",
				zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
			rt.result = &milvuspb.RetrieveResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    reason,
				},
2328 2329 2330
			}
			return nil
		}
2331

2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
		if len(rt.result.FieldsData) == 0 {
			log.Info("Retrieve result is nil.",
				zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
			rt.result = &milvuspb.RetrieveResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_EmptyCollection,
					Reason:    reason,
				},
			}
			return nil
		}

2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
		schema, err := globalMetaCache.GetCollectionSchema(ctx, rt.retrieve.CollectionName)
		if err != nil {
			return err
		}
		for i := 0; i < len(rt.result.FieldsData); i++ {
			for _, field := range schema.Fields {
				if field.Name == rt.OutputFields[i] {
					rt.result.FieldsData[i].FieldName = field.Name
					rt.result.FieldsData[i].Type = field.DataType
				}
			}
		}
2356
	}
2357 2358 2359 2360

	log.Info("Retrieve PostExecute done.",
		zap.Any("requestID", rt.Base.MsgID), zap.Any("requestType", "retrieve"))
	return nil
2361 2362
}

2363
type HasCollectionTask struct {
D
dragondriver 已提交
2364
	Condition
2365
	*milvuspb.HasCollectionRequest
2366 2367 2368
	ctx       context.Context
	rootCoord types.RootCoord
	result    *milvuspb.BoolResponse
2369 2370
}

2371
func (hct *HasCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
2372
	return hct.ctx
2373 2374
}

C
cai.zhang 已提交
2375
func (hct *HasCollectionTask) ID() UniqueID {
2376
	return hct.Base.MsgID
2377 2378
}

2379
func (hct *HasCollectionTask) SetID(uid UniqueID) {
2380
	hct.Base.MsgID = uid
2381 2382
}

S
sunby 已提交
2383 2384 2385 2386
func (hct *HasCollectionTask) Name() string {
	return HasCollectionTaskName
}

2387
func (hct *HasCollectionTask) Type() commonpb.MsgType {
2388
	return hct.Base.MsgType
2389 2390 2391
}

func (hct *HasCollectionTask) BeginTs() Timestamp {
2392
	return hct.Base.Timestamp
2393 2394 2395
}

func (hct *HasCollectionTask) EndTs() Timestamp {
2396
	return hct.Base.Timestamp
2397 2398 2399
}

func (hct *HasCollectionTask) SetTs(ts Timestamp) {
2400
	hct.Base.Timestamp = ts
2401 2402
}

S
sunby 已提交
2403 2404 2405 2406 2407 2408
func (hct *HasCollectionTask) OnEnqueue() error {
	hct.Base = &commonpb.MsgBase{}
	return nil
}

func (hct *HasCollectionTask) PreExecute(ctx context.Context) error {
2409
	hct.Base.MsgType = commonpb.MsgType_HasCollection
2410
	hct.Base.SourceID = Params.ProxyID
2411

2412
	if err := ValidateCollectionName(hct.CollectionName); err != nil {
N
neza2017 已提交
2413 2414
		return err
	}
2415 2416 2417
	return nil
}

S
sunby 已提交
2418
func (hct *HasCollectionTask) Execute(ctx context.Context) error {
2419
	var err error
2420
	hct.result, err = hct.rootCoord.HasCollection(ctx, hct.HasCollectionRequest)
G
godchen 已提交
2421 2422 2423
	if hct.result == nil {
		return errors.New("has collection resp is nil")
	}
2424
	if hct.result.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
2425 2426
		return errors.New(hct.result.Status.Reason)
	}
2427 2428 2429
	return err
}

S
sunby 已提交
2430
func (hct *HasCollectionTask) PostExecute(ctx context.Context) error {
2431 2432 2433 2434
	return nil
}

type DescribeCollectionTask struct {
D
dragondriver 已提交
2435
	Condition
2436
	*milvuspb.DescribeCollectionRequest
2437 2438 2439
	ctx       context.Context
	rootCoord types.RootCoord
	result    *milvuspb.DescribeCollectionResponse
2440 2441
}

2442
func (dct *DescribeCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
2443
	return dct.ctx
2444 2445
}

C
cai.zhang 已提交
2446
func (dct *DescribeCollectionTask) ID() UniqueID {
2447
	return dct.Base.MsgID
2448 2449
}

2450
func (dct *DescribeCollectionTask) SetID(uid UniqueID) {
2451
	dct.Base.MsgID = uid
2452 2453
}

S
sunby 已提交
2454 2455 2456 2457
func (dct *DescribeCollectionTask) Name() string {
	return DescribeCollectionTaskName
}

2458
func (dct *DescribeCollectionTask) Type() commonpb.MsgType {
2459
	return dct.Base.MsgType
2460 2461 2462
}

func (dct *DescribeCollectionTask) BeginTs() Timestamp {
2463
	return dct.Base.Timestamp
2464 2465 2466
}

func (dct *DescribeCollectionTask) EndTs() Timestamp {
2467
	return dct.Base.Timestamp
2468 2469 2470
}

func (dct *DescribeCollectionTask) SetTs(ts Timestamp) {
2471
	dct.Base.Timestamp = ts
2472 2473
}

S
sunby 已提交
2474 2475 2476 2477 2478 2479
func (dct *DescribeCollectionTask) OnEnqueue() error {
	dct.Base = &commonpb.MsgBase{}
	return nil
}

func (dct *DescribeCollectionTask) PreExecute(ctx context.Context) error {
2480
	dct.Base.MsgType = commonpb.MsgType_DescribeCollection
2481
	dct.Base.SourceID = Params.ProxyID
2482

2483
	if err := ValidateCollectionName(dct.CollectionName); err != nil {
N
neza2017 已提交
2484 2485
		return err
	}
2486 2487 2488
	return nil
}

S
sunby 已提交
2489
func (dct *DescribeCollectionTask) Execute(ctx context.Context) error {
2490
	var err error
S
sunby 已提交
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
	dct.result = &milvuspb.DescribeCollectionResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Schema: &schemapb.CollectionSchema{
			Name:        "",
			Description: "",
			AutoID:      false,
			Fields:      make([]*schemapb.FieldSchema, 0),
		},
		CollectionID:         0,
		VirtualChannelNames:  nil,
		PhysicalChannelNames: nil,
	}

2506
	result, err := dct.rootCoord.DescribeCollection(ctx, dct.DescribeCollectionRequest)
S
sunby 已提交
2507

2508 2509
	if err != nil {
		return err
G
godchen 已提交
2510
	}
S
sunby 已提交
2511

2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
	if result.Status.ErrorCode != commonpb.ErrorCode_Success {
		dct.result.Status = result.Status
	} else {
		dct.result.Schema.Name = result.Schema.Name
		dct.result.Schema.Description = result.Schema.Description
		dct.result.Schema.AutoID = result.Schema.AutoID
		dct.result.CollectionID = result.CollectionID
		dct.result.VirtualChannelNames = result.VirtualChannelNames
		dct.result.PhysicalChannelNames = result.PhysicalChannelNames

		for _, field := range result.Schema.Fields {
			if field.FieldID >= 100 { // TODO(dragondriver): use StartOfUserFieldID replacing 100
				dct.result.Schema.Fields = append(dct.result.Schema.Fields, &schemapb.FieldSchema{
					FieldID:      field.FieldID,
					Name:         field.Name,
					IsPrimaryKey: field.IsPrimaryKey,
2528
					AutoID:       field.AutoID,
2529 2530 2531 2532 2533 2534
					Description:  field.Description,
					DataType:     field.DataType,
					TypeParams:   field.TypeParams,
					IndexParams:  field.IndexParams,
				})
			}
S
sunby 已提交
2535 2536
		}
	}
2537
	return nil
2538 2539
}

S
sunby 已提交
2540
func (dct *DescribeCollectionTask) PostExecute(ctx context.Context) error {
2541 2542 2543
	return nil
}

2544
type GetCollectionStatisticsTask struct {
2545
	Condition
G
godchen 已提交
2546
	*milvuspb.GetCollectionStatisticsRequest
2547 2548 2549
	ctx       context.Context
	dataCoord types.DataCoord
	result    *milvuspb.GetCollectionStatisticsResponse
2550 2551
}

2552
func (g *GetCollectionStatisticsTask) TraceCtx() context.Context {
S
sunby 已提交
2553 2554 2555
	return g.ctx
}

2556
func (g *GetCollectionStatisticsTask) ID() UniqueID {
2557 2558 2559
	return g.Base.MsgID
}

2560
func (g *GetCollectionStatisticsTask) SetID(uid UniqueID) {
2561 2562 2563
	g.Base.MsgID = uid
}

2564
func (g *GetCollectionStatisticsTask) Name() string {
S
sunby 已提交
2565 2566 2567
	return GetCollectionStatisticsTaskName
}

2568
func (g *GetCollectionStatisticsTask) Type() commonpb.MsgType {
2569 2570 2571
	return g.Base.MsgType
}

2572
func (g *GetCollectionStatisticsTask) BeginTs() Timestamp {
2573 2574 2575
	return g.Base.Timestamp
}

2576
func (g *GetCollectionStatisticsTask) EndTs() Timestamp {
2577 2578 2579
	return g.Base.Timestamp
}

2580
func (g *GetCollectionStatisticsTask) SetTs(ts Timestamp) {
2581 2582 2583
	g.Base.Timestamp = ts
}

2584
func (g *GetCollectionStatisticsTask) OnEnqueue() error {
2585 2586 2587 2588
	g.Base = &commonpb.MsgBase{}
	return nil
}

2589
func (g *GetCollectionStatisticsTask) PreExecute(ctx context.Context) error {
2590
	g.Base.MsgType = commonpb.MsgType_GetCollectionStatistics
2591 2592 2593 2594
	g.Base.SourceID = Params.ProxyID
	return nil
}

2595
func (g *GetCollectionStatisticsTask) Execute(ctx context.Context) error {
G
godchen 已提交
2596
	collID, err := globalMetaCache.GetCollectionID(ctx, g.CollectionName)
2597 2598 2599
	if err != nil {
		return err
	}
G
godchen 已提交
2600
	req := &datapb.GetCollectionStatisticsRequest{
2601
		Base: &commonpb.MsgBase{
2602
			MsgType:   commonpb.MsgType_GetCollectionStatistics,
2603 2604 2605 2606 2607 2608 2609
			MsgID:     g.Base.MsgID,
			Timestamp: g.Base.Timestamp,
			SourceID:  g.Base.SourceID,
		},
		CollectionID: collID,
	}

2610
	result, _ := g.dataCoord.GetCollectionStatistics(ctx, req)
G
godchen 已提交
2611 2612 2613
	if result == nil {
		return errors.New("get collection statistics resp is nil")
	}
2614
	if result.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
2615
		return errors.New(result.Status.Reason)
2616
	}
G
godchen 已提交
2617
	g.result = &milvuspb.GetCollectionStatisticsResponse{
2618
		Status: &commonpb.Status{
2619
			ErrorCode: commonpb.ErrorCode_Success,
2620 2621 2622 2623 2624 2625 2626
			Reason:    "",
		},
		Stats: result.Stats,
	}
	return nil
}

2627 2628 2629 2630 2631 2632 2633
func (g *GetCollectionStatisticsTask) PostExecute(ctx context.Context) error {
	return nil
}

type GetPartitionStatisticsTask struct {
	Condition
	*milvuspb.GetPartitionStatisticsRequest
2634 2635 2636
	ctx       context.Context
	dataCoord types.DataCoord
	result    *milvuspb.GetPartitionStatisticsResponse
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
}

func (g *GetPartitionStatisticsTask) TraceCtx() context.Context {
	return g.ctx
}

func (g *GetPartitionStatisticsTask) ID() UniqueID {
	return g.Base.MsgID
}

func (g *GetPartitionStatisticsTask) SetID(uid UniqueID) {
	g.Base.MsgID = uid
}

func (g *GetPartitionStatisticsTask) Name() string {
	return GetPartitionStatisticsTaskName
}

func (g *GetPartitionStatisticsTask) Type() commonpb.MsgType {
	return g.Base.MsgType
}

func (g *GetPartitionStatisticsTask) BeginTs() Timestamp {
	return g.Base.Timestamp
}

func (g *GetPartitionStatisticsTask) EndTs() Timestamp {
	return g.Base.Timestamp
}

func (g *GetPartitionStatisticsTask) SetTs(ts Timestamp) {
	g.Base.Timestamp = ts
}

func (g *GetPartitionStatisticsTask) OnEnqueue() error {
	g.Base = &commonpb.MsgBase{}
	return nil
}

func (g *GetPartitionStatisticsTask) PreExecute(ctx context.Context) error {
	g.Base.MsgType = commonpb.MsgType_GetPartitionStatistics
	g.Base.SourceID = Params.ProxyID
	return nil
}

func (g *GetPartitionStatisticsTask) Execute(ctx context.Context) error {
	collID, err := globalMetaCache.GetCollectionID(ctx, g.CollectionName)
	if err != nil {
		return err
	}
	partitionID, err := globalMetaCache.GetPartitionID(ctx, g.CollectionName, g.PartitionName)
	if err != nil {
		return err
	}
	req := &datapb.GetPartitionStatisticsRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_GetPartitionStatistics,
			MsgID:     g.Base.MsgID,
			Timestamp: g.Base.Timestamp,
			SourceID:  g.Base.SourceID,
		},
		CollectionID: collID,
		PartitionID:  partitionID,
	}

2702
	result, _ := g.dataCoord.GetPartitionStatistics(ctx, req)
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719
	if result == nil {
		return errors.New("get partition statistics resp is nil")
	}
	if result.Status.ErrorCode != commonpb.ErrorCode_Success {
		return errors.New(result.Status.Reason)
	}
	g.result = &milvuspb.GetPartitionStatisticsResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		Stats: result.Stats,
	}
	return nil
}

func (g *GetPartitionStatisticsTask) PostExecute(ctx context.Context) error {
2720 2721 2722 2723
	return nil
}

type ShowCollectionsTask struct {
D
dragondriver 已提交
2724
	Condition
G
godchen 已提交
2725
	*milvuspb.ShowCollectionsRequest
2726 2727 2728 2729
	ctx        context.Context
	rootCoord  types.RootCoord
	queryCoord types.QueryCoord
	result     *milvuspb.ShowCollectionsResponse
2730 2731
}

2732
func (sct *ShowCollectionsTask) TraceCtx() context.Context {
S
sunby 已提交
2733
	return sct.ctx
2734 2735
}

C
cai.zhang 已提交
2736
func (sct *ShowCollectionsTask) ID() UniqueID {
2737
	return sct.Base.MsgID
2738 2739
}

2740
func (sct *ShowCollectionsTask) SetID(uid UniqueID) {
2741
	sct.Base.MsgID = uid
2742 2743
}

S
sunby 已提交
2744 2745 2746 2747
func (sct *ShowCollectionsTask) Name() string {
	return ShowCollectionTaskName
}

2748
func (sct *ShowCollectionsTask) Type() commonpb.MsgType {
2749
	return sct.Base.MsgType
2750 2751 2752
}

func (sct *ShowCollectionsTask) BeginTs() Timestamp {
2753
	return sct.Base.Timestamp
2754 2755 2756
}

func (sct *ShowCollectionsTask) EndTs() Timestamp {
2757
	return sct.Base.Timestamp
2758 2759 2760
}

func (sct *ShowCollectionsTask) SetTs(ts Timestamp) {
2761
	sct.Base.Timestamp = ts
2762 2763
}

S
sunby 已提交
2764 2765 2766 2767 2768 2769
func (sct *ShowCollectionsTask) OnEnqueue() error {
	sct.Base = &commonpb.MsgBase{}
	return nil
}

func (sct *ShowCollectionsTask) PreExecute(ctx context.Context) error {
2770
	sct.Base.MsgType = commonpb.MsgType_ShowCollections
2771
	sct.Base.SourceID = Params.ProxyID
2772

2773 2774 2775
	return nil
}

S
sunby 已提交
2776
func (sct *ShowCollectionsTask) Execute(ctx context.Context) error {
2777
	var err error
2778

2779
	respFromRootCoord, err := sct.rootCoord.ShowCollections(ctx, sct.ShowCollectionsRequest)
2780 2781 2782

	if err != nil {
		return err
G
godchen 已提交
2783
	}
2784

2785
	if respFromRootCoord == nil {
2786
		return errors.New("failed to show collections")
G
godchen 已提交
2787
	}
2788

2789 2790
	if respFromRootCoord.Status.ErrorCode != commonpb.ErrorCode_Success {
		return errors.New(respFromRootCoord.Status.Reason)
2791 2792 2793
	}

	if sct.ShowCollectionsRequest.Type == milvuspb.ShowCollectionsType_InMemory {
2794
		resp, err := sct.queryCoord.ShowCollections(ctx, &querypb.ShowCollectionsRequest{
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
			Base: &commonpb.MsgBase{
				MsgType:   commonpb.MsgType_ShowCollections,
				MsgID:     sct.ShowCollectionsRequest.Base.MsgID,
				Timestamp: sct.ShowCollectionsRequest.Base.Timestamp,
				SourceID:  sct.ShowCollectionsRequest.Base.SourceID,
			},
			//DbID: sct.ShowCollectionsRequest.DbName,
		})

		if err != nil {
			return err
		}

		if resp == nil {
			return errors.New("failed to show collections")
		}

		if resp.Status.ErrorCode != commonpb.ErrorCode_Success {
			return errors.New(resp.Status.Reason)
		}

		sct.result = &milvuspb.ShowCollectionsResponse{
			Status:          resp.Status,
			CollectionNames: make([]string, 0, len(resp.CollectionIDs)),
			CollectionIds:   make([]int64, 0, len(resp.CollectionIDs)),
		}

		idMap := make(map[int64]string)
2823 2824
		for i, name := range respFromRootCoord.CollectionNames {
			idMap[respFromRootCoord.CollectionIds[i]] = name
2825 2826 2827 2828 2829 2830
		}

		for _, id := range resp.CollectionIDs {
			sct.result.CollectionIds = append(sct.result.CollectionIds, id)
			sct.result.CollectionNames = append(sct.result.CollectionNames, idMap[id])
		}
2831 2832
	} else {
		sct.result = respFromRootCoord
2833 2834 2835
	}

	return nil
2836 2837
}

S
sunby 已提交
2838
func (sct *ShowCollectionsTask) PostExecute(ctx context.Context) error {
2839 2840
	return nil
}
N
neza2017 已提交
2841 2842 2843

type CreatePartitionTask struct {
	Condition
2844
	*milvuspb.CreatePartitionRequest
2845 2846 2847
	ctx       context.Context
	rootCoord types.RootCoord
	result    *commonpb.Status
N
neza2017 已提交
2848 2849
}

2850
func (cpt *CreatePartitionTask) TraceCtx() context.Context {
S
sunby 已提交
2851
	return cpt.ctx
2852 2853
}

N
neza2017 已提交
2854
func (cpt *CreatePartitionTask) ID() UniqueID {
2855
	return cpt.Base.MsgID
N
neza2017 已提交
2856 2857
}

2858
func (cpt *CreatePartitionTask) SetID(uid UniqueID) {
2859
	cpt.Base.MsgID = uid
2860 2861
}

S
sunby 已提交
2862 2863 2864 2865
func (cpt *CreatePartitionTask) Name() string {
	return CreatePartitionTaskName
}

2866
func (cpt *CreatePartitionTask) Type() commonpb.MsgType {
2867
	return cpt.Base.MsgType
N
neza2017 已提交
2868 2869 2870
}

func (cpt *CreatePartitionTask) BeginTs() Timestamp {
2871
	return cpt.Base.Timestamp
N
neza2017 已提交
2872 2873 2874
}

func (cpt *CreatePartitionTask) EndTs() Timestamp {
2875
	return cpt.Base.Timestamp
N
neza2017 已提交
2876 2877 2878
}

func (cpt *CreatePartitionTask) SetTs(ts Timestamp) {
2879
	cpt.Base.Timestamp = ts
N
neza2017 已提交
2880 2881
}

S
sunby 已提交
2882 2883 2884 2885 2886 2887
func (cpt *CreatePartitionTask) OnEnqueue() error {
	cpt.Base = &commonpb.MsgBase{}
	return nil
}

func (cpt *CreatePartitionTask) PreExecute(ctx context.Context) error {
2888
	cpt.Base.MsgType = commonpb.MsgType_CreatePartition
2889
	cpt.Base.SourceID = Params.ProxyID
2890

2891
	collName, partitionTag := cpt.CollectionName, cpt.PartitionName
N
neza2017 已提交
2892 2893 2894 2895 2896 2897 2898 2899 2900

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	if err := ValidatePartitionTag(partitionTag, true); err != nil {
		return err
	}

N
neza2017 已提交
2901 2902 2903
	return nil
}

S
sunby 已提交
2904
func (cpt *CreatePartitionTask) Execute(ctx context.Context) (err error) {
2905
	cpt.result, err = cpt.rootCoord.CreatePartition(ctx, cpt.CreatePartitionRequest)
G
godchen 已提交
2906 2907 2908
	if cpt.result == nil {
		return errors.New("get collection statistics resp is nil")
	}
2909
	if cpt.result.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
2910 2911
		return errors.New(cpt.result.Reason)
	}
N
neza2017 已提交
2912 2913 2914
	return err
}

S
sunby 已提交
2915
func (cpt *CreatePartitionTask) PostExecute(ctx context.Context) error {
N
neza2017 已提交
2916 2917 2918 2919 2920
	return nil
}

type DropPartitionTask struct {
	Condition
2921
	*milvuspb.DropPartitionRequest
2922 2923 2924
	ctx       context.Context
	rootCoord types.RootCoord
	result    *commonpb.Status
N
neza2017 已提交
2925 2926
}

2927
func (dpt *DropPartitionTask) TraceCtx() context.Context {
S
sunby 已提交
2928
	return dpt.ctx
2929 2930
}

N
neza2017 已提交
2931
func (dpt *DropPartitionTask) ID() UniqueID {
2932
	return dpt.Base.MsgID
N
neza2017 已提交
2933 2934
}

2935
func (dpt *DropPartitionTask) SetID(uid UniqueID) {
2936
	dpt.Base.MsgID = uid
2937 2938
}

S
sunby 已提交
2939 2940 2941 2942
func (dpt *DropPartitionTask) Name() string {
	return DropPartitionTaskName
}

2943
func (dpt *DropPartitionTask) Type() commonpb.MsgType {
2944
	return dpt.Base.MsgType
N
neza2017 已提交
2945 2946 2947
}

func (dpt *DropPartitionTask) BeginTs() Timestamp {
2948
	return dpt.Base.Timestamp
N
neza2017 已提交
2949 2950 2951
}

func (dpt *DropPartitionTask) EndTs() Timestamp {
2952
	return dpt.Base.Timestamp
N
neza2017 已提交
2953 2954 2955
}

func (dpt *DropPartitionTask) SetTs(ts Timestamp) {
2956
	dpt.Base.Timestamp = ts
N
neza2017 已提交
2957 2958
}

S
sunby 已提交
2959 2960 2961 2962 2963 2964
func (dpt *DropPartitionTask) OnEnqueue() error {
	dpt.Base = &commonpb.MsgBase{}
	return nil
}

func (dpt *DropPartitionTask) PreExecute(ctx context.Context) error {
2965
	dpt.Base.MsgType = commonpb.MsgType_DropPartition
2966
	dpt.Base.SourceID = Params.ProxyID
2967

2968
	collName, partitionTag := dpt.CollectionName, dpt.PartitionName
N
neza2017 已提交
2969 2970 2971 2972 2973 2974 2975 2976 2977

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	if err := ValidatePartitionTag(partitionTag, true); err != nil {
		return err
	}

N
neza2017 已提交
2978 2979 2980
	return nil
}

S
sunby 已提交
2981
func (dpt *DropPartitionTask) Execute(ctx context.Context) (err error) {
2982
	dpt.result, err = dpt.rootCoord.DropPartition(ctx, dpt.DropPartitionRequest)
G
godchen 已提交
2983 2984 2985
	if dpt.result == nil {
		return errors.New("get collection statistics resp is nil")
	}
2986
	if dpt.result.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
2987 2988
		return errors.New(dpt.result.Reason)
	}
N
neza2017 已提交
2989 2990 2991
	return err
}

S
sunby 已提交
2992
func (dpt *DropPartitionTask) PostExecute(ctx context.Context) error {
N
neza2017 已提交
2993 2994 2995 2996 2997
	return nil
}

type HasPartitionTask struct {
	Condition
2998
	*milvuspb.HasPartitionRequest
2999 3000 3001
	ctx       context.Context
	rootCoord types.RootCoord
	result    *milvuspb.BoolResponse
N
neza2017 已提交
3002 3003
}

3004
func (hpt *HasPartitionTask) TraceCtx() context.Context {
S
sunby 已提交
3005
	return hpt.ctx
3006 3007
}

N
neza2017 已提交
3008
func (hpt *HasPartitionTask) ID() UniqueID {
3009
	return hpt.Base.MsgID
N
neza2017 已提交
3010 3011
}

3012
func (hpt *HasPartitionTask) SetID(uid UniqueID) {
3013
	hpt.Base.MsgID = uid
3014 3015
}

S
sunby 已提交
3016 3017 3018 3019
func (hpt *HasPartitionTask) Name() string {
	return HasPartitionTaskName
}

3020
func (hpt *HasPartitionTask) Type() commonpb.MsgType {
3021
	return hpt.Base.MsgType
N
neza2017 已提交
3022 3023 3024
}

func (hpt *HasPartitionTask) BeginTs() Timestamp {
3025
	return hpt.Base.Timestamp
N
neza2017 已提交
3026 3027 3028
}

func (hpt *HasPartitionTask) EndTs() Timestamp {
3029
	return hpt.Base.Timestamp
N
neza2017 已提交
3030 3031 3032
}

func (hpt *HasPartitionTask) SetTs(ts Timestamp) {
3033
	hpt.Base.Timestamp = ts
N
neza2017 已提交
3034 3035
}

S
sunby 已提交
3036 3037 3038 3039 3040 3041
func (hpt *HasPartitionTask) OnEnqueue() error {
	hpt.Base = &commonpb.MsgBase{}
	return nil
}

func (hpt *HasPartitionTask) PreExecute(ctx context.Context) error {
3042
	hpt.Base.MsgType = commonpb.MsgType_HasPartition
3043
	hpt.Base.SourceID = Params.ProxyID
3044

3045
	collName, partitionTag := hpt.CollectionName, hpt.PartitionName
N
neza2017 已提交
3046 3047 3048 3049 3050 3051 3052 3053

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	if err := ValidatePartitionTag(partitionTag, true); err != nil {
		return err
	}
N
neza2017 已提交
3054 3055 3056
	return nil
}

S
sunby 已提交
3057
func (hpt *HasPartitionTask) Execute(ctx context.Context) (err error) {
3058
	hpt.result, err = hpt.rootCoord.HasPartition(ctx, hpt.HasPartitionRequest)
G
godchen 已提交
3059 3060 3061
	if hpt.result == nil {
		return errors.New("get collection statistics resp is nil")
	}
3062
	if hpt.result.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
3063 3064
		return errors.New(hpt.result.Status.Reason)
	}
N
neza2017 已提交
3065 3066 3067
	return err
}

S
sunby 已提交
3068
func (hpt *HasPartitionTask) PostExecute(ctx context.Context) error {
N
neza2017 已提交
3069 3070 3071 3072 3073
	return nil
}

type ShowPartitionsTask struct {
	Condition
G
godchen 已提交
3074
	*milvuspb.ShowPartitionsRequest
3075 3076 3077
	ctx       context.Context
	rootCoord types.RootCoord
	result    *milvuspb.ShowPartitionsResponse
N
neza2017 已提交
3078 3079
}

3080
func (spt *ShowPartitionsTask) TraceCtx() context.Context {
S
sunby 已提交
3081
	return spt.ctx
3082 3083
}

N
neza2017 已提交
3084
func (spt *ShowPartitionsTask) ID() UniqueID {
3085
	return spt.Base.MsgID
N
neza2017 已提交
3086 3087
}

3088
func (spt *ShowPartitionsTask) SetID(uid UniqueID) {
3089
	spt.Base.MsgID = uid
3090 3091
}

S
sunby 已提交
3092 3093 3094 3095
func (spt *ShowPartitionsTask) Name() string {
	return ShowPartitionTaskName
}

3096
func (spt *ShowPartitionsTask) Type() commonpb.MsgType {
3097
	return spt.Base.MsgType
N
neza2017 已提交
3098 3099 3100
}

func (spt *ShowPartitionsTask) BeginTs() Timestamp {
3101
	return spt.Base.Timestamp
N
neza2017 已提交
3102 3103 3104
}

func (spt *ShowPartitionsTask) EndTs() Timestamp {
3105
	return spt.Base.Timestamp
N
neza2017 已提交
3106 3107 3108
}

func (spt *ShowPartitionsTask) SetTs(ts Timestamp) {
3109
	spt.Base.Timestamp = ts
N
neza2017 已提交
3110 3111
}

S
sunby 已提交
3112 3113 3114 3115 3116 3117
func (spt *ShowPartitionsTask) OnEnqueue() error {
	spt.Base = &commonpb.MsgBase{}
	return nil
}

func (spt *ShowPartitionsTask) PreExecute(ctx context.Context) error {
3118
	spt.Base.MsgType = commonpb.MsgType_ShowPartitions
3119
	spt.Base.SourceID = Params.ProxyID
3120

3121
	if err := ValidateCollectionName(spt.CollectionName); err != nil {
N
neza2017 已提交
3122 3123
		return err
	}
N
neza2017 已提交
3124 3125 3126
	return nil
}

S
sunby 已提交
3127
func (spt *ShowPartitionsTask) Execute(ctx context.Context) error {
3128
	var err error
3129
	spt.result, err = spt.rootCoord.ShowPartitions(ctx, spt.ShowPartitionsRequest)
G
godchen 已提交
3130 3131
	if spt.result == nil {
		return errors.New("get collection statistics resp is nil")
G
godchen 已提交
3132
	}
3133
	if spt.result.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
3134 3135 3136
		return errors.New(spt.result.Status.Reason)
	}
	return err
N
neza2017 已提交
3137 3138
}

S
sunby 已提交
3139
func (spt *ShowPartitionsTask) PostExecute(ctx context.Context) error {
N
neza2017 已提交
3140 3141
	return nil
}
3142 3143 3144

type CreateIndexTask struct {
	Condition
3145
	*milvuspb.CreateIndexRequest
3146 3147 3148
	ctx       context.Context
	rootCoord types.RootCoord
	result    *commonpb.Status
3149 3150
}

3151
func (cit *CreateIndexTask) TraceCtx() context.Context {
S
sunby 已提交
3152
	return cit.ctx
3153 3154
}

3155
func (cit *CreateIndexTask) ID() UniqueID {
3156
	return cit.Base.MsgID
3157 3158 3159
}

func (cit *CreateIndexTask) SetID(uid UniqueID) {
3160
	cit.Base.MsgID = uid
3161 3162
}

S
sunby 已提交
3163 3164 3165 3166
func (cit *CreateIndexTask) Name() string {
	return CreateIndexTaskName
}

3167
func (cit *CreateIndexTask) Type() commonpb.MsgType {
3168
	return cit.Base.MsgType
3169 3170 3171
}

func (cit *CreateIndexTask) BeginTs() Timestamp {
3172
	return cit.Base.Timestamp
3173 3174 3175
}

func (cit *CreateIndexTask) EndTs() Timestamp {
3176
	return cit.Base.Timestamp
3177 3178 3179
}

func (cit *CreateIndexTask) SetTs(ts Timestamp) {
3180
	cit.Base.Timestamp = ts
3181 3182
}

S
sunby 已提交
3183 3184 3185 3186 3187 3188
func (cit *CreateIndexTask) OnEnqueue() error {
	cit.Base = &commonpb.MsgBase{}
	return nil
}

func (cit *CreateIndexTask) PreExecute(ctx context.Context) error {
3189
	cit.Base.MsgType = commonpb.MsgType_CreateIndex
3190
	cit.Base.SourceID = Params.ProxyID
3191

3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
	collName, fieldName := cit.CollectionName, cit.FieldName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	if err := ValidateFieldName(fieldName); err != nil {
		return err
	}

3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
	// check index param, not accurate, only some static rules
	indexParams := make(map[string]string)
	for _, kv := range cit.CreateIndexRequest.ExtraParams {
		if kv.Key == "params" { // TODO(dragondriver): change `params` to const variable
			params, err := funcutil.ParseIndexParamsMap(kv.Value)
			if err != nil {
				log.Warn("Failed to parse index params",
					zap.String("params", kv.Value),
					zap.Error(err))
				continue
			}
			for k, v := range params {
				indexParams[k] = v
			}
		} else {
			indexParams[kv.Key] = kv.Value
		}
	}

	indexType, exist := indexParams["index_type"] // TODO(dragondriver): change `index_type` to const variable
	if !exist {
		indexType = indexparamcheck.IndexFaissIvfPQ // IVF_PQ is the default index type
	}

	adapter, err := indexparamcheck.GetConfAdapterMgrInstance().GetAdapter(indexType)
	if err != nil {
		log.Warn("Failed to get conf adapter", zap.String("index_type", indexType))
		return fmt.Errorf("invalid index type: %s", indexType)
	}

	ok := adapter.CheckTrain(indexParams)
	if !ok {
		log.Warn("Create index with invalid params", zap.Any("index_params", indexParams))
		return fmt.Errorf("invalid index params: %v", cit.CreateIndexRequest.ExtraParams)
	}

3238 3239 3240
	return nil
}

S
sunby 已提交
3241
func (cit *CreateIndexTask) Execute(ctx context.Context) error {
G
godchen 已提交
3242
	var err error
3243
	cit.result, err = cit.rootCoord.CreateIndex(ctx, cit.CreateIndexRequest)
G
godchen 已提交
3244 3245 3246
	if cit.result == nil {
		return errors.New("get collection statistics resp is nil")
	}
3247
	if cit.result.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
3248 3249
		return errors.New(cit.result.Reason)
	}
3250 3251 3252
	return err
}

S
sunby 已提交
3253
func (cit *CreateIndexTask) PostExecute(ctx context.Context) error {
3254 3255 3256 3257 3258
	return nil
}

type DescribeIndexTask struct {
	Condition
3259
	*milvuspb.DescribeIndexRequest
3260 3261 3262
	ctx       context.Context
	rootCoord types.RootCoord
	result    *milvuspb.DescribeIndexResponse
3263 3264
}

3265
func (dit *DescribeIndexTask) TraceCtx() context.Context {
S
sunby 已提交
3266
	return dit.ctx
3267 3268
}

3269
func (dit *DescribeIndexTask) ID() UniqueID {
3270
	return dit.Base.MsgID
3271 3272 3273
}

func (dit *DescribeIndexTask) SetID(uid UniqueID) {
3274
	dit.Base.MsgID = uid
3275 3276
}

S
sunby 已提交
3277 3278 3279 3280
func (dit *DescribeIndexTask) Name() string {
	return DescribeIndexTaskName
}

3281
func (dit *DescribeIndexTask) Type() commonpb.MsgType {
3282
	return dit.Base.MsgType
3283 3284 3285
}

func (dit *DescribeIndexTask) BeginTs() Timestamp {
3286
	return dit.Base.Timestamp
3287 3288 3289
}

func (dit *DescribeIndexTask) EndTs() Timestamp {
3290
	return dit.Base.Timestamp
3291 3292 3293
}

func (dit *DescribeIndexTask) SetTs(ts Timestamp) {
3294
	dit.Base.Timestamp = ts
3295 3296
}

S
sunby 已提交
3297 3298 3299 3300 3301 3302
func (dit *DescribeIndexTask) OnEnqueue() error {
	dit.Base = &commonpb.MsgBase{}
	return nil
}

func (dit *DescribeIndexTask) PreExecute(ctx context.Context) error {
3303
	dit.Base.MsgType = commonpb.MsgType_DescribeIndex
3304
	dit.Base.SourceID = Params.ProxyID
3305

3306
	if err := ValidateCollectionName(dit.CollectionName); err != nil {
3307 3308 3309
		return err
	}

Z
zhenshan.cao 已提交
3310 3311 3312 3313 3314
	// only support default index name for now. @2021.02.18
	if dit.IndexName == "" {
		dit.IndexName = Params.DefaultIndexName
	}

3315 3316 3317
	return nil
}

S
sunby 已提交
3318
func (dit *DescribeIndexTask) Execute(ctx context.Context) error {
3319
	var err error
3320
	dit.result, err = dit.rootCoord.DescribeIndex(ctx, dit.DescribeIndexRequest)
G
godchen 已提交
3321 3322 3323
	if dit.result == nil {
		return errors.New("get collection statistics resp is nil")
	}
3324
	if dit.result.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
3325 3326
		return errors.New(dit.result.Status.Reason)
	}
3327 3328 3329
	return err
}

S
sunby 已提交
3330
func (dit *DescribeIndexTask) PostExecute(ctx context.Context) error {
3331 3332 3333
	return nil
}

B
BossZou 已提交
3334 3335
type DropIndexTask struct {
	Condition
S
sunby 已提交
3336
	ctx context.Context
B
BossZou 已提交
3337
	*milvuspb.DropIndexRequest
3338 3339
	rootCoord types.RootCoord
	result    *commonpb.Status
B
BossZou 已提交
3340 3341
}

3342
func (dit *DropIndexTask) TraceCtx() context.Context {
S
sunby 已提交
3343
	return dit.ctx
B
BossZou 已提交
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
}

func (dit *DropIndexTask) ID() UniqueID {
	return dit.Base.MsgID
}

func (dit *DropIndexTask) SetID(uid UniqueID) {
	dit.Base.MsgID = uid
}

S
sunby 已提交
3354 3355 3356 3357
func (dit *DropIndexTask) Name() string {
	return DropIndexTaskName
}

B
BossZou 已提交
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373
func (dit *DropIndexTask) Type() commonpb.MsgType {
	return dit.Base.MsgType
}

func (dit *DropIndexTask) BeginTs() Timestamp {
	return dit.Base.Timestamp
}

func (dit *DropIndexTask) EndTs() Timestamp {
	return dit.Base.Timestamp
}

func (dit *DropIndexTask) SetTs(ts Timestamp) {
	dit.Base.Timestamp = ts
}

S
sunby 已提交
3374 3375 3376 3377 3378 3379
func (dit *DropIndexTask) OnEnqueue() error {
	dit.Base = &commonpb.MsgBase{}
	return nil
}

func (dit *DropIndexTask) PreExecute(ctx context.Context) error {
3380
	dit.Base.MsgType = commonpb.MsgType_DropIndex
B
BossZou 已提交
3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392
	dit.Base.SourceID = Params.ProxyID

	collName, fieldName := dit.CollectionName, dit.FieldName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	if err := ValidateFieldName(fieldName); err != nil {
		return err
	}

3393 3394 3395 3396
	if dit.IndexName == "" {
		dit.IndexName = Params.DefaultIndexName
	}

B
BossZou 已提交
3397 3398 3399
	return nil
}

S
sunby 已提交
3400
func (dit *DropIndexTask) Execute(ctx context.Context) error {
B
BossZou 已提交
3401
	var err error
3402
	dit.result, err = dit.rootCoord.DropIndex(ctx, dit.DropIndexRequest)
B
BossZou 已提交
3403 3404 3405
	if dit.result == nil {
		return errors.New("drop index resp is nil")
	}
3406
	if dit.result.ErrorCode != commonpb.ErrorCode_Success {
B
BossZou 已提交
3407 3408 3409 3410 3411
		return errors.New(dit.result.Reason)
	}
	return err
}

S
sunby 已提交
3412
func (dit *DropIndexTask) PostExecute(ctx context.Context) error {
B
BossZou 已提交
3413 3414 3415
	return nil
}

3416 3417 3418
type GetIndexBuildProgressTask struct {
	Condition
	*milvuspb.GetIndexBuildProgressRequest
3419 3420 3421 3422 3423
	ctx        context.Context
	indexCoord types.IndexCoord
	rootCoord  types.RootCoord
	dataCoord  types.DataCoord
	result     *milvuspb.GetIndexBuildProgressResponse
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
}

func (gibpt *GetIndexBuildProgressTask) TraceCtx() context.Context {
	return gibpt.ctx
}

func (gibpt *GetIndexBuildProgressTask) ID() UniqueID {
	return gibpt.Base.MsgID
}

func (gibpt *GetIndexBuildProgressTask) SetID(uid UniqueID) {
	gibpt.Base.MsgID = uid
}

func (gibpt *GetIndexBuildProgressTask) Name() string {
	return GetIndexBuildProgressTaskName
}

func (gibpt *GetIndexBuildProgressTask) Type() commonpb.MsgType {
	return gibpt.Base.MsgType
}

func (gibpt *GetIndexBuildProgressTask) BeginTs() Timestamp {
	return gibpt.Base.Timestamp
}

func (gibpt *GetIndexBuildProgressTask) EndTs() Timestamp {
	return gibpt.Base.Timestamp
}

func (gibpt *GetIndexBuildProgressTask) SetTs(ts Timestamp) {
	gibpt.Base.Timestamp = ts
}

func (gibpt *GetIndexBuildProgressTask) OnEnqueue() error {
	gibpt.Base = &commonpb.MsgBase{}
	return nil
}

func (gibpt *GetIndexBuildProgressTask) PreExecute(ctx context.Context) error {
	gibpt.Base.MsgType = commonpb.MsgType_GetIndexBuildProgress
	gibpt.Base.SourceID = Params.ProxyID

	if err := ValidateCollectionName(gibpt.CollectionName); err != nil {
		return err
	}

	return nil
}

func (gibpt *GetIndexBuildProgressTask) Execute(ctx context.Context) error {
	collectionName := gibpt.CollectionName
	collectionID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
	if err != nil { // err is not nil if collection not exists
		return err
	}

	showPartitionRequest := &milvuspb.ShowPartitionsRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowPartitions,
			MsgID:     gibpt.Base.MsgID,
			Timestamp: gibpt.Base.Timestamp,
			SourceID:  Params.ProxyID,
		},
		DbName:         gibpt.DbName,
		CollectionName: collectionName,
		CollectionID:   collectionID,
	}
3492
	partitions, err := gibpt.rootCoord.ShowPartitions(ctx, showPartitionRequest)
3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512
	if err != nil {
		return err
	}

	if gibpt.IndexName == "" {
		gibpt.IndexName = Params.DefaultIndexName
	}

	describeIndexReq := milvuspb.DescribeIndexRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_DescribeIndex,
			MsgID:     gibpt.Base.MsgID,
			Timestamp: gibpt.Base.Timestamp,
			SourceID:  Params.ProxyID,
		},
		DbName:         gibpt.DbName,
		CollectionName: gibpt.CollectionName,
		//		IndexName:      gibpt.IndexName,
	}

3513
	indexDescriptionResp, err2 := gibpt.rootCoord.DescribeIndex(ctx, &describeIndexReq)
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527
	if err2 != nil {
		return err2
	}

	matchIndexID := int64(-1)
	foundIndexID := false
	for _, desc := range indexDescriptionResp.IndexDescriptions {
		if desc.IndexName == gibpt.IndexName {
			matchIndexID = desc.IndexID
			foundIndexID = true
			break
		}
	}
	if !foundIndexID {
3528
		return fmt.Errorf("no index is created")
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
	}

	var allSegmentIDs []UniqueID
	for _, partitionID := range partitions.PartitionIDs {
		showSegmentsRequest := &milvuspb.ShowSegmentsRequest{
			Base: &commonpb.MsgBase{
				MsgType:   commonpb.MsgType_ShowSegments,
				MsgID:     gibpt.Base.MsgID,
				Timestamp: gibpt.Base.Timestamp,
				SourceID:  Params.ProxyID,
			},
			CollectionID: collectionID,
			PartitionID:  partitionID,
		}
3543
		segments, err := gibpt.rootCoord.ShowSegments(ctx, showSegmentsRequest)
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568
		if err != nil {
			return err
		}
		if segments.Status.ErrorCode != commonpb.ErrorCode_Success {
			return errors.New(segments.Status.Reason)
		}
		allSegmentIDs = append(allSegmentIDs, segments.SegmentIDs...)
	}

	getIndexStatesRequest := &indexpb.GetIndexStatesRequest{
		IndexBuildIDs: make([]UniqueID, 0),
	}

	buildIndexMap := make(map[int64]int64)
	for _, segmentID := range allSegmentIDs {
		describeSegmentRequest := &milvuspb.DescribeSegmentRequest{
			Base: &commonpb.MsgBase{
				MsgType:   commonpb.MsgType_DescribeSegment,
				MsgID:     gibpt.Base.MsgID,
				Timestamp: gibpt.Base.Timestamp,
				SourceID:  Params.ProxyID,
			},
			CollectionID: collectionID,
			SegmentID:    segmentID,
		}
3569
		segmentDesc, err := gibpt.rootCoord.DescribeSegment(ctx, describeSegmentRequest)
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
		if err != nil {
			return err
		}
		if segmentDesc.IndexID == matchIndexID {
			if segmentDesc.EnableIndex {
				getIndexStatesRequest.IndexBuildIDs = append(getIndexStatesRequest.IndexBuildIDs, segmentDesc.BuildID)
				buildIndexMap[segmentID] = segmentDesc.BuildID
			}
		}
	}

3581
	states, err := gibpt.indexCoord.GetIndexStates(ctx, getIndexStatesRequest)
3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
	if err != nil {
		return err
	}

	if states.Status.ErrorCode != commonpb.ErrorCode_Success {
		gibpt.result = &milvuspb.GetIndexBuildProgressResponse{
			Status: states.Status,
		}
	}

	buildFinishMap := make(map[int64]bool)
	for _, state := range states.States {
		if state.State == commonpb.IndexState_Finished {
			buildFinishMap[state.IndexBuildID] = true
		}
	}

3599
	infoResp, err := gibpt.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_SegmentInfo,
			MsgID:     0,
			Timestamp: 0,
			SourceID:  Params.ProxyID,
		},
		SegmentIDs: allSegmentIDs,
	})
	if err != nil {
		return err
	}

	total := int64(0)
	indexed := int64(0)

	for _, info := range infoResp.Infos {
S
sunby 已提交
3616
		total += info.NumOfRows
3617
		if buildFinishMap[buildIndexMap[info.ID]] {
S
sunby 已提交
3618
			indexed += info.NumOfRows
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637
		}
	}

	gibpt.result = &milvuspb.GetIndexBuildProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		TotalRows:   total,
		IndexedRows: indexed,
	}

	return nil
}

func (gibpt *GetIndexBuildProgressTask) PostExecute(ctx context.Context) error {
	return nil
}

3638
type GetIndexStateTask struct {
3639
	Condition
G
godchen 已提交
3640
	*milvuspb.GetIndexStateRequest
3641 3642 3643 3644
	ctx        context.Context
	indexCoord types.IndexCoord
	rootCoord  types.RootCoord
	result     *milvuspb.GetIndexStateResponse
3645 3646
}

3647
func (gist *GetIndexStateTask) TraceCtx() context.Context {
S
sunby 已提交
3648
	return gist.ctx
3649 3650
}

S
sunby 已提交
3651 3652
func (gist *GetIndexStateTask) ID() UniqueID {
	return gist.Base.MsgID
3653 3654
}

S
sunby 已提交
3655 3656
func (gist *GetIndexStateTask) SetID(uid UniqueID) {
	gist.Base.MsgID = uid
3657 3658
}

S
sunby 已提交
3659 3660
func (gist *GetIndexStateTask) Name() string {
	return GetIndexStateTaskName
3661 3662
}

S
sunby 已提交
3663 3664
func (gist *GetIndexStateTask) Type() commonpb.MsgType {
	return gist.Base.MsgType
3665 3666
}

S
sunby 已提交
3667 3668
func (gist *GetIndexStateTask) BeginTs() Timestamp {
	return gist.Base.Timestamp
3669 3670
}

S
sunby 已提交
3671 3672
func (gist *GetIndexStateTask) EndTs() Timestamp {
	return gist.Base.Timestamp
3673 3674
}

S
sunby 已提交
3675 3676 3677 3678 3679 3680 3681 3682
func (gist *GetIndexStateTask) SetTs(ts Timestamp) {
	gist.Base.Timestamp = ts
}

func (gist *GetIndexStateTask) OnEnqueue() error {
	gist.Base = &commonpb.MsgBase{}
	return nil
}
3683

S
sunby 已提交
3684
func (gist *GetIndexStateTask) PreExecute(ctx context.Context) error {
3685
	gist.Base.MsgType = commonpb.MsgType_GetIndexState
S
sunby 已提交
3686 3687
	gist.Base.SourceID = Params.ProxyID

3688
	if err := ValidateCollectionName(gist.CollectionName); err != nil {
3689 3690 3691 3692 3693 3694
		return err
	}

	return nil
}

S
sunby 已提交
3695 3696
func (gist *GetIndexStateTask) Execute(ctx context.Context) error {
	collectionName := gist.CollectionName
G
godchen 已提交
3697
	collectionID, err := globalMetaCache.GetCollectionID(ctx, collectionName)
Z
zhenshan.cao 已提交
3698 3699 3700 3701
	if err != nil { // err is not nil if collection not exists
		return err
	}

G
godchen 已提交
3702
	showPartitionRequest := &milvuspb.ShowPartitionsRequest{
Z
zhenshan.cao 已提交
3703
		Base: &commonpb.MsgBase{
3704
			MsgType:   commonpb.MsgType_ShowPartitions,
S
sunby 已提交
3705 3706
			MsgID:     gist.Base.MsgID,
			Timestamp: gist.Base.Timestamp,
Z
zhenshan.cao 已提交
3707 3708
			SourceID:  Params.ProxyID,
		},
S
sunby 已提交
3709
		DbName:         gist.DbName,
Z
zhenshan.cao 已提交
3710 3711 3712
		CollectionName: collectionName,
		CollectionID:   collectionID,
	}
3713
	partitions, err := gist.rootCoord.ShowPartitions(ctx, showPartitionRequest)
Z
zhenshan.cao 已提交
3714 3715 3716 3717
	if err != nil {
		return err
	}

S
sunby 已提交
3718 3719
	if gist.IndexName == "" {
		gist.IndexName = Params.DefaultIndexName
3720 3721 3722 3723
	}

	describeIndexReq := milvuspb.DescribeIndexRequest{
		Base: &commonpb.MsgBase{
3724
			MsgType:   commonpb.MsgType_DescribeIndex,
S
sunby 已提交
3725 3726
			MsgID:     gist.Base.MsgID,
			Timestamp: gist.Base.Timestamp,
3727 3728
			SourceID:  Params.ProxyID,
		},
S
sunby 已提交
3729 3730 3731
		DbName:         gist.DbName,
		CollectionName: gist.CollectionName,
		IndexName:      gist.IndexName,
3732 3733
	}

3734
	indexDescriptionResp, err2 := gist.rootCoord.DescribeIndex(ctx, &describeIndexReq)
3735 3736 3737 3738 3739 3740 3741
	if err2 != nil {
		return err2
	}

	matchIndexID := int64(-1)
	foundIndexID := false
	for _, desc := range indexDescriptionResp.IndexDescriptions {
S
sunby 已提交
3742
		if desc.IndexName == gist.IndexName {
3743 3744 3745 3746 3747 3748
			matchIndexID = desc.IndexID
			foundIndexID = true
			break
		}
	}
	if !foundIndexID {
3749
		return fmt.Errorf("no index is created")
3750 3751
	}

Z
zhenshan.cao 已提交
3752
	var allSegmentIDs []UniqueID
Z
zhenshan.cao 已提交
3753
	for _, partitionID := range partitions.PartitionIDs {
G
godchen 已提交
3754
		showSegmentsRequest := &milvuspb.ShowSegmentsRequest{
Z
zhenshan.cao 已提交
3755
			Base: &commonpb.MsgBase{
3756
				MsgType:   commonpb.MsgType_ShowSegments,
S
sunby 已提交
3757 3758
				MsgID:     gist.Base.MsgID,
				Timestamp: gist.Base.Timestamp,
Z
zhenshan.cao 已提交
3759 3760 3761 3762 3763
				SourceID:  Params.ProxyID,
			},
			CollectionID: collectionID,
			PartitionID:  partitionID,
		}
3764
		segments, err := gist.rootCoord.ShowSegments(ctx, showSegmentsRequest)
Z
zhenshan.cao 已提交
3765 3766 3767
		if err != nil {
			return err
		}
3768
		if segments.Status.ErrorCode != commonpb.ErrorCode_Success {
Z
zhenshan.cao 已提交
3769
			return errors.New(segments.Status.Reason)
Z
zhenshan.cao 已提交
3770
		}
Z
zhenshan.cao 已提交
3771 3772 3773
		allSegmentIDs = append(allSegmentIDs, segments.SegmentIDs...)
	}

G
godchen 已提交
3774
	getIndexStatesRequest := &indexpb.GetIndexStatesRequest{
Z
zhenshan.cao 已提交
3775 3776
		IndexBuildIDs: make([]UniqueID, 0),
	}
Z
zhenshan.cao 已提交
3777

Z
zhenshan.cao 已提交
3778 3779 3780
	for _, segmentID := range allSegmentIDs {
		describeSegmentRequest := &milvuspb.DescribeSegmentRequest{
			Base: &commonpb.MsgBase{
3781
				MsgType:   commonpb.MsgType_DescribeSegment,
S
sunby 已提交
3782 3783
				MsgID:     gist.Base.MsgID,
				Timestamp: gist.Base.Timestamp,
Z
zhenshan.cao 已提交
3784 3785 3786 3787 3788
				SourceID:  Params.ProxyID,
			},
			CollectionID: collectionID,
			SegmentID:    segmentID,
		}
3789
		segmentDesc, err := gist.rootCoord.DescribeSegment(ctx, describeSegmentRequest)
Z
zhenshan.cao 已提交
3790 3791 3792
		if err != nil {
			return err
		}
Z
zhenshan.cao 已提交
3793
		if segmentDesc.IndexID == matchIndexID {
3794
			if segmentDesc.EnableIndex {
3795
				getIndexStatesRequest.IndexBuildIDs = append(getIndexStatesRequest.IndexBuildIDs, segmentDesc.BuildID)
3796
			}
Z
zhenshan.cao 已提交
3797 3798
		}
	}
Z
zhenshan.cao 已提交
3799

3800 3801 3802 3803 3804 3805
	gist.result = &milvuspb.GetIndexStateResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		State: commonpb.IndexState_Finished,
Z
zhenshan.cao 已提交
3806 3807
	}

C
Cai Yudong 已提交
3808
	log.Debug("Proxy GetIndexState", zap.Int("IndexBuildIDs", len(getIndexStatesRequest.IndexBuildIDs)), zap.Error(err))
3809 3810 3811

	if len(getIndexStatesRequest.IndexBuildIDs) == 0 {
		return nil
3812
	}
3813
	states, err := gist.indexCoord.GetIndexStates(ctx, getIndexStatesRequest)
Z
zhenshan.cao 已提交
3814 3815 3816 3817
	if err != nil {
		return err
	}

3818
	if states.Status.ErrorCode != commonpb.ErrorCode_Success {
G
godchen 已提交
3819
		gist.result = &milvuspb.GetIndexStateResponse{
Z
zhenshan.cao 已提交
3820
			Status: states.Status,
T
ThreadDao 已提交
3821
			State:  commonpb.IndexState_Failed,
Z
zhenshan.cao 已提交
3822 3823 3824 3825 3826
		}
		return nil
	}

	for _, state := range states.States {
T
ThreadDao 已提交
3827
		if state.State != commonpb.IndexState_Finished {
G
godchen 已提交
3828
			gist.result = &milvuspb.GetIndexStateResponse{
Z
zhenshan.cao 已提交
3829
				Status: states.Status,
Z
zhenshan.cao 已提交
3830
				State:  state.State,
Z
zhenshan.cao 已提交
3831
			}
Z
zhenshan.cao 已提交
3832
			return nil
Z
zhenshan.cao 已提交
3833 3834 3835
		}
	}

3836
	return nil
3837 3838
}

S
sunby 已提交
3839
func (gist *GetIndexStateTask) PostExecute(ctx context.Context) error {
3840 3841
	return nil
}
Z
zhenshan.cao 已提交
3842 3843 3844 3845

type FlushTask struct {
	Condition
	*milvuspb.FlushRequest
3846 3847
	ctx       context.Context
	dataCoord types.DataCoord
3848
	result    *milvuspb.FlushResponse
Z
zhenshan.cao 已提交
3849 3850
}

3851
func (ft *FlushTask) TraceCtx() context.Context {
S
sunby 已提交
3852
	return ft.ctx
Z
zhenshan.cao 已提交
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
}

func (ft *FlushTask) ID() UniqueID {
	return ft.Base.MsgID
}

func (ft *FlushTask) SetID(uid UniqueID) {
	ft.Base.MsgID = uid
}

S
sunby 已提交
3863 3864 3865 3866
func (ft *FlushTask) Name() string {
	return FlushTaskName
}

Z
zhenshan.cao 已提交
3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
func (ft *FlushTask) Type() commonpb.MsgType {
	return ft.Base.MsgType
}

func (ft *FlushTask) BeginTs() Timestamp {
	return ft.Base.Timestamp
}

func (ft *FlushTask) EndTs() Timestamp {
	return ft.Base.Timestamp
}

func (ft *FlushTask) SetTs(ts Timestamp) {
	ft.Base.Timestamp = ts
}

S
sunby 已提交
3883 3884 3885 3886 3887 3888
func (ft *FlushTask) OnEnqueue() error {
	ft.Base = &commonpb.MsgBase{}
	return nil
}

func (ft *FlushTask) PreExecute(ctx context.Context) error {
3889
	ft.Base.MsgType = commonpb.MsgType_Flush
Z
zhenshan.cao 已提交
3890 3891 3892 3893
	ft.Base.SourceID = Params.ProxyID
	return nil
}

S
sunby 已提交
3894
func (ft *FlushTask) Execute(ctx context.Context) error {
3895
	coll2Segments := make(map[string]*schemapb.LongArray)
3896
	for _, collName := range ft.CollectionNames {
G
godchen 已提交
3897
		collID, err := globalMetaCache.GetCollectionID(ctx, collName)
3898 3899 3900 3901 3902
		if err != nil {
			return err
		}
		flushReq := &datapb.FlushRequest{
			Base: &commonpb.MsgBase{
3903
				MsgType:   commonpb.MsgType_Flush,
3904 3905 3906 3907 3908 3909 3910
				MsgID:     ft.Base.MsgID,
				Timestamp: ft.Base.Timestamp,
				SourceID:  ft.Base.SourceID,
			},
			DbID:         0,
			CollectionID: collID,
		}
3911 3912 3913
		resp, err := ft.dataCoord.Flush(ctx, flushReq)
		if err != nil {
			return fmt.Errorf("Failed to call flush to data coordinator: %s", err.Error())
3914
		}
3915 3916
		if resp.Status.ErrorCode != commonpb.ErrorCode_Success {
			return errors.New(resp.Status.Reason)
3917
		}
3918
		coll2Segments[collName] = &schemapb.LongArray{Data: resp.GetSegmentIDs()}
Z
zhenshan.cao 已提交
3919
	}
3920 3921 3922 3923 3924 3925 3926
	ft.result = &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		DbName:     "",
		CollSegIDs: coll2Segments,
Z
zhenshan.cao 已提交
3927
	}
3928
	return nil
Z
zhenshan.cao 已提交
3929 3930
}

S
sunby 已提交
3931
func (ft *FlushTask) PostExecute(ctx context.Context) error {
Z
zhenshan.cao 已提交
3932 3933
	return nil
}
3934 3935 3936 3937

type LoadCollectionTask struct {
	Condition
	*milvuspb.LoadCollectionRequest
3938 3939 3940
	ctx        context.Context
	queryCoord types.QueryCoord
	result     *commonpb.Status
3941 3942
}

3943
func (lct *LoadCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
3944
	return lct.ctx
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954
}

func (lct *LoadCollectionTask) ID() UniqueID {
	return lct.Base.MsgID
}

func (lct *LoadCollectionTask) SetID(uid UniqueID) {
	lct.Base.MsgID = uid
}

S
sunby 已提交
3955 3956 3957 3958
func (lct *LoadCollectionTask) Name() string {
	return LoadCollectionTaskName
}

3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
func (lct *LoadCollectionTask) Type() commonpb.MsgType {
	return lct.Base.MsgType
}

func (lct *LoadCollectionTask) BeginTs() Timestamp {
	return lct.Base.Timestamp
}

func (lct *LoadCollectionTask) EndTs() Timestamp {
	return lct.Base.Timestamp
}

func (lct *LoadCollectionTask) SetTs(ts Timestamp) {
	lct.Base.Timestamp = ts
}

S
sunby 已提交
3975 3976 3977 3978 3979 3980
func (lct *LoadCollectionTask) OnEnqueue() error {
	lct.Base = &commonpb.MsgBase{}
	return nil
}

func (lct *LoadCollectionTask) PreExecute(ctx context.Context) error {
S
sunby 已提交
3981
	log.Debug("LoadCollectionTask PreExecute", zap.String("role", Params.RoleName), zap.Int64("msgID", lct.Base.MsgID))
3982
	lct.Base.MsgType = commonpb.MsgType_LoadCollection
3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993
	lct.Base.SourceID = Params.ProxyID

	collName := lct.CollectionName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	return nil
}

S
sunby 已提交
3994
func (lct *LoadCollectionTask) Execute(ctx context.Context) (err error) {
S
sunby 已提交
3995
	log.Debug("LoadCollectionTask Execute", zap.String("role", Params.RoleName), zap.Int64("msgID", lct.Base.MsgID))
G
godchen 已提交
3996
	collID, err := globalMetaCache.GetCollectionID(ctx, lct.CollectionName)
3997 3998 3999
	if err != nil {
		return err
	}
G
godchen 已提交
4000
	collSchema, err := globalMetaCache.GetCollectionSchema(ctx, lct.CollectionName)
4001 4002 4003 4004
	if err != nil {
		return err
	}

4005 4006
	request := &querypb.LoadCollectionRequest{
		Base: &commonpb.MsgBase{
4007
			MsgType:   commonpb.MsgType_LoadCollection,
4008 4009 4010 4011 4012 4013
			MsgID:     lct.Base.MsgID,
			Timestamp: lct.Base.Timestamp,
			SourceID:  lct.Base.SourceID,
		},
		DbID:         0,
		CollectionID: collID,
4014
		Schema:       collSchema,
4015
	}
4016
	log.Debug("send LoadCollectionRequest to query coordinator", zap.String("role", Params.RoleName), zap.Int64("msgID", request.Base.MsgID), zap.Int64("collectionID", request.CollectionID),
S
sunby 已提交
4017
		zap.Any("schema", request.Schema))
4018
	lct.result, err = lct.queryCoord.LoadCollection(ctx, request)
S
sunby 已提交
4019
	if err != nil {
4020
		return fmt.Errorf("call query coordinator LoadCollection: %s", err)
S
sunby 已提交
4021 4022
	}
	return nil
4023 4024
}

S
sunby 已提交
4025
func (lct *LoadCollectionTask) PostExecute(ctx context.Context) error {
S
sunby 已提交
4026
	log.Debug("LoadCollectionTask PostExecute", zap.String("role", Params.RoleName), zap.Int64("msgID", lct.Base.MsgID))
4027 4028 4029 4030 4031 4032
	return nil
}

type ReleaseCollectionTask struct {
	Condition
	*milvuspb.ReleaseCollectionRequest
4033 4034 4035 4036
	ctx        context.Context
	queryCoord types.QueryCoord
	result     *commonpb.Status
	chMgr      channelsMgr
4037 4038
}

4039
func (rct *ReleaseCollectionTask) TraceCtx() context.Context {
S
sunby 已提交
4040
	return rct.ctx
4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
}

func (rct *ReleaseCollectionTask) ID() UniqueID {
	return rct.Base.MsgID
}

func (rct *ReleaseCollectionTask) SetID(uid UniqueID) {
	rct.Base.MsgID = uid
}

S
sunby 已提交
4051 4052 4053 4054
func (rct *ReleaseCollectionTask) Name() string {
	return ReleaseCollectionTaskName
}

4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070
func (rct *ReleaseCollectionTask) Type() commonpb.MsgType {
	return rct.Base.MsgType
}

func (rct *ReleaseCollectionTask) BeginTs() Timestamp {
	return rct.Base.Timestamp
}

func (rct *ReleaseCollectionTask) EndTs() Timestamp {
	return rct.Base.Timestamp
}

func (rct *ReleaseCollectionTask) SetTs(ts Timestamp) {
	rct.Base.Timestamp = ts
}

S
sunby 已提交
4071 4072 4073 4074 4075 4076
func (rct *ReleaseCollectionTask) OnEnqueue() error {
	rct.Base = &commonpb.MsgBase{}
	return nil
}

func (rct *ReleaseCollectionTask) PreExecute(ctx context.Context) error {
4077
	rct.Base.MsgType = commonpb.MsgType_ReleaseCollection
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088
	rct.Base.SourceID = Params.ProxyID

	collName := rct.CollectionName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	return nil
}

S
sunby 已提交
4089
func (rct *ReleaseCollectionTask) Execute(ctx context.Context) (err error) {
G
godchen 已提交
4090
	collID, err := globalMetaCache.GetCollectionID(ctx, rct.CollectionName)
4091 4092 4093 4094 4095
	if err != nil {
		return err
	}
	request := &querypb.ReleaseCollectionRequest{
		Base: &commonpb.MsgBase{
4096
			MsgType:   commonpb.MsgType_ReleaseCollection,
4097 4098 4099 4100 4101 4102 4103
			MsgID:     rct.Base.MsgID,
			Timestamp: rct.Base.Timestamp,
			SourceID:  rct.Base.SourceID,
		},
		DbID:         0,
		CollectionID: collID,
	}
4104

4105
	rct.result, err = rct.queryCoord.ReleaseCollection(ctx, request)
4106 4107 4108

	_ = rct.chMgr.removeDQLStream(collID)

4109 4110 4111
	return err
}

S
sunby 已提交
4112
func (rct *ReleaseCollectionTask) PostExecute(ctx context.Context) error {
4113 4114 4115 4116 4117
	return nil
}

type LoadPartitionTask struct {
	Condition
G
godchen 已提交
4118
	*milvuspb.LoadPartitionsRequest
4119 4120 4121
	ctx        context.Context
	queryCoord types.QueryCoord
	result     *commonpb.Status
4122 4123
}

4124 4125 4126 4127
func (lpt *LoadPartitionTask) TraceCtx() context.Context {
	return lpt.ctx
}

4128 4129 4130 4131 4132 4133 4134 4135
func (lpt *LoadPartitionTask) ID() UniqueID {
	return lpt.Base.MsgID
}

func (lpt *LoadPartitionTask) SetID(uid UniqueID) {
	lpt.Base.MsgID = uid
}

S
sunby 已提交
4136 4137 4138 4139
func (lpt *LoadPartitionTask) Name() string {
	return LoadPartitionTaskName
}

4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155
func (lpt *LoadPartitionTask) Type() commonpb.MsgType {
	return lpt.Base.MsgType
}

func (lpt *LoadPartitionTask) BeginTs() Timestamp {
	return lpt.Base.Timestamp
}

func (lpt *LoadPartitionTask) EndTs() Timestamp {
	return lpt.Base.Timestamp
}

func (lpt *LoadPartitionTask) SetTs(ts Timestamp) {
	lpt.Base.Timestamp = ts
}

S
sunby 已提交
4156 4157 4158 4159 4160 4161
func (lpt *LoadPartitionTask) OnEnqueue() error {
	lpt.Base = &commonpb.MsgBase{}
	return nil
}

func (lpt *LoadPartitionTask) PreExecute(ctx context.Context) error {
4162
	lpt.Base.MsgType = commonpb.MsgType_LoadPartitions
4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173
	lpt.Base.SourceID = Params.ProxyID

	collName := lpt.CollectionName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	return nil
}

S
sunby 已提交
4174
func (lpt *LoadPartitionTask) Execute(ctx context.Context) error {
4175
	var partitionIDs []int64
G
godchen 已提交
4176
	collID, err := globalMetaCache.GetCollectionID(ctx, lpt.CollectionName)
4177 4178 4179
	if err != nil {
		return err
	}
G
godchen 已提交
4180
	collSchema, err := globalMetaCache.GetCollectionSchema(ctx, lpt.CollectionName)
4181 4182 4183
	if err != nil {
		return err
	}
4184
	for _, partitionName := range lpt.PartitionNames {
G
godchen 已提交
4185
		partitionID, err := globalMetaCache.GetPartitionID(ctx, lpt.CollectionName, partitionName)
4186 4187 4188 4189 4190
		if err != nil {
			return err
		}
		partitionIDs = append(partitionIDs, partitionID)
	}
G
godchen 已提交
4191
	request := &querypb.LoadPartitionsRequest{
4192
		Base: &commonpb.MsgBase{
4193
			MsgType:   commonpb.MsgType_LoadPartitions,
4194 4195 4196 4197 4198 4199 4200
			MsgID:     lpt.Base.MsgID,
			Timestamp: lpt.Base.Timestamp,
			SourceID:  lpt.Base.SourceID,
		},
		DbID:         0,
		CollectionID: collID,
		PartitionIDs: partitionIDs,
4201
		Schema:       collSchema,
4202
	}
4203
	lpt.result, err = lpt.queryCoord.LoadPartitions(ctx, request)
4204 4205 4206
	return err
}

S
sunby 已提交
4207
func (lpt *LoadPartitionTask) PostExecute(ctx context.Context) error {
4208 4209 4210 4211 4212
	return nil
}

type ReleasePartitionTask struct {
	Condition
G
godchen 已提交
4213
	*milvuspb.ReleasePartitionsRequest
4214 4215 4216
	ctx        context.Context
	queryCoord types.QueryCoord
	result     *commonpb.Status
4217 4218
}

4219
func (rpt *ReleasePartitionTask) TraceCtx() context.Context {
S
sunby 已提交
4220
	return rpt.ctx
4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234
}

func (rpt *ReleasePartitionTask) ID() UniqueID {
	return rpt.Base.MsgID
}

func (rpt *ReleasePartitionTask) SetID(uid UniqueID) {
	rpt.Base.MsgID = uid
}

func (rpt *ReleasePartitionTask) Type() commonpb.MsgType {
	return rpt.Base.MsgType
}

S
sunby 已提交
4235 4236 4237 4238
func (rpt *ReleasePartitionTask) Name() string {
	return ReleasePartitionTaskName
}

4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
func (rpt *ReleasePartitionTask) BeginTs() Timestamp {
	return rpt.Base.Timestamp
}

func (rpt *ReleasePartitionTask) EndTs() Timestamp {
	return rpt.Base.Timestamp
}

func (rpt *ReleasePartitionTask) SetTs(ts Timestamp) {
	rpt.Base.Timestamp = ts
}

S
sunby 已提交
4251 4252 4253 4254 4255 4256
func (rpt *ReleasePartitionTask) OnEnqueue() error {
	rpt.Base = &commonpb.MsgBase{}
	return nil
}

func (rpt *ReleasePartitionTask) PreExecute(ctx context.Context) error {
4257
	rpt.Base.MsgType = commonpb.MsgType_ReleasePartitions
4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268
	rpt.Base.SourceID = Params.ProxyID

	collName := rpt.CollectionName

	if err := ValidateCollectionName(collName); err != nil {
		return err
	}

	return nil
}

S
sunby 已提交
4269
func (rpt *ReleasePartitionTask) Execute(ctx context.Context) (err error) {
4270
	var partitionIDs []int64
G
godchen 已提交
4271
	collID, err := globalMetaCache.GetCollectionID(ctx, rpt.CollectionName)
4272 4273 4274 4275
	if err != nil {
		return err
	}
	for _, partitionName := range rpt.PartitionNames {
G
godchen 已提交
4276
		partitionID, err := globalMetaCache.GetPartitionID(ctx, rpt.CollectionName, partitionName)
4277 4278 4279 4280 4281
		if err != nil {
			return err
		}
		partitionIDs = append(partitionIDs, partitionID)
	}
G
godchen 已提交
4282
	request := &querypb.ReleasePartitionsRequest{
4283
		Base: &commonpb.MsgBase{
4284
			MsgType:   commonpb.MsgType_ReleasePartitions,
4285 4286 4287 4288 4289 4290 4291 4292
			MsgID:     rpt.Base.MsgID,
			Timestamp: rpt.Base.Timestamp,
			SourceID:  rpt.Base.SourceID,
		},
		DbID:         0,
		CollectionID: collID,
		PartitionIDs: partitionIDs,
	}
4293
	rpt.result, err = rpt.queryCoord.ReleasePartitions(ctx, request)
4294 4295 4296
	return err
}

S
sunby 已提交
4297
func (rpt *ReleasePartitionTask) PostExecute(ctx context.Context) error {
4298 4299
	return nil
}