impl.go 159.1 KB
Newer Older
1 2 3 4 5 6
// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
7 8
// with the License. You may obtain a copy of the License at
//
9
//     http://www.apache.org/licenses/LICENSE-2.0
10
//
11 12 13 14 15
// 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.
16

C
Cai Yudong 已提交
17
package proxy
18 19 20

import (
	"context"
21
	"errors"
22
	"fmt"
C
cai.zhang 已提交
23
	"os"
24
	"strconv"
25 26 27
	"sync"

	"golang.org/x/sync/errgroup"
28

29
	"github.com/golang/protobuf/proto"
S
SimFG 已提交
30 31
	"github.com/milvus-io/milvus-proto/go-api/commonpb"
	"github.com/milvus-io/milvus-proto/go-api/milvuspb"
32
	"github.com/milvus-io/milvus/internal/common"
X
Xiangyu Wang 已提交
33
	"github.com/milvus-io/milvus/internal/log"
34
	"github.com/milvus-io/milvus/internal/metrics"
J
jaime 已提交
35
	"github.com/milvus-io/milvus/internal/mq/msgstream"
X
Xiangyu Wang 已提交
36 37 38 39
	"github.com/milvus-io/milvus/internal/proto/datapb"
	"github.com/milvus-io/milvus/internal/proto/internalpb"
	"github.com/milvus-io/milvus/internal/proto/proxypb"
	"github.com/milvus-io/milvus/internal/proto/querypb"
40
	"github.com/milvus-io/milvus/internal/util"
41
	"github.com/milvus-io/milvus/internal/util/commonpbutil"
42
	"github.com/milvus-io/milvus/internal/util/crypto"
43
	"github.com/milvus-io/milvus/internal/util/errorutil"
44
	"github.com/milvus-io/milvus/internal/util/importutil"
45 46
	"github.com/milvus-io/milvus/internal/util/logutil"
	"github.com/milvus-io/milvus/internal/util/metricsinfo"
E
Enwei Jiao 已提交
47
	"github.com/milvus-io/milvus/internal/util/paramtable"
48
	"github.com/milvus-io/milvus/internal/util/timerecord"
49
	"github.com/milvus-io/milvus/internal/util/trace"
X
Xiangyu Wang 已提交
50
	"github.com/milvus-io/milvus/internal/util/typeutil"
51 52
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
53 54
)

55 56
const moduleName = "Proxy"

57
// UpdateStateCode updates the state code of Proxy.
58
func (node *Proxy) UpdateStateCode(code commonpb.StateCode) {
59
	node.stateCode.Store(code)
Z
zhenshan.cao 已提交
60 61
}

62
// GetComponentStates get state of Proxy.
63 64
func (node *Proxy) GetComponentStates(ctx context.Context) (*milvuspb.ComponentStates, error) {
	stats := &milvuspb.ComponentStates{
G
godchen 已提交
65 66 67 68
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
	}
69
	code, ok := node.stateCode.Load().(commonpb.StateCode)
G
godchen 已提交
70 71 72 73 74 75
	if !ok {
		errMsg := "unexpected error in type assertion"
		stats.Status = &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    errMsg,
		}
G
godchen 已提交
76
		return stats, nil
G
godchen 已提交
77
	}
78 79 80 81
	nodeID := common.NotRegisteredID
	if node.session != nil && node.session.Registered() {
		nodeID = node.session.ServerID
	}
82
	info := &milvuspb.ComponentInfo{
83 84
		// NodeID:    Params.ProxyID, // will race with Proxy.Register()
		NodeID:    nodeID,
C
Cai Yudong 已提交
85
		Role:      typeutil.ProxyRole,
G
godchen 已提交
86 87 88 89 90 91
		StateCode: code,
	}
	stats.State = info
	return stats, nil
}

C
cxytz01 已提交
92
// GetStatisticsChannel gets statistics channel of Proxy.
C
Cai Yudong 已提交
93
func (node *Proxy) GetStatisticsChannel(ctx context.Context) (*milvuspb.StringResponse, error) {
G
godchen 已提交
94 95 96 97 98 99 100 101 102
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		Value: "",
	}, nil
}

103
// InvalidateCollectionMetaCache invalidate the meta cache of specific collection.
C
Cai Yudong 已提交
104
func (node *Proxy) InvalidateCollectionMetaCache(ctx context.Context, request *proxypb.InvalidateCollMetaCacheRequest) (*commonpb.Status, error) {
105
	ctx = logutil.WithModule(ctx, moduleName)
106
	logutil.Logger(ctx).Info("received request to invalidate collection meta cache",
107
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
108
		zap.String("db", request.DbName),
109 110
		zap.String("collectionName", request.CollectionName),
		zap.Int64("collectionID", request.CollectionID))
D
dragondriver 已提交
111

112
	collectionName := request.CollectionName
113
	collectionID := request.CollectionID
X
Xiaofan 已提交
114 115

	var aliasName []string
N
neza2017 已提交
116
	if globalMetaCache != nil {
117 118 119 120
		if collectionName != "" {
			globalMetaCache.RemoveCollection(ctx, collectionName) // no need to return error, though collection may be not cached
		}
		if request.CollectionID != UniqueID(0) {
X
Xiaofan 已提交
121
			aliasName = globalMetaCache.RemoveCollectionsByID(ctx, collectionID)
122
		}
N
neza2017 已提交
123
	}
124 125
	if request.GetBase().GetMsgType() == commonpb.MsgType_DropCollection {
		// no need to handle error, since this Proxy may not create dml stream for the collection.
126 127
		node.chMgr.removeDMLStream(request.GetCollectionID())
		// clean up collection level metrics
E
Enwei Jiao 已提交
128
		metrics.CleanupCollectionMetrics(paramtable.GetNodeID(), collectionName)
X
Xiaofan 已提交
129
		for _, alias := range aliasName {
E
Enwei Jiao 已提交
130
			metrics.CleanupCollectionMetrics(paramtable.GetNodeID(), alias)
X
Xiaofan 已提交
131
		}
132
	}
133
	logutil.Logger(ctx).Info("complete to invalidate collection meta cache",
134
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
135
		zap.String("db", request.DbName),
136 137
		zap.String("collection", collectionName),
		zap.Int64("collectionID", collectionID))
D
dragondriver 已提交
138

139
	return &commonpb.Status{
140
		ErrorCode: commonpb.ErrorCode_Success,
141 142
		Reason:    "",
	}, nil
143 144
}

145
// CreateCollection create a collection by the schema.
146
// TODO(dragondriver): add more detailed ut for ConsistencyLevel, should we support multiple consistency level in Proxy?
C
Cai Yudong 已提交
147
func (node *Proxy) CreateCollection(ctx context.Context, request *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
148 149 150
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
151 152 153 154

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreateCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
155 156 157
	method := "CreateCollection"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
158
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
159

160
	cct := &createCollectionTask{
S
sunby 已提交
161
		ctx:                     ctx,
162 163
		Condition:               NewTaskCondition(ctx),
		CreateCollectionRequest: request,
164
		rootCoord:               node.rootCoord,
165 166
	}

167 168 169
	// avoid data race
	lenOfSchema := len(request.Schema)

170 171
	log.Debug(
		rpcReceived(method),
172
		zap.String("traceID", traceID),
173
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
174 175
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
176
		zap.Int("len(schema)", lenOfSchema),
177 178
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
179

180 181 182
	if err := node.sched.ddQueue.Enqueue(cct); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
183 184
			zap.Error(err),
			zap.String("traceID", traceID),
185
			zap.String("role", typeutil.ProxyRole),
186 187 188
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Int("len(schema)", lenOfSchema),
189 190
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
191

E
Enwei Jiao 已提交
192
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
193
		return &commonpb.Status{
194
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
195 196 197 198
			Reason:    err.Error(),
		}, nil
	}

199 200
	log.Debug(
		rpcEnqueued(method),
201
		zap.String("traceID", traceID),
202
		zap.String("role", typeutil.ProxyRole),
203 204 205
		zap.Int64("MsgID", cct.ID()),
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
206 207
		zap.Uint64("timestamp", request.Base.Timestamp),
		zap.String("db", request.DbName),
208 209
		zap.String("collection", request.CollectionName),
		zap.Int("len(schema)", lenOfSchema),
210 211
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
212

213 214 215
	if err := cct.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
216
			zap.Error(err),
217
			zap.String("traceID", traceID),
218
			zap.String("role", typeutil.ProxyRole),
219 220 221
			zap.Int64("MsgID", cct.ID()),
			zap.Uint64("BeginTs", cct.BeginTs()),
			zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
222 223
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
224
			zap.Int("len(schema)", lenOfSchema),
225 226
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
D
dragondriver 已提交
227

E
Enwei Jiao 已提交
228
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
229
		return &commonpb.Status{
230
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
231 232 233 234
			Reason:    err.Error(),
		}, nil
	}

235 236
	log.Debug(
		rpcDone(method),
237
		zap.String("traceID", traceID),
238
		zap.String("role", typeutil.ProxyRole),
239 240 241 242 243 244
		zap.Int64("MsgID", cct.ID()),
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Int("len(schema)", lenOfSchema),
245 246
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
247

E
Enwei Jiao 已提交
248 249
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
250 251 252
	return cct.result, nil
}

253
// DropCollection drop a collection.
C
Cai Yudong 已提交
254
func (node *Proxy) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
255 256 257
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
258 259 260 261

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
262 263
	method := "DropCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
264
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
265

266
	dct := &dropCollectionTask{
S
sunby 已提交
267
		ctx:                   ctx,
268 269
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
270
		rootCoord:             node.rootCoord,
271
		chMgr:                 node.chMgr,
S
sunby 已提交
272
		chTicker:              node.chTicker,
273 274
	}

275 276
	log.Debug("DropCollection received",
		zap.String("traceID", traceID),
277
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
278 279
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
280 281 282 283 284

	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DropCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
285
			zap.String("role", typeutil.ProxyRole),
286 287 288
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
289
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
290
		return &commonpb.Status{
291
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
292 293 294 295
			Reason:    err.Error(),
		}, nil
	}

296 297
	log.Debug("DropCollection enqueued",
		zap.String("traceID", traceID),
298
		zap.String("role", typeutil.ProxyRole),
299 300 301
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
302 303
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
304 305 306

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DropCollection failed to WaitToFinish",
D
dragondriver 已提交
307
			zap.Error(err),
308
			zap.String("traceID", traceID),
309
			zap.String("role", typeutil.ProxyRole),
310 311 312
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTs", dct.BeginTs()),
			zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
313 314 315
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
316
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
317
		return &commonpb.Status{
318
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
319 320 321 322
			Reason:    err.Error(),
		}, nil
	}

323 324
	log.Debug("DropCollection done",
		zap.String("traceID", traceID),
325
		zap.String("role", typeutil.ProxyRole),
326 327 328 329 330 331
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
332 333
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
334 335 336
	return dct.result, nil
}

337
// HasCollection check if the specific collection exists in Milvus.
C
Cai Yudong 已提交
338
func (node *Proxy) HasCollection(ctx context.Context, request *milvuspb.HasCollectionRequest) (*milvuspb.BoolResponse, error) {
339 340 341 342 343
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
344 345 346 347

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
348 349
	method := "HasCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
350
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
351
		metrics.TotalLabel).Inc()
352 353 354

	log.Debug("HasCollection received",
		zap.String("traceID", traceID),
355
		zap.String("role", typeutil.ProxyRole),
356 357 358
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

359
	hct := &hasCollectionTask{
S
sunby 已提交
360
		ctx:                  ctx,
361 362
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
363
		rootCoord:            node.rootCoord,
364 365
	}

366 367 368 369
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
370
			zap.String("role", typeutil.ProxyRole),
371 372 373
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
374
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
375
			metrics.AbandonLabel).Inc()
376 377
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
378
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
379 380 381 382 383
				Reason:    err.Error(),
			},
		}, nil
	}

384 385
	log.Debug("HasCollection enqueued",
		zap.String("traceID", traceID),
386
		zap.String("role", typeutil.ProxyRole),
387 388 389
		zap.Int64("MsgID", hct.ID()),
		zap.Uint64("BeginTS", hct.BeginTs()),
		zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
390 391
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
392 393 394

	if err := hct.WaitToFinish(); err != nil {
		log.Warn("HasCollection failed to WaitToFinish",
D
dragondriver 已提交
395
			zap.Error(err),
396
			zap.String("traceID", traceID),
397
			zap.String("role", typeutil.ProxyRole),
398 399 400
			zap.Int64("MsgID", hct.ID()),
			zap.Uint64("BeginTS", hct.BeginTs()),
			zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
401 402 403
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
404
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
405
			metrics.FailLabel).Inc()
406 407
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
408
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
409 410 411 412 413
				Reason:    err.Error(),
			},
		}, nil
	}

414 415
	log.Debug("HasCollection done",
		zap.String("traceID", traceID),
416
		zap.String("role", typeutil.ProxyRole),
417 418 419 420 421 422
		zap.Int64("MsgID", hct.ID()),
		zap.Uint64("BeginTS", hct.BeginTs()),
		zap.Uint64("EndTS", hct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
423
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
424
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
425
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
426 427 428
	return hct.result, nil
}

429
// LoadCollection load a collection into query nodes.
C
Cai Yudong 已提交
430
func (node *Proxy) LoadCollection(ctx context.Context, request *milvuspb.LoadCollectionRequest) (*commonpb.Status, error) {
431 432 433
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
434 435 436 437

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
438 439
	method := "LoadCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
440
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
441
		metrics.TotalLabel).Inc()
442
	lct := &loadCollectionTask{
S
sunby 已提交
443
		ctx:                   ctx,
444 445
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
446
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
447
		indexCoord:            node.indexCoord,
448 449
	}

450 451
	log.Debug("LoadCollection received",
		zap.String("traceID", traceID),
452
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
453 454
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
455 456 457 458 459

	if err := node.sched.ddQueue.Enqueue(lct); err != nil {
		log.Warn("LoadCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
460
			zap.String("role", typeutil.ProxyRole),
461 462 463
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
464
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
465
			metrics.AbandonLabel).Inc()
466
		return &commonpb.Status{
467
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
468 469 470
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
471

472 473
	log.Debug("LoadCollection enqueued",
		zap.String("traceID", traceID),
474
		zap.String("role", typeutil.ProxyRole),
475 476 477
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
478 479
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
480 481 482

	if err := lct.WaitToFinish(); err != nil {
		log.Warn("LoadCollection failed to WaitToFinish",
D
dragondriver 已提交
483
			zap.Error(err),
484
			zap.String("traceID", traceID),
485
			zap.String("role", typeutil.ProxyRole),
486 487 488
			zap.Int64("MsgID", lct.ID()),
			zap.Uint64("BeginTS", lct.BeginTs()),
			zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
489 490
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))
E
Enwei Jiao 已提交
491
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
492
			metrics.FailLabel).Inc()
493
		return &commonpb.Status{
494
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
495 496 497 498
			Reason:    err.Error(),
		}, nil
	}

499 500
	log.Debug("LoadCollection done",
		zap.String("traceID", traceID),
501
		zap.String("role", typeutil.ProxyRole),
502 503 504 505 506 507
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
508
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
509
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
510
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
511
	return lct.result, nil
512 513
}

514
// ReleaseCollection remove the loaded collection from query nodes.
C
Cai Yudong 已提交
515
func (node *Proxy) ReleaseCollection(ctx context.Context, request *milvuspb.ReleaseCollectionRequest) (*commonpb.Status, error) {
516 517 518
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
519

520
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleaseCollection")
521 522
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
523 524
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
525
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
526
		metrics.TotalLabel).Inc()
527
	rct := &releaseCollectionTask{
S
sunby 已提交
528
		ctx:                      ctx,
529 530
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
531
		queryCoord:               node.queryCoord,
532
		chMgr:                    node.chMgr,
533 534
	}

535 536
	log.Debug(
		rpcReceived(method),
537
		zap.String("traceID", traceID),
538
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
539 540
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
541 542

	if err := node.sched.ddQueue.Enqueue(rct); err != nil {
543 544
		log.Warn(
			rpcFailedToEnqueue(method),
545 546
			zap.Error(err),
			zap.String("traceID", traceID),
547
			zap.String("role", typeutil.ProxyRole),
548 549 550
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
551
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
552
			metrics.AbandonLabel).Inc()
553
		return &commonpb.Status{
554
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
555 556 557 558
			Reason:    err.Error(),
		}, nil
	}

559 560
	log.Debug(
		rpcEnqueued(method),
561
		zap.String("traceID", traceID),
562
		zap.String("role", typeutil.ProxyRole),
563 564 565
		zap.Int64("MsgID", rct.ID()),
		zap.Uint64("BeginTS", rct.BeginTs()),
		zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
566 567
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
568 569

	if err := rct.WaitToFinish(); err != nil {
570 571
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
572
			zap.Error(err),
573
			zap.String("traceID", traceID),
574
			zap.String("role", typeutil.ProxyRole),
575 576 577
			zap.Int64("MsgID", rct.ID()),
			zap.Uint64("BeginTS", rct.BeginTs()),
			zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
578 579 580
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
581
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
582
			metrics.FailLabel).Inc()
583
		return &commonpb.Status{
584
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
585 586 587 588
			Reason:    err.Error(),
		}, nil
	}

589 590
	log.Debug(
		rpcDone(method),
591
		zap.String("traceID", traceID),
592
		zap.String("role", typeutil.ProxyRole),
593 594 595 596 597 598
		zap.Int64("MsgID", rct.ID()),
		zap.Uint64("BeginTS", rct.BeginTs()),
		zap.Uint64("EndTS", rct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
599
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
600
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
601
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
602
	return rct.result, nil
603 604
}

605
// DescribeCollection get the meta information of specific collection, such as schema, created timestamp and etc.
C
Cai Yudong 已提交
606
func (node *Proxy) DescribeCollection(ctx context.Context, request *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
607 608 609 610 611
	if !node.checkHealthy() {
		return &milvuspb.DescribeCollectionResponse{
			Status: unhealthyStatus(),
		}, nil
	}
612

613
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeCollection")
614 615
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
616 617
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
618
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
619
		metrics.TotalLabel).Inc()
620

621
	dct := &describeCollectionTask{
S
sunby 已提交
622
		ctx:                       ctx,
623 624
		Condition:                 NewTaskCondition(ctx),
		DescribeCollectionRequest: request,
625
		rootCoord:                 node.rootCoord,
626 627
	}

628 629
	log.Debug("DescribeCollection received",
		zap.String("traceID", traceID),
630
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
631 632
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
633 634 635 636 637

	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DescribeCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
638
			zap.String("role", typeutil.ProxyRole),
639 640 641
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
642
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
643
			metrics.AbandonLabel).Inc()
644 645
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
646
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
647 648 649 650 651
				Reason:    err.Error(),
			},
		}, nil
	}

652 653
	log.Debug("DescribeCollection enqueued",
		zap.String("traceID", traceID),
654
		zap.String("role", typeutil.ProxyRole),
655 656 657
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTS", dct.BeginTs()),
		zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
658 659
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
660 661 662

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DescribeCollection failed to WaitToFinish",
D
dragondriver 已提交
663
			zap.Error(err),
664
			zap.String("traceID", traceID),
665
			zap.String("role", typeutil.ProxyRole),
666 667 668
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTS", dct.BeginTs()),
			zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
669 670 671
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
672
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
673
			metrics.FailLabel).Inc()
674

675 676
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
677
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
678 679 680 681 682
				Reason:    err.Error(),
			},
		}, nil
	}

683 684
	log.Debug("DescribeCollection done",
		zap.String("traceID", traceID),
685
		zap.String("role", typeutil.ProxyRole),
686 687 688 689 690 691
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTS", dct.BeginTs()),
		zap.Uint64("EndTS", dct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
692
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
693
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
694
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
695 696 697
	return dct.result, nil
}

698 699 700 701 702 703 704 705 706
// GetStatistics get the statistics, such as `num_rows`.
// WARNING: It is an experimental API
func (node *Proxy) GetStatistics(ctx context.Context, request *milvuspb.GetStatisticsRequest) (*milvuspb.GetStatisticsResponse, error) {
	if !node.checkHealthy() {
		return &milvuspb.GetStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}

707
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetStatistics")
708 709 710 711
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
	method := "GetStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
712
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
713
		metrics.TotalLabel).Inc()
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
	g := &getStatisticsTask{
		request:   request,
		Condition: NewTaskCondition(ctx),
		ctx:       ctx,
		tr:        tr,
		dc:        node.dataCoord,
		qc:        node.queryCoord,
		shardMgr:  node.shardMgr,
	}

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Strings("partitions", request.PartitionNames))

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Strings("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
742
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
			metrics.AbandonLabel).Inc()

		return &milvuspb.GetStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Strings("partitions", request.PartitionNames))

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.Int64("MsgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Strings("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
777
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
			metrics.FailLabel).Inc()

		return &milvuspb.GetStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
798
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
799
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
800
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
801 802 803
	return g.result, nil
}

804
// GetCollectionStatistics get the collection statistics, such as `num_rows`.
C
Cai Yudong 已提交
805
func (node *Proxy) GetCollectionStatistics(ctx context.Context, request *milvuspb.GetCollectionStatisticsRequest) (*milvuspb.GetCollectionStatisticsResponse, error) {
806 807 808 809 810
	if !node.checkHealthy() {
		return &milvuspb.GetCollectionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
811 812 813 814

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetCollectionStatistics")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
815 816
	method := "GetCollectionStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
817
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
818
		metrics.TotalLabel).Inc()
819
	g := &getCollectionStatisticsTask{
G
godchen 已提交
820 821 822
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
823
		dataCoord:                      node.dataCoord,
824 825
	}

826 827
	log.Debug(
		rpcReceived(method),
828
		zap.String("traceID", traceID),
829
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
830 831
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
832 833

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
834 835
		log.Warn(
			rpcFailedToEnqueue(method),
836 837
			zap.Error(err),
			zap.String("traceID", traceID),
838
			zap.String("role", typeutil.ProxyRole),
839 840 841
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
842
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
843
			metrics.AbandonLabel).Inc()
844

G
godchen 已提交
845
		return &milvuspb.GetCollectionStatisticsResponse{
846
			Status: &commonpb.Status{
847
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
848 849 850 851 852
				Reason:    err.Error(),
			},
		}, nil
	}

853 854
	log.Debug(
		rpcEnqueued(method),
855
		zap.String("traceID", traceID),
856
		zap.String("role", typeutil.ProxyRole),
857
		zap.Int64("msgID", g.ID()),
858 859
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
D
dragondriver 已提交
860 861
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
862 863

	if err := g.WaitToFinish(); err != nil {
864 865
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
866
			zap.Error(err),
867
			zap.String("traceID", traceID),
868
			zap.String("role", typeutil.ProxyRole),
869 870 871
			zap.Int64("MsgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
D
dragondriver 已提交
872 873 874
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
875
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
876
			metrics.FailLabel).Inc()
877

G
godchen 已提交
878
		return &milvuspb.GetCollectionStatisticsResponse{
879
			Status: &commonpb.Status{
880
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
881 882 883 884 885
				Reason:    err.Error(),
			},
		}, nil
	}

886 887
	log.Debug(
		rpcDone(method),
888
		zap.String("traceID", traceID),
889
		zap.String("role", typeutil.ProxyRole),
890
		zap.Int64("msgID", g.ID()),
891 892 893 894 895
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
896
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
897
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
898
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
899
	return g.result, nil
900 901
}

902
// ShowCollections list all collections in Milvus.
C
Cai Yudong 已提交
903
func (node *Proxy) ShowCollections(ctx context.Context, request *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
904 905 906 907 908
	if !node.checkHealthy() {
		return &milvuspb.ShowCollectionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
909 910
	method := "ShowCollections"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
911
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
912

913
	sct := &showCollectionsTask{
G
godchen 已提交
914 915 916
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
917
		queryCoord:             node.queryCoord,
918
		rootCoord:              node.rootCoord,
919 920
	}

921
	log.Debug("ShowCollections received",
922
		zap.String("role", typeutil.ProxyRole),
923 924 925 926 927 928
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
		zap.Any("CollectionNames", request.CollectionNames),
	)

929
	err := node.sched.ddQueue.Enqueue(sct)
930
	if err != nil {
931 932
		log.Warn("ShowCollections failed to enqueue",
			zap.Error(err),
933
			zap.String("role", typeutil.ProxyRole),
934 935 936 937 938 939
			zap.String("DbName", request.DbName),
			zap.Uint64("TimeStamp", request.TimeStamp),
			zap.String("ShowType", request.Type.String()),
			zap.Any("CollectionNames", request.CollectionNames),
		)

E
Enwei Jiao 已提交
940
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
G
godchen 已提交
941
		return &milvuspb.ShowCollectionsResponse{
942
			Status: &commonpb.Status{
943
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
944 945 946 947 948
				Reason:    err.Error(),
			},
		}, nil
	}

949
	log.Debug("ShowCollections enqueued",
950
		zap.String("role", typeutil.ProxyRole),
951
		zap.Int64("MsgID", sct.ID()),
952
		zap.String("DbName", sct.ShowCollectionsRequest.DbName),
953
		zap.Uint64("TimeStamp", request.TimeStamp),
954 955 956
		zap.String("ShowType", sct.ShowCollectionsRequest.Type.String()),
		zap.Any("CollectionNames", sct.ShowCollectionsRequest.CollectionNames),
	)
D
dragondriver 已提交
957

958 959
	err = sct.WaitToFinish()
	if err != nil {
960 961
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
962
			zap.String("role", typeutil.ProxyRole),
963 964 965 966 967 968 969
			zap.Int64("MsgID", sct.ID()),
			zap.String("DbName", request.DbName),
			zap.Uint64("TimeStamp", request.TimeStamp),
			zap.String("ShowType", request.Type.String()),
			zap.Any("CollectionNames", request.CollectionNames),
		)

E
Enwei Jiao 已提交
970
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
971

G
godchen 已提交
972
		return &milvuspb.ShowCollectionsResponse{
973
			Status: &commonpb.Status{
974
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
975 976 977 978 979
				Reason:    err.Error(),
			},
		}, nil
	}

980
	log.Debug("ShowCollections Done",
981
		zap.String("role", typeutil.ProxyRole),
982 983 984 985
		zap.Int64("MsgID", sct.ID()),
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
986 987
		zap.Int("len(CollectionNames)", len(request.CollectionNames)),
		zap.Int("num_collections", len(sct.result.CollectionNames)))
988

E
Enwei Jiao 已提交
989 990
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
991 992 993
	return sct.result, nil
}

J
jaime 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004
func (node *Proxy) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-AlterCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
	method := "AlterCollection"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
1005
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
J
jaime 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

	act := &alterCollectionTask{
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		AlterCollectionRequest: request,
		rootCoord:              node.rootCoord,
	}

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

	if err := node.sched.ddQueue.Enqueue(act); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
1030
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
J
jaime 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", act.ID()),
		zap.Uint64("BeginTs", act.BeginTs()),
		zap.Uint64("EndTs", act.EndTs()),
		zap.Uint64("timestamp", request.Base.Timestamp),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

	if err := act.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.Int64("MsgID", act.ID()),
			zap.Uint64("BeginTs", act.BeginTs()),
			zap.Uint64("EndTs", act.EndTs()),
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
1060
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
J
jaime 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", act.ID()),
		zap.Uint64("BeginTs", act.BeginTs()),
		zap.Uint64("EndTs", act.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
1077 1078
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
J
jaime 已提交
1079 1080 1081
	return act.result, nil
}

1082
// CreatePartition create a partition in specific collection.
C
Cai Yudong 已提交
1083
func (node *Proxy) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
1084 1085 1086
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1087

1088
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreatePartition")
1089 1090
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1091 1092
	method := "CreatePartition"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1093
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1094

1095
	cpt := &createPartitionTask{
S
sunby 已提交
1096
		ctx:                    ctx,
1097 1098
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
1099
		rootCoord:              node.rootCoord,
1100 1101 1102
		result:                 nil,
	}

1103 1104 1105
	log.Debug(
		rpcReceived("CreatePartition"),
		zap.String("traceID", traceID),
1106
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1107 1108 1109
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1110 1111 1112 1113 1114 1115

	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
			zap.Error(err),
			zap.String("traceID", traceID),
1116
			zap.String("role", typeutil.ProxyRole),
1117 1118 1119 1120
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1121
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1122

1123
		return &commonpb.Status{
1124
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1125 1126 1127
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1128

1129 1130 1131
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.String("traceID", traceID),
1132
		zap.String("role", typeutil.ProxyRole),
1133 1134 1135
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1136 1137 1138
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1139 1140 1141 1142

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
1143
			zap.Error(err),
1144
			zap.String("traceID", traceID),
1145
			zap.String("role", typeutil.ProxyRole),
1146 1147 1148
			zap.Int64("MsgID", cpt.ID()),
			zap.Uint64("BeginTS", cpt.BeginTs()),
			zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1149 1150 1151 1152
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1153
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1154

1155
		return &commonpb.Status{
1156
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1157 1158 1159
			Reason:    err.Error(),
		}, nil
	}
1160 1161 1162 1163

	log.Debug(
		rpcDone("CreatePartition"),
		zap.String("traceID", traceID),
1164
		zap.String("role", typeutil.ProxyRole),
1165 1166 1167 1168 1169 1170 1171
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1172 1173
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1174 1175 1176
	return cpt.result, nil
}

1177
// DropPartition drop a partition in specific collection.
C
Cai Yudong 已提交
1178
func (node *Proxy) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
1179 1180 1181
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1182

1183
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropPartition")
1184 1185
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1186 1187
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1188
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1189

1190
	dpt := &dropPartitionTask{
S
sunby 已提交
1191
		ctx:                  ctx,
1192 1193
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
1194
		rootCoord:            node.rootCoord,
C
cai.zhang 已提交
1195
		queryCoord:           node.queryCoord,
1196 1197 1198
		result:               nil,
	}

1199 1200 1201
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1202
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1203 1204 1205
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1206 1207 1208 1209 1210 1211

	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1212
			zap.String("role", typeutil.ProxyRole),
1213 1214 1215 1216
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1217
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1218

1219
		return &commonpb.Status{
1220
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1221 1222 1223
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1224

1225 1226 1227
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1228
		zap.String("role", typeutil.ProxyRole),
1229 1230 1231
		zap.Int64("MsgID", dpt.ID()),
		zap.Uint64("BeginTS", dpt.BeginTs()),
		zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1232 1233 1234
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1235 1236 1237 1238

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1239
			zap.Error(err),
1240
			zap.String("traceID", traceID),
1241
			zap.String("role", typeutil.ProxyRole),
1242 1243 1244
			zap.Int64("MsgID", dpt.ID()),
			zap.Uint64("BeginTS", dpt.BeginTs()),
			zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1245 1246 1247 1248
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1249
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1250

1251
		return &commonpb.Status{
1252
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1253 1254 1255
			Reason:    err.Error(),
		}, nil
	}
1256 1257 1258 1259

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1260
		zap.String("role", typeutil.ProxyRole),
1261 1262 1263 1264 1265 1266 1267
		zap.Int64("MsgID", dpt.ID()),
		zap.Uint64("BeginTS", dpt.BeginTs()),
		zap.Uint64("EndTS", dpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1268 1269
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1270 1271 1272
	return dpt.result, nil
}

1273
// HasPartition check if partition exist.
C
Cai Yudong 已提交
1274
func (node *Proxy) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
1275 1276 1277 1278 1279
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
D
dragondriver 已提交
1280

D
dragondriver 已提交
1281
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasPartition")
D
dragondriver 已提交
1282 1283
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1284 1285 1286
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
E
Enwei Jiao 已提交
1287
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1288
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1289

1290
	hpt := &hasPartitionTask{
S
sunby 已提交
1291
		ctx:                 ctx,
1292 1293
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1294
		rootCoord:           node.rootCoord,
1295 1296 1297
		result:              nil,
	}

D
dragondriver 已提交
1298 1299 1300
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1301
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1302 1303 1304
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1305 1306 1307 1308 1309 1310

	if err := node.sched.ddQueue.Enqueue(hpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1311
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1312 1313 1314 1315
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1316
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1317
			metrics.AbandonLabel).Inc()
1318

1319 1320
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1321
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1322 1323 1324 1325 1326
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1327

D
dragondriver 已提交
1328 1329 1330
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1331
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1332 1333 1334
		zap.Int64("MsgID", hpt.ID()),
		zap.Uint64("BeginTS", hpt.BeginTs()),
		zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1335 1336 1337
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1338 1339 1340 1341

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1342
			zap.Error(err),
D
dragondriver 已提交
1343
			zap.String("traceID", traceID),
1344
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1345 1346 1347
			zap.Int64("MsgID", hpt.ID()),
			zap.Uint64("BeginTS", hpt.BeginTs()),
			zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1348 1349 1350 1351
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1352
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1353
			metrics.FailLabel).Inc()
1354

1355 1356
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1357
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1358 1359 1360 1361 1362
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1363 1364 1365 1366

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1367
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1368 1369 1370 1371 1372 1373 1374
		zap.Int64("MsgID", hpt.ID()),
		zap.Uint64("BeginTS", hpt.BeginTs()),
		zap.Uint64("EndTS", hpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1375
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1376
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1377
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1378 1379 1380
	return hpt.result, nil
}

1381
// LoadPartitions load specific partitions into query nodes.
C
Cai Yudong 已提交
1382
func (node *Proxy) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
1383 1384 1385
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1386

D
dragondriver 已提交
1387
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadPartitions")
1388 1389
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1390 1391
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1392
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1393
		metrics.TotalLabel).Inc()
1394
	lpt := &loadPartitionsTask{
G
godchen 已提交
1395 1396 1397
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1398
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
1399
		indexCoord:            node.indexCoord,
1400 1401
	}

1402 1403 1404
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1405
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1406 1407 1408
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1409 1410 1411 1412 1413 1414

	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1415
			zap.String("role", typeutil.ProxyRole),
1416 1417 1418 1419
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1420
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1421
			metrics.AbandonLabel).Inc()
1422

1423
		return &commonpb.Status{
1424
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1425 1426 1427 1428
			Reason:    err.Error(),
		}, nil
	}

1429 1430 1431
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1432
		zap.String("role", typeutil.ProxyRole),
1433 1434 1435
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1436 1437 1438
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1439 1440 1441 1442

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1443
			zap.Error(err),
1444
			zap.String("traceID", traceID),
1445
			zap.String("role", typeutil.ProxyRole),
1446 1447 1448
			zap.Int64("MsgID", lpt.ID()),
			zap.Uint64("BeginTS", lpt.BeginTs()),
			zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1449 1450 1451 1452
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1453
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1454
			metrics.FailLabel).Inc()
1455

1456
		return &commonpb.Status{
1457
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1458 1459 1460 1461
			Reason:    err.Error(),
		}, nil
	}

1462 1463 1464
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1465
		zap.String("role", typeutil.ProxyRole),
1466 1467 1468 1469 1470 1471 1472
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1473
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1474
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1475
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1476
	return lpt.result, nil
1477 1478
}

1479
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1480
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1481 1482 1483
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1484 1485 1486 1487 1488

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleasePartitions")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

1489
	rpt := &releasePartitionsTask{
G
godchen 已提交
1490 1491 1492
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1493
		queryCoord:               node.queryCoord,
1494 1495
	}

1496
	method := "ReleasePartitions"
1497
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1498
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1499
		metrics.TotalLabel).Inc()
1500 1501 1502
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1503
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1504 1505 1506
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1507 1508 1509 1510 1511 1512

	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1513
			zap.String("role", typeutil.ProxyRole),
1514 1515 1516 1517
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1518
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1519
			metrics.AbandonLabel).Inc()
1520

1521
		return &commonpb.Status{
1522
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1523 1524 1525 1526
			Reason:    err.Error(),
		}, nil
	}

1527 1528 1529
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1530
		zap.String("role", typeutil.ProxyRole),
1531 1532 1533
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1534 1535 1536
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1537 1538 1539 1540

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1541
			zap.Error(err),
1542
			zap.String("traceID", traceID),
1543
			zap.String("role", typeutil.ProxyRole),
1544 1545 1546
			zap.Int64("msgID", rpt.Base.MsgID),
			zap.Uint64("BeginTS", rpt.BeginTs()),
			zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1547 1548 1549 1550
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1551
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1552
			metrics.FailLabel).Inc()
1553

1554
		return &commonpb.Status{
1555
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1556 1557 1558 1559
			Reason:    err.Error(),
		}, nil
	}

1560 1561 1562
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1563
		zap.String("role", typeutil.ProxyRole),
1564 1565 1566 1567 1568 1569 1570
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
1571
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1572
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1573
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1574
	return rpt.result, nil
1575 1576
}

1577
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1578
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1579 1580 1581 1582 1583
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1584 1585 1586 1587

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetPartitionStatistics")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1588 1589
	method := "GetPartitionStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1590
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1591
		metrics.TotalLabel).Inc()
1592

1593
	g := &getPartitionStatisticsTask{
1594 1595 1596
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1597
		dataCoord:                     node.dataCoord,
1598 1599
	}

1600 1601 1602
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1603
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1604 1605 1606
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1607 1608 1609 1610 1611 1612

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1613
			zap.String("role", typeutil.ProxyRole),
1614 1615 1616 1617
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1618
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1619
			metrics.AbandonLabel).Inc()
1620

1621 1622 1623 1624 1625 1626 1627 1628
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1629 1630 1631
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1632
		zap.String("role", typeutil.ProxyRole),
1633 1634 1635
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
1636 1637 1638
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1639 1640 1641 1642

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1643
			zap.Error(err),
1644
			zap.String("traceID", traceID),
1645
			zap.String("role", typeutil.ProxyRole),
1646 1647 1648
			zap.Int64("msgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
1649 1650 1651 1652
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1653
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1654
			metrics.FailLabel).Inc()
1655

1656 1657 1658 1659 1660 1661 1662 1663
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1664 1665 1666
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1667
		zap.String("role", typeutil.ProxyRole),
1668 1669 1670 1671 1672 1673 1674
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

E
Enwei Jiao 已提交
1675
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1676
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1677
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1678
	return g.result, nil
1679 1680
}

1681
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1682
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1683 1684 1685 1686 1687
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1688 1689 1690 1691 1692

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ShowPartitions")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

1693
	spt := &showPartitionsTask{
G
godchen 已提交
1694 1695 1696
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1697
		rootCoord:             node.rootCoord,
1698
		queryCoord:            node.queryCoord,
G
godchen 已提交
1699
		result:                nil,
1700 1701
	}

1702
	method := "ShowPartitions"
1703 1704
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
E
Enwei Jiao 已提交
1705
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1706
		metrics.TotalLabel).Inc()
1707 1708 1709 1710

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1711
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1712
		zap.Any("request", request))
1713 1714 1715 1716 1717 1718

	if err := node.sched.ddQueue.Enqueue(spt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1719
			zap.String("role", typeutil.ProxyRole),
1720 1721
			zap.Any("request", request))

E
Enwei Jiao 已提交
1722
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1723
			metrics.AbandonLabel).Inc()
1724

G
godchen 已提交
1725
		return &milvuspb.ShowPartitionsResponse{
1726
			Status: &commonpb.Status{
1727
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1728 1729 1730 1731 1732
				Reason:    err.Error(),
			},
		}, nil
	}

1733 1734 1735
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1736
		zap.String("role", typeutil.ProxyRole),
1737 1738 1739
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1740 1741
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1742 1743 1744 1745 1746
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1747
			zap.Error(err),
1748
			zap.String("traceID", traceID),
1749
			zap.String("role", typeutil.ProxyRole),
1750 1751 1752 1753 1754 1755
			zap.Int64("msgID", spt.ID()),
			zap.Uint64("BeginTS", spt.BeginTs()),
			zap.Uint64("EndTS", spt.EndTs()),
			zap.String("db", spt.ShowPartitionsRequest.DbName),
			zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
			zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))
D
dragondriver 已提交
1756

E
Enwei Jiao 已提交
1757
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1758
			metrics.FailLabel).Inc()
1759

G
godchen 已提交
1760
		return &milvuspb.ShowPartitionsResponse{
1761
			Status: &commonpb.Status{
1762
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1763 1764 1765 1766
				Reason:    err.Error(),
			},
		}, nil
	}
1767 1768 1769 1770

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1771
		zap.String("role", typeutil.ProxyRole),
1772 1773 1774 1775 1776 1777 1778
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

E
Enwei Jiao 已提交
1779
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1780
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1781
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1782 1783 1784
	return spt.result, nil
}

S
SimFG 已提交
1785 1786
func (node *Proxy) getCollectionProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest, collectionID int64) (int64, error) {
	resp, err := node.queryCoord.ShowCollections(ctx, &querypb.ShowCollectionsRequest{
S
smellthemoon 已提交
1787
		Base: commonpbutil.UpdateMsgBase(
1788 1789 1790
			request.Base,
			commonpbutil.WithMsgType(commonpb.MsgType_DescribeCollection),
		),
S
SimFG 已提交
1791 1792 1793 1794 1795
		CollectionIDs: []int64{collectionID},
	})
	if err != nil {
		return 0, err
	}
X
xige-16 已提交
1796 1797 1798 1799 1800

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

S
SimFG 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
	if len(resp.InMemoryPercentages) == 0 {
		return 0, errors.New("fail to show collections from the querycoord, no data")
	}
	return resp.InMemoryPercentages[0], nil
}

func (node *Proxy) getPartitionProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest, collectionID int64) (int64, error) {
	IDs2Names := make(map[int64]string)
	partitionIDs := make([]int64, 0)
	for _, partitionName := range request.PartitionNames {
		partitionID, err := globalMetaCache.GetPartitionID(ctx, request.CollectionName, partitionName)
		if err != nil {
			return 0, err
		}
		IDs2Names[partitionID] = partitionName
		partitionIDs = append(partitionIDs, partitionID)
	}
	resp, err := node.queryCoord.ShowPartitions(ctx, &querypb.ShowPartitionsRequest{
S
smellthemoon 已提交
1819
		Base: commonpbutil.UpdateMsgBase(
1820 1821 1822
			request.Base,
			commonpbutil.WithMsgType(commonpb.MsgType_ShowPartitions),
		),
S
SimFG 已提交
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
		CollectionID: collectionID,
		PartitionIDs: partitionIDs,
	})
	if err != nil {
		return 0, err
	}
	if len(resp.InMemoryPercentages) != len(partitionIDs) {
		return 0, errors.New("fail to show partitions from the querycoord, invalid data num")
	}
	var progress int64
	for _, p := range resp.InMemoryPercentages {
		progress += p
	}
	progress /= int64(len(partitionIDs))
	return progress, nil
}

func (node *Proxy) GetLoadingProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest) (*milvuspb.GetLoadingProgressResponse, error) {
	if !node.checkHealthy() {
		return &milvuspb.GetLoadingProgressResponse{Status: unhealthyStatus()}, nil
	}
	method := "GetLoadingProgress"
	tr := timerecord.NewTimeRecorder(method)
1846
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetLoadingProgress")
S
SimFG 已提交
1847 1848
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
E
Enwei Jiao 已提交
1849
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
S
SimFG 已提交
1850 1851 1852 1853 1854 1855 1856 1857
	logger.Info(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.Any("request", request))

	getErrResponse := func(err error) *milvuspb.GetLoadingProgressResponse {
		logger.Error("fail to get loading progress", zap.String("collection_name", request.CollectionName),
			zap.Strings("partition_name", request.PartitionNames), zap.Error(err))
E
Enwei Jiao 已提交
1858
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
S
SimFG 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
		return &milvuspb.GetLoadingProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}
	}
	if err := validateCollectionName(request.CollectionName); err != nil {
		return getErrResponse(err), nil
	}
	collectionID, err := globalMetaCache.GetCollectionID(ctx, request.CollectionName)
	if err != nil {
		return getErrResponse(err), nil
	}
1873 1874 1875 1876
	msgBase := commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
		commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
1877
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
1878
	)
S
SimFG 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
	if request.Base == nil {
		request.Base = msgBase
	} else {
		request.Base.MsgID = msgBase.MsgID
		request.Base.Timestamp = msgBase.Timestamp
		request.Base.SourceID = msgBase.SourceID
	}

	var progress int64
	if len(request.GetPartitionNames()) == 0 {
		if progress, err = node.getCollectionProgress(ctx, request, collectionID); err != nil {
			return getErrResponse(err), nil
		}
	} else {
		if progress, err = node.getPartitionProgress(ctx, request, collectionID); err != nil {
			return getErrResponse(err), nil
		}
	}

	logger.Info(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.Any("request", request))
E
Enwei Jiao 已提交
1902 1903
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
S
SimFG 已提交
1904 1905 1906 1907 1908 1909 1910 1911
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1912
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1913
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1914 1915 1916
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1917

1918
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreateIndex")
D
dragondriver 已提交
1919 1920 1921
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

1922
	cit := &createIndexTask{
Z
zhenshan.cao 已提交
1923 1924 1925 1926 1927
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		req:        request,
		rootCoord:  node.rootCoord,
		indexCoord: node.indexCoord,
1928
		queryCoord: node.queryCoord,
1929 1930
	}

D
dragondriver 已提交
1931
	method := "CreateIndex"
1932
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1933
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1934
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1935 1936 1937
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1938
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1939 1940 1941 1942
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1943 1944 1945 1946 1947 1948

	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1949
			zap.String("role", typeutil.ProxyRole),
Z
zhenshan.cao 已提交
1950 1951 1952 1953
			zap.String("db", request.GetDbName()),
			zap.String("collection", request.GetCollectionName()),
			zap.String("field", request.GetFieldName()),
			zap.Any("extra_params", request.GetExtraParams()))
D
dragondriver 已提交
1954

E
Enwei Jiao 已提交
1955
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1956
			metrics.AbandonLabel).Inc()
1957

1958
		return &commonpb.Status{
1959
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1960 1961 1962 1963
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1964 1965 1966
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1967
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1968 1969 1970
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1971 1972 1973 1974
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1975 1976 1977 1978

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1979
			zap.Error(err),
D
dragondriver 已提交
1980
			zap.String("traceID", traceID),
1981
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1982 1983 1984
			zap.Int64("MsgID", cit.ID()),
			zap.Uint64("BeginTs", cit.BeginTs()),
			zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1985 1986 1987 1988 1989
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

E
Enwei Jiao 已提交
1990
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1991
			metrics.FailLabel).Inc()
1992

1993
		return &commonpb.Status{
1994
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1995 1996 1997 1998
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1999 2000 2001
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2002
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2003 2004 2005 2006 2007 2008 2009 2010
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))

E
Enwei Jiao 已提交
2011
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2012
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2013
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2014 2015 2016
	return cit.result, nil
}

2017
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
2018
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
2019 2020 2021 2022 2023
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2024 2025 2026 2027 2028

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeIndex")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

2029
	dit := &describeIndexTask{
S
sunby 已提交
2030
		ctx:                  ctx,
2031 2032
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
2033
		indexCoord:           node.indexCoord,
2034 2035
	}

2036 2037 2038
	method := "DescribeIndex"
	// avoid data race
	indexName := request.IndexName
2039
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2040
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2041
		metrics.TotalLabel).Inc()
2042 2043 2044
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2045
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2046 2047 2048
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2049 2050 2051 2052 2053 2054 2055
		zap.String("index name", indexName))

	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2056
			zap.String("role", typeutil.ProxyRole),
2057 2058 2059 2060 2061
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", indexName))

E
Enwei Jiao 已提交
2062
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2063
			metrics.AbandonLabel).Inc()
2064

2065 2066
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
2067
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2068 2069 2070 2071 2072
				Reason:    err.Error(),
			},
		}, nil
	}

2073 2074 2075
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2076
		zap.String("role", typeutil.ProxyRole),
2077 2078 2079
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2080 2081 2082
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2083 2084 2085 2086 2087
		zap.String("index name", indexName))

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2088
			zap.Error(err),
2089
			zap.String("traceID", traceID),
2090
			zap.String("role", typeutil.ProxyRole),
2091 2092 2093
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2094 2095 2096
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
2097
			zap.String("index name", indexName))
D
dragondriver 已提交
2098

Z
zhenshan.cao 已提交
2099 2100 2101 2102
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
E
Enwei Jiao 已提交
2103
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2104
			metrics.FailLabel).Inc()
2105

2106 2107
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
2108
				ErrorCode: errCode,
2109 2110 2111 2112 2113
				Reason:    err.Error(),
			},
		}, nil
	}

2114 2115 2116
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2117
		zap.String("role", typeutil.ProxyRole),
2118 2119 2120 2121 2122 2123 2124 2125
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", indexName))

E
Enwei Jiao 已提交
2126
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2127
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2128
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2129 2130 2131
	return dit.result, nil
}

2132
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
2133
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
2134 2135 2136
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2137 2138 2139 2140 2141

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropIndex")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

2142
	dit := &dropIndexTask{
S
sunby 已提交
2143
		ctx:              ctx,
B
BossZou 已提交
2144 2145
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
2146
		indexCoord:       node.indexCoord,
2147
		queryCoord:       node.queryCoord,
B
BossZou 已提交
2148
	}
G
godchen 已提交
2149

D
dragondriver 已提交
2150
	method := "DropIndex"
2151
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2152
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2153
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2154 2155 2156 2157

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2158
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2159 2160 2161 2162 2163
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

D
dragondriver 已提交
2164 2165 2166 2167 2168
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2169
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2170 2171 2172 2173
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
E
Enwei Jiao 已提交
2174
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2175
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2176

B
BossZou 已提交
2177
		return &commonpb.Status{
2178
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2179 2180 2181
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2182

D
dragondriver 已提交
2183 2184 2185
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2186
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2187 2188 2189
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2190 2191 2192 2193
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
D
dragondriver 已提交
2194 2195 2196 2197

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2198
			zap.Error(err),
D
dragondriver 已提交
2199
			zap.String("traceID", traceID),
2200
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2201 2202 2203
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2204 2205 2206 2207 2208
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

E
Enwei Jiao 已提交
2209
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2210
			metrics.FailLabel).Inc()
2211

B
BossZou 已提交
2212
		return &commonpb.Status{
2213
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2214 2215 2216
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2217 2218 2219 2220

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2221
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2222 2223 2224 2225 2226 2227 2228 2229
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

E
Enwei Jiao 已提交
2230
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2231
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2232
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
2233 2234 2235
	return dit.result, nil
}

2236 2237
// GetIndexBuildProgress gets index build progress with filed_name and index_name.
// IndexRows is the num of indexed rows. And TotalRows is the total number of segment rows.
2238
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2239
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
2240 2241 2242 2243 2244
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2245 2246 2247 2248 2249

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetIndexBuildProgress")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

2250
	gibpt := &getIndexBuildProgressTask{
2251 2252 2253
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
2254 2255
		indexCoord:                   node.indexCoord,
		rootCoord:                    node.rootCoord,
2256
		dataCoord:                    node.dataCoord,
2257 2258
	}

2259
	method := "GetIndexBuildProgress"
2260
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2261
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2262
		metrics.TotalLabel).Inc()
2263 2264 2265
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2266
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2267 2268 2269 2270
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2271 2272 2273 2274 2275 2276

	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2277
			zap.String("role", typeutil.ProxyRole),
2278 2279 2280 2281
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
E
Enwei Jiao 已提交
2282
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2283
			metrics.AbandonLabel).Inc()
2284

2285 2286 2287 2288 2289 2290 2291 2292
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2293 2294 2295
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2296
		zap.String("role", typeutil.ProxyRole),
2297 2298 2299
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
2300 2301 2302 2303
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2304 2305 2306 2307

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
2308
			zap.Error(err),
2309
			zap.String("traceID", traceID),
2310
			zap.String("role", typeutil.ProxyRole),
2311 2312 2313
			zap.Int64("MsgID", gibpt.ID()),
			zap.Uint64("BeginTs", gibpt.BeginTs()),
			zap.Uint64("EndTs", gibpt.EndTs()),
2314 2315 2316 2317
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
E
Enwei Jiao 已提交
2318
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2319
			metrics.FailLabel).Inc()
2320 2321 2322 2323 2324 2325 2326 2327

		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2328 2329 2330 2331

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2332
		zap.String("role", typeutil.ProxyRole),
2333 2334 2335 2336 2337 2338 2339 2340
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName),
		zap.Any("result", gibpt.result))
2341

E
Enwei Jiao 已提交
2342
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2343
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2344
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2345
	return gibpt.result, nil
2346 2347
}

2348
// GetIndexState get the build-state of index.
2349
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2350
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
2351 2352 2353 2354 2355
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2356 2357 2358 2359 2360

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Insert")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

2361
	dipt := &getIndexStateTask{
G
godchen 已提交
2362 2363 2364
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
2365 2366
		indexCoord:           node.indexCoord,
		rootCoord:            node.rootCoord,
2367 2368
	}

2369
	method := "GetIndexState"
2370
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2371
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2372
		metrics.TotalLabel).Inc()
2373 2374 2375
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2376
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2377 2378 2379 2380
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2381 2382 2383 2384 2385 2386

	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2387
			zap.String("role", typeutil.ProxyRole),
2388 2389 2390 2391 2392
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

E
Enwei Jiao 已提交
2393
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2394
			metrics.AbandonLabel).Inc()
2395

G
godchen 已提交
2396
		return &milvuspb.GetIndexStateResponse{
2397
			Status: &commonpb.Status{
2398
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2399 2400 2401 2402 2403
				Reason:    err.Error(),
			},
		}, nil
	}

2404 2405 2406
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2407
		zap.String("role", typeutil.ProxyRole),
2408 2409 2410
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2411 2412 2413 2414
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2415 2416 2417 2418

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2419
			zap.Error(err),
2420
			zap.String("traceID", traceID),
2421
			zap.String("role", typeutil.ProxyRole),
2422 2423 2424
			zap.Int64("MsgID", dipt.ID()),
			zap.Uint64("BeginTs", dipt.BeginTs()),
			zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2425 2426 2427 2428
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
E
Enwei Jiao 已提交
2429
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2430
			metrics.FailLabel).Inc()
2431

G
godchen 已提交
2432
		return &milvuspb.GetIndexStateResponse{
2433
			Status: &commonpb.Status{
2434
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2435 2436 2437 2438 2439
				Reason:    err.Error(),
			},
		}, nil
	}

2440 2441 2442
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2443
		zap.String("role", typeutil.ProxyRole),
2444 2445 2446 2447 2448 2449 2450 2451
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

E
Enwei Jiao 已提交
2452
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2453
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2454
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2455 2456 2457
	return dipt.result, nil
}

2458
// Insert insert records into collection.
C
Cai Yudong 已提交
2459
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
X
Xiangyu Wang 已提交
2460 2461 2462 2463 2464 2465
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Insert")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
	log.Info("Start processing insert request in Proxy", zap.String("traceID", traceID))
	defer log.Info("Finish processing insert request in Proxy", zap.String("traceID", traceID))

2466 2467 2468 2469 2470
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2471 2472
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
2473
	receiveSize := proto.Size(request)
2474
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(receiveSize))
E
Enwei Jiao 已提交
2475
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel).Add(float64(receiveSize))
D
dragondriver 已提交
2476

E
Enwei Jiao 已提交
2477
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
2478
	it := &insertTask{
2479 2480
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2481
		// req:       request,
2482 2483 2484 2485
		BaseInsertTask: BaseInsertTask{
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2486
			InsertRequest: internalpb.InsertRequest{
2487 2488 2489
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Insert),
					commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
2490
					commonpbutil.WithSourceID(paramtable.GetNodeID()),
2491
				),
2492 2493
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2494 2495 2496
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
				Version:        internalpb.InsertDataVersion_ColumnBased,
2497
				// RowData: transfer column based request to this
2498 2499
			},
		},
2500
		idAllocator:   node.rowIDAllocator,
2501 2502 2503
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2504
	}
2505 2506

	if len(it.PartitionName) <= 0 {
2507
		it.PartitionName = Params.CommonCfg.DefaultPartitionName
2508 2509
	}

X
Xiangyu Wang 已提交
2510
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2511
		numRows := request.NumRows
2512 2513 2514 2515
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2516

X
Xiangyu Wang 已提交
2517 2518 2519 2520 2521 2522 2523
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2524 2525
	}

X
Xiangyu Wang 已提交
2526
	log.Debug("Enqueue insert request in Proxy",
2527
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2528 2529 2530 2531 2532
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.Int("len(FieldsData)", len(request.FieldsData)),
		zap.Int("len(HashKeys)", len(request.HashKeys)),
2533 2534
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))
D
dragondriver 已提交
2535

X
Xiangyu Wang 已提交
2536 2537
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Debug("Failed to enqueue insert task: " + err.Error())
E
Enwei Jiao 已提交
2538
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2539
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2540
		return constructFailedResponse(err), nil
2541
	}
D
dragondriver 已提交
2542

X
Xiangyu Wang 已提交
2543
	log.Debug("Detail of insert request in Proxy",
2544
		zap.String("role", typeutil.ProxyRole),
X
Xiangyu Wang 已提交
2545
		zap.Int64("msgID", it.Base.MsgID),
D
dragondriver 已提交
2546 2547 2548 2549 2550
		zap.Uint64("BeginTS", it.BeginTs()),
		zap.Uint64("EndTS", it.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
X
Xiangyu Wang 已提交
2551 2552 2553 2554 2555
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))

	if err := it.WaitToFinish(); err != nil {
		log.Debug("Failed to execute insert task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
E
Enwei Jiao 已提交
2556
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2557
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2558 2559 2560 2561 2562
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2563
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
			errIndex := make([]uint32, numRows)
			for i := uint32(0); i < numRows; i++ {
				errIndex[i] = i
			}
			it.result.ErrIndex = errIndex
		}

		setErrorIndex()
	}

	// InsertCnt always equals to the number of entities in the request
X
xige-16 已提交
2575
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2576

E
Enwei Jiao 已提交
2577
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2578
		metrics.SuccessLabel).Inc()
2579
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
E
Enwei Jiao 已提交
2580 2581 2582
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(successCnt))
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
2583 2584 2585
	return it.result, nil
}

2586
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2587
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
2588 2589 2590
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Delete")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2591 2592
	log.Info("Start processing delete request in Proxy", zap.String("traceID", traceID))
	defer log.Info("Finish processing delete request in Proxy", zap.String("traceID", traceID))
2593

2594
	receiveSize := proto.Size(request)
2595
	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(receiveSize))
E
Enwei Jiao 已提交
2596
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel).Add(float64(receiveSize))
2597

G
groot 已提交
2598 2599 2600 2601 2602 2603
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2604 2605 2606
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
2607
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2608
		metrics.TotalLabel).Inc()
2609
	dt := &deleteTask{
X
xige-16 已提交
2610 2611 2612
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
G
godchen 已提交
2613
		BaseDeleteTask: BaseDeleteTask{
G
godchen 已提交
2614 2615 2616
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2617
			DeleteRequest: internalpb.DeleteRequest{
2618 2619 2620 2621
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Delete),
					commonpbutil.WithMsgID(0),
				),
X
xige-16 已提交
2622
				DbName:         request.DbName,
G
godchen 已提交
2623 2624 2625
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2626 2627 2628 2629
			},
		},
		chMgr:    node.chMgr,
		chTicker: node.chTicker,
G
groot 已提交
2630 2631
	}

2632
	log.Debug("Enqueue delete request in Proxy",
2633
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2634 2635 2636 2637
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2638 2639 2640 2641

	// MsgID will be set by Enqueue()
	if err := node.sched.dmQueue.Enqueue(dt); err != nil {
		log.Error("Failed to enqueue delete task: "+err.Error(), zap.String("traceID", traceID))
E
Enwei Jiao 已提交
2642
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2643
			metrics.AbandonLabel).Inc()
2644

G
groot 已提交
2645 2646 2647 2648 2649 2650 2651 2652
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2653
	log.Debug("Detail of delete request in Proxy",
2654
		zap.String("role", typeutil.ProxyRole),
G
groot 已提交
2655 2656 2657 2658 2659
		zap.Int64("msgID", dt.Base.MsgID),
		zap.Uint64("timestamp", dt.Base.Timestamp),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
2660 2661
		zap.String("expr", request.Expr),
		zap.String("traceID", traceID))
G
groot 已提交
2662

2663 2664
	if err := dt.WaitToFinish(); err != nil {
		log.Error("Failed to execute delete task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
E
Enwei Jiao 已提交
2665
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2666
			metrics.FailLabel).Inc()
G
groot 已提交
2667 2668 2669 2670 2671 2672 2673 2674
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

E
Enwei Jiao 已提交
2675
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2676
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2677 2678
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2679 2680 2681
	return dt.result, nil
}

2682
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2683
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2684
	receiveSize := proto.Size(request)
E
Enwei Jiao 已提交
2685
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.SearchLabel).Add(float64(receiveSize))
2686 2687 2688

	rateCol.Add(internalpb.RateType_DQLSearch.String(), float64(request.GetNq()))

2689 2690 2691 2692 2693
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2694 2695
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2696
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2697
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2698

C
cai.zhang 已提交
2699 2700
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Search")
	defer sp.Finish()
D
dragondriver 已提交
2701

2702
	qt := &searchTask{
S
sunby 已提交
2703
		ctx:       ctx,
2704
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2705
		SearchRequest: &internalpb.SearchRequest{
2706 2707
			Base: commonpbutil.NewMsgBase(
				commonpbutil.WithMsgType(commonpb.MsgType_Search),
E
Enwei Jiao 已提交
2708
				commonpbutil.WithSourceID(paramtable.GetNodeID()),
2709
			),
E
Enwei Jiao 已提交
2710
			ReqID: paramtable.GetNodeID(),
2711
		},
2712 2713 2714 2715
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2716 2717
	}

2718 2719 2720
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

Z
Zach 已提交
2721
	log.Ctx(ctx).Info(
2722
		rpcReceived(method),
2723
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2724 2725 2726 2727 2728
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames),
		zap.Any("dsl", request.Dsl),
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2729 2730 2731 2732
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2733

2734
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2735
		log.Ctx(ctx).Warn(
2736
			rpcFailedToEnqueue(method),
D
dragondriver 已提交
2737
			zap.Error(err),
2738
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2739 2740 2741 2742 2743 2744
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
			zap.Any("OutputFields", request.OutputFields),
2745 2746 2747
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2748

E
Enwei Jiao 已提交
2749
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2750
			metrics.AbandonLabel).Inc()
2751

2752 2753
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2754
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2755 2756 2757 2758
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2759
	tr.CtxRecord(ctx, "search request enqueue")
2760

Z
Zach 已提交
2761
	log.Ctx(ctx).Debug(
2762
		rpcEnqueued(method),
2763
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2764
		zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2765 2766 2767 2768 2769
		zap.Uint64("timestamp", qt.Base.Timestamp),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames),
		zap.Any("dsl", request.Dsl),
2770
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2771 2772 2773 2774
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2775

2776
	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2777
		log.Ctx(ctx).Warn(
2778
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2779
			zap.Error(err),
2780
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2781
			zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2782 2783 2784 2785
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
2786
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2787 2788 2789 2790
			zap.Any("OutputFields", request.OutputFields),
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
2791

E
Enwei Jiao 已提交
2792
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2793
			metrics.FailLabel).Inc()
2794

2795 2796
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2797
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2798 2799 2800 2801 2802
				Reason:    err.Error(),
			},
		}, nil
	}

Z
Zach 已提交
2803
	span := tr.CtxRecord(ctx, "wait search result")
E
Enwei Jiao 已提交
2804
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2805
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
2806
	tr.CtxRecord(ctx, "wait search result")
Z
Zach 已提交
2807
	log.Ctx(ctx).Debug(
2808
		rpcDone(method),
2809
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2810 2811 2812 2813 2814 2815
		zap.Int64("msgID", qt.ID()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames),
		zap.Any("dsl", request.Dsl),
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2816 2817 2818 2819
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2820

E
Enwei Jiao 已提交
2821
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2822
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2823
	metrics.ProxySearchVectors.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(qt.result.GetResults().GetNumQueries()))
C
cai.zhang 已提交
2824
	searchDur := tr.ElapseSpan().Milliseconds()
E
Enwei Jiao 已提交
2825
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2826
		metrics.SearchLabel).Observe(float64(searchDur))
E
Enwei Jiao 已提交
2827
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2828
		metrics.SearchLabel, request.CollectionName).Observe(float64(searchDur))
2829 2830
	if qt.result != nil {
		sentSize := proto.Size(qt.result)
E
Enwei Jiao 已提交
2831
		metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(sentSize))
2832
		rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
2833
	}
2834 2835 2836
	return qt.result, nil
}

2837
// Flush notify data nodes to persist the data of collection.
2838 2839 2840 2841 2842 2843 2844
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2845
	if !node.checkHealthy() {
2846 2847
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2848
	}
D
dragondriver 已提交
2849 2850 2851 2852 2853

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Flush")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

2854
	ft := &flushTask{
T
ThreadDao 已提交
2855 2856 2857
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2858
		dataCoord:    node.dataCoord,
2859 2860
	}

D
dragondriver 已提交
2861
	method := "Flush"
2862
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2863
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2864 2865 2866 2867

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2868
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2869 2870
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2871 2872 2873 2874 2875 2876

	if err := node.sched.ddQueue.Enqueue(ft); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2877
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2878 2879 2880
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

E
Enwei Jiao 已提交
2881
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
2882

2883 2884
		resp.Status.Reason = err.Error()
		return resp, nil
2885 2886
	}

D
dragondriver 已提交
2887 2888 2889
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2890
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2891 2892 2893
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2894 2895
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2896 2897 2898 2899

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2900
			zap.Error(err),
D
dragondriver 已提交
2901
			zap.String("traceID", traceID),
2902
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2903 2904 2905
			zap.Int64("MsgID", ft.ID()),
			zap.Uint64("BeginTs", ft.BeginTs()),
			zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2906 2907 2908
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

E
Enwei Jiao 已提交
2909
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
2910

D
dragondriver 已提交
2911
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2912 2913
		resp.Status.Reason = err.Error()
		return resp, nil
2914 2915
	}

D
dragondriver 已提交
2916 2917 2918
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2919
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2920 2921 2922 2923 2924 2925
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))

E
Enwei Jiao 已提交
2926 2927
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2928
	return ft.result, nil
2929 2930
}

2931
// Query get the records by primary keys.
C
Cai Yudong 已提交
2932
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2933
	receiveSize := proto.Size(request)
E
Enwei Jiao 已提交
2934
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.QueryLabel).Add(float64(receiveSize))
2935 2936 2937

	rateCol.Add(internalpb.RateType_DQLQuery.String(), 1)

2938 2939 2940 2941 2942
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2943

D
dragondriver 已提交
2944 2945
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Query")
	defer sp.Finish()
2946
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2947

2948
	qt := &queryTask{
2949 2950 2951
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
2952 2953
			Base: commonpbutil.NewMsgBase(
				commonpbutil.WithMsgType(commonpb.MsgType_Retrieve),
E
Enwei Jiao 已提交
2954
				commonpbutil.WithSourceID(paramtable.GetNodeID()),
2955
			),
E
Enwei Jiao 已提交
2956
			ReqID: paramtable.GetNodeID(),
2957
		},
2958 2959
		request:          request,
		qc:               node.queryCoord,
2960
		queryShardPolicy: mergeRoundRobinPolicy,
2961
		shardMgr:         node.shardMgr,
2962 2963
	}

D
dragondriver 已提交
2964 2965
	method := "Query"

E
Enwei Jiao 已提交
2966
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2967 2968
		metrics.TotalLabel).Inc()

Z
Zach 已提交
2969
	log.Ctx(ctx).Info(
D
dragondriver 已提交
2970
		rpcReceived(method),
2971
		zap.String("role", typeutil.ProxyRole),
2972 2973
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2974 2975 2976 2977 2978
		zap.Strings("partitions", request.PartitionNames),
		zap.String("expr", request.Expr),
		zap.Strings("OutputFields", request.OutputFields),
		zap.Uint64("travel_timestamp", request.TravelTimestamp),
		zap.Uint64("guarantee_timestamp", request.GuaranteeTimestamp))
G
godchen 已提交
2979

D
dragondriver 已提交
2980
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2981
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
2982 2983 2984
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("role", typeutil.ProxyRole),
2985 2986 2987
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2988

E
Enwei Jiao 已提交
2989
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2990
			metrics.AbandonLabel).Inc()
2991

2992 2993 2994 2995 2996 2997
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
2998
	}
Z
Zach 已提交
2999
	tr.CtxRecord(ctx, "query request enqueue")
3000

Z
Zach 已提交
3001
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
3002
		rpcEnqueued(method),
3003
		zap.String("role", typeutil.ProxyRole),
3004
		zap.Int64("msgID", qt.ID()),
3005 3006
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
3007
		zap.Strings("partitions", request.PartitionNames))
D
dragondriver 已提交
3008 3009

	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
3010
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
3011 3012
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
3013
			zap.String("role", typeutil.ProxyRole),
3014
			zap.Int64("msgID", qt.ID()),
3015 3016 3017
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
3018

E
Enwei Jiao 已提交
3019
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3020
			metrics.FailLabel).Inc()
3021

3022 3023 3024 3025 3026 3027 3028
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
3029
	span := tr.CtxRecord(ctx, "wait query result")
E
Enwei Jiao 已提交
3030
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
3031
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
3032

Z
Zach 已提交
3033
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
3034 3035
		rpcDone(method),
		zap.String("role", typeutil.ProxyRole),
3036
		zap.Int64("msgID", qt.ID()),
3037 3038 3039
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
3040

E
Enwei Jiao 已提交
3041
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3042 3043
		metrics.SuccessLabel).Inc()

E
Enwei Jiao 已提交
3044
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
3045
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
E
Enwei Jiao 已提交
3046
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
3047
		metrics.QueryLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
3048 3049

	ret := &milvuspb.QueryResults{
3050 3051
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
3052 3053
	}
	sentSize := proto.Size(qt.result)
3054
	rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
E
Enwei Jiao 已提交
3055
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(sentSize))
3056
	return ret, nil
3057
}
3058

3059
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
3060 3061 3062 3063
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3064 3065 3066 3067 3068

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreateAlias")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

Y
Yusup 已提交
3069 3070 3071 3072 3073 3074 3075
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
3076
	method := "CreateAlias"
3077
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3078
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

	if err := node.sched.ddQueue.Enqueue(cat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
3098
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
3099

Y
Yusup 已提交
3100 3101 3102 3103 3104 3105
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3106 3107 3108
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3109
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3110 3111 3112 3113
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3114 3115
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3116 3117 3118 3119

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3120
			zap.Error(err),
D
dragondriver 已提交
3121
			zap.String("traceID", traceID),
3122
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3123 3124 3125 3126
			zap.Int64("MsgID", cat.ID()),
			zap.Uint64("BeginTs", cat.BeginTs()),
			zap.Uint64("EndTs", cat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3127 3128
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
E
Enwei Jiao 已提交
3129
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
3130 3131 3132 3133 3134 3135 3136

		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
3148 3149
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3150 3151 3152
	return cat.result, nil
}

3153
// DropAlias alter the alias of collection.
Y
Yusup 已提交
3154 3155 3156 3157
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3158 3159 3160 3161 3162

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropAlias")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

Y
Yusup 已提交
3163 3164 3165 3166 3167 3168 3169
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
3170
	method := "DropAlias"
3171
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3172
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias))

	if err := node.sched.ddQueue.Enqueue(dat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("alias", request.Alias))
E
Enwei Jiao 已提交
3189
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3190

Y
Yusup 已提交
3191 3192 3193 3194 3195 3196
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3197 3198 3199
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3200
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3201 3202 3203 3204
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3205
		zap.String("alias", request.Alias))
D
dragondriver 已提交
3206 3207 3208 3209

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3210
			zap.Error(err),
D
dragondriver 已提交
3211
			zap.String("traceID", traceID),
3212
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3213 3214 3215 3216
			zap.Int64("MsgID", dat.ID()),
			zap.Uint64("BeginTs", dat.BeginTs()),
			zap.Uint64("EndTs", dat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3217 3218
			zap.String("alias", request.Alias))

E
Enwei Jiao 已提交
3219
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3220

Y
Yusup 已提交
3221 3222 3223 3224 3225 3226
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias))

E
Enwei Jiao 已提交
3237 3238
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3239 3240 3241
	return dat.result, nil
}

3242
// AlterAlias alter alias of collection.
Y
Yusup 已提交
3243 3244 3245 3246
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3247 3248 3249 3250 3251

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-AlterAlias")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

Y
Yusup 已提交
3252 3253 3254 3255 3256 3257 3258
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
3259
	method := "AlterAlias"
3260
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3261
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

	if err := node.sched.ddQueue.Enqueue(aat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
E
Enwei Jiao 已提交
3280
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3281

Y
Yusup 已提交
3282 3283 3284 3285 3286 3287
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3288 3289 3290
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3291
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3292 3293 3294 3295
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3296 3297
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3298 3299 3300 3301

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3302
			zap.Error(err),
D
dragondriver 已提交
3303
			zap.String("traceID", traceID),
3304
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3305 3306 3307 3308
			zap.Int64("MsgID", aat.ID()),
			zap.Uint64("BeginTs", aat.BeginTs()),
			zap.Uint64("EndTs", aat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3309 3310 3311
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
3312
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3313

Y
Yusup 已提交
3314 3315 3316 3317 3318 3319
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

E
Enwei Jiao 已提交
3331 3332
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3333 3334 3335
	return aat.result, nil
}

3336
// CalcDistance calculates the distances between vectors.
3337
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
3338 3339 3340 3341 3342
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
3343

3344 3345 3346 3347
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CalcDistance")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

3348 3349
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
3350

3351 3352 3353 3354 3355
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
3356 3357
		}

3358
		qt := &queryTask{
3359 3360 3361
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
3362 3363
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Retrieve),
E
Enwei Jiao 已提交
3364
					commonpbutil.WithSourceID(paramtable.GetNodeID()),
3365
				),
E
Enwei Jiao 已提交
3366
				ReqID: paramtable.GetNodeID(),
3367
			},
3368 3369 3370 3371
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

3372
			queryShardPolicy: mergeRoundRobinPolicy,
3373
			shardMgr:         node.shardMgr,
3374 3375
		}

G
groot 已提交
3376 3377 3378 3379 3380 3381
		items := []zapcore.Field{
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
			zap.Any("OutputFields", queryRequest.OutputFields),
		}

3382
		err := node.sched.dqQueue.Enqueue(qt)
3383
		if err != nil {
G
groot 已提交
3384
			log.Error("CalcDistance queryTask failed to enqueue", append(items, zap.Error(err))...)
3385

3386 3387 3388 3389 3390
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3391
			}, err
3392
		}
3393

G
groot 已提交
3394
		log.Debug("CalcDistance queryTask enqueued", items...)
3395 3396 3397

		err = qt.WaitToFinish()
		if err != nil {
G
groot 已提交
3398
			log.Error("CalcDistance queryTask failed to WaitToFinish", append(items, zap.Error(err))...)
3399 3400 3401 3402 3403 3404

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3405
			}, err
3406
		}
3407

G
groot 已提交
3408
		log.Debug("CalcDistance queryTask Done", items...)
3409 3410

		return &milvuspb.QueryResults{
3411 3412
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
3413 3414 3415
		}, nil
	}

G
groot 已提交
3416 3417 3418 3419
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
		traceID:   traceID,
		queryFunc: query,
3420 3421
	}

G
groot 已提交
3422
	return task.Execute(ctx, request)
3423 3424
}

3425
// GetDdChannel returns the used channel for dd operations.
C
Cai Yudong 已提交
3426
func (node *Proxy) GetDdChannel(ctx context.Context, request *internalpb.GetDdChannelRequest) (*milvuspb.StringResponse, error) {
3427 3428
	panic("implement me")
}
X
XuanYang-cn 已提交
3429

3430
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3431
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
D
dragondriver 已提交
3432
	log.Debug("GetPersistentSegmentInfo",
3433
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3434 3435 3436
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3437
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3438
		Status: &commonpb.Status{
3439
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3440 3441
		},
	}
3442 3443 3444 3445
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3446 3447
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3448
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3449
		metrics.TotalLabel).Inc()
3450 3451 3452

	// list segments
	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
X
XuanYang-cn 已提交
3453
	if err != nil {
E
Enwei Jiao 已提交
3454
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
		resp.Status.Reason = fmt.Errorf("getCollectionID failed, err:%w", err).Error()
		return resp, nil
	}

	getSegmentsByStatesResponse, err := node.dataCoord.GetSegmentsByStates(ctx, &datapb.GetSegmentsByStatesRequest{
		CollectionID: collectionID,
		// -1 means list all partition segemnts
		PartitionID: -1,
		States:      []commonpb.SegmentState{commonpb.SegmentState_Flushing, commonpb.SegmentState_Flushed, commonpb.SegmentState_Sealed},
	})
	if err != nil {
E
Enwei Jiao 已提交
3466
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3467
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3468 3469
		return resp, nil
	}
3470 3471

	// get Segment info
3472
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
3473 3474 3475 3476
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
			commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
3477
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3478
		),
3479
		SegmentIDs: getSegmentsByStatesResponse.Segments,
X
XuanYang-cn 已提交
3480 3481
	})
	if err != nil {
E
Enwei Jiao 已提交
3482
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3483 3484
			metrics.FailLabel).Inc()
		log.Warn("GetPersistentSegmentInfo fail", zap.Error(err))
3485
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3486 3487
		return resp, nil
	}
3488
	log.Debug("GetPersistentSegmentInfo ", zap.Int("len(infos)", len(infoResp.Infos)), zap.Any("status", infoResp.Status))
3489
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3490
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3491
			metrics.FailLabel).Inc()
X
XuanYang-cn 已提交
3492 3493 3494 3495 3496 3497
		resp.Status.Reason = infoResp.Status.Reason
		return resp, nil
	}
	persistentInfos := make([]*milvuspb.PersistentSegmentInfo, len(infoResp.Infos))
	for i, info := range infoResp.Infos {
		persistentInfos[i] = &milvuspb.PersistentSegmentInfo{
S
sunby 已提交
3498
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3499 3500
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3501
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3502 3503 3504
			State:        info.State,
		}
	}
E
Enwei Jiao 已提交
3505
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3506
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
3507
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3508
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3509 3510 3511 3512
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3513
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3514
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
D
dragondriver 已提交
3515
	log.Debug("GetQuerySegmentInfo",
3516
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3517 3518 3519
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3520
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3521
		Status: &commonpb.Status{
3522
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3523 3524
		},
	}
3525 3526 3527 3528
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3529

3530 3531
	method := "GetQuerySegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3532
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3533 3534
		metrics.TotalLabel).Inc()

3535 3536
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
E
Enwei Jiao 已提交
3537
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3538 3539 3540
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3541
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
3542 3543 3544 3545
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
			commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
3546
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3547
		),
3548
		CollectionID: collID,
Z
zhenshan.cao 已提交
3549 3550
	})
	if err != nil {
E
Enwei Jiao 已提交
3551
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3552
		log.Error("Failed to get segment info from QueryCoord", zap.Error(err))
Z
zhenshan.cao 已提交
3553 3554 3555
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3556
	log.Debug("GetQuerySegmentInfo ", zap.Any("infos", infoResp.Infos), zap.Any("status", infoResp.Status))
3557
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3558
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3559
		log.Error("Failed to get segment info from QueryCoord", zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572
		resp.Status.Reason = infoResp.Status.Reason
		return resp, nil
	}
	queryInfos := make([]*milvuspb.QuerySegmentInfo, len(infoResp.Infos))
	for i, info := range infoResp.Infos {
		queryInfos[i] = &milvuspb.QuerySegmentInfo{
			SegmentID:    info.SegmentID,
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
			NumRows:      info.NumRows,
			MemSize:      info.MemSize,
			IndexName:    info.IndexName,
			IndexID:      info.IndexID,
X
xige-16 已提交
3573
			State:        info.SegmentState,
3574
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3575 3576
		}
	}
3577

E
Enwei Jiao 已提交
3578 3579
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3580
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3581 3582 3583 3584
	resp.Infos = queryInfos
	return resp, nil
}

J
jingkl 已提交
3585
// Dummy handles dummy request
C
Cai Yudong 已提交
3586
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
	failedResponse := &milvuspb.DummyResponse{
		Response: `{"status": "fail"}`,
	}

	// TODO(wxyu): change name RequestType to Request
	drt, err := parseDummyRequestType(req.RequestType)
	if err != nil {
		log.Debug("Failed to parse dummy request type")
		return failedResponse, nil
	}

3598 3599
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3600
		if err != nil {
3601
			log.Debug("Failed to parse dummy query request")
3602 3603 3604
			return failedResponse, nil
		}

3605
		request := &milvuspb.QueryRequest{
3606 3607 3608
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3609
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3610 3611
		}

3612
		_, err = node.Query(ctx, request)
3613
		if err != nil {
3614
			log.Debug("Failed to execute dummy query")
3615 3616
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3617 3618 3619 3620 3621 3622

		return &milvuspb.DummyResponse{
			Response: `{"status": "success"}`,
		}, nil
	}

3623 3624
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3625 3626
}

J
jingkl 已提交
3627
// RegisterLink registers a link
C
Cai Yudong 已提交
3628
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
3629
	code := node.stateCode.Load().(commonpb.StateCode)
D
dragondriver 已提交
3630
	log.Debug("RegisterLink",
3631
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3632
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3633

3634
	if code != commonpb.StateCode_Healthy {
3635 3636 3637
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3638
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3639
				Reason:    "proxy not healthy",
3640 3641 3642
			},
		}, nil
	}
E
Enwei Jiao 已提交
3643
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Inc()
3644 3645 3646
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3647
			ErrorCode: commonpb.ErrorCode_Success,
3648
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3649 3650 3651
		},
	}, nil
}
3652

3653
// GetMetrics gets the metrics of proxy
3654 3655 3656
// TODO(dragondriver): cache the Metrics and set a retention to the cache
func (node *Proxy) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	log.Debug("Proxy.GetMetrics",
E
Enwei Jiao 已提交
3657
		zap.Int64("node_id", paramtable.GetNodeID()),
3658 3659 3660 3661
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
E
Enwei Jiao 已提交
3662
			zap.Int64("node_id", paramtable.GetNodeID()),
3663
			zap.String("req", req.Request),
E
Enwei Jiao 已提交
3664
			zap.Error(errProxyIsUnhealthy(paramtable.GetNodeID())))
3665 3666 3667 3668

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
E
Enwei Jiao 已提交
3669
				Reason:    msgProxyIsUnhealthy(paramtable.GetNodeID()),
3670 3671 3672 3673 3674 3675 3676 3677
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
E
Enwei Jiao 已提交
3678
			zap.Int64("node_id", paramtable.GetNodeID()),
3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693
			zap.String("req", req.Request),
			zap.Error(err))

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			Response: "",
		}, nil
	}

	log.Debug("Proxy.GetMetrics",
		zap.String("metric_type", metricType))

3694 3695 3696 3697
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
		commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
3698
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3699
	)
3700
	if metricType == metricsinfo.SystemInfoMetrics {
3701 3702 3703 3704 3705 3706 3707
		ret, err := node.metricsCacheManager.GetSystemInfoMetrics()
		if err == nil && ret != nil {
			return ret, nil
		}
		log.Debug("failed to get system info metrics from cache, recompute instead",
			zap.Error(err))

3708
		metrics, err := getSystemInfoMetrics(ctx, req, node)
3709 3710

		log.Debug("Proxy.GetMetrics",
E
Enwei Jiao 已提交
3711
			zap.Int64("node_id", paramtable.GetNodeID()),
3712 3713 3714 3715 3716
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3717 3718
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3719
		return metrics, nil
3720 3721 3722
	}

	log.Debug("Proxy.GetMetrics failed, request metric type is not implemented yet",
E
Enwei Jiao 已提交
3723
		zap.Int64("node_id", paramtable.GetNodeID()),
3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735
		zap.String("req", req.Request),
		zap.String("metric_type", metricType))

	return &milvuspb.GetMetricsResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    metricsinfo.MsgUnimplementedMetric,
		},
		Response: "",
	}, nil
}

3736 3737 3738 3739 3740
// GetProxyMetrics gets the metrics of proxy, it's an internal interface which is different from GetMetrics interface,
// because it only obtains the metrics of Proxy, not including the topological metrics of Query cluster and Data cluster.
func (node *Proxy) GetProxyMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	if !node.checkHealthy() {
		log.Warn("Proxy.GetProxyMetrics failed",
E
Enwei Jiao 已提交
3741
			zap.Int64("node_id", paramtable.GetNodeID()),
3742
			zap.String("req", req.Request),
E
Enwei Jiao 已提交
3743
			zap.Error(errProxyIsUnhealthy(paramtable.GetNodeID())))
3744 3745 3746 3747

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
E
Enwei Jiao 已提交
3748
				Reason:    msgProxyIsUnhealthy(paramtable.GetNodeID()),
3749 3750 3751 3752 3753 3754 3755
			},
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetProxyMetrics failed to parse metric type",
E
Enwei Jiao 已提交
3756
			zap.Int64("node_id", paramtable.GetNodeID()),
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
			zap.String("req", req.Request),
			zap.Error(err))

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

3768 3769 3770 3771
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
		commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
3772
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3773
	)
3774 3775 3776 3777 3778

	if metricType == metricsinfo.SystemInfoMetrics {
		proxyMetrics, err := getProxyMetrics(ctx, req, node)
		if err != nil {
			log.Warn("Proxy.GetProxyMetrics failed to getProxyMetrics",
E
Enwei Jiao 已提交
3779
				zap.Int64("node_id", paramtable.GetNodeID()),
3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
				zap.String("req", req.Request),
				zap.Error(err))

			return &milvuspb.GetMetricsResponse{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
			}, nil
		}

		log.Debug("Proxy.GetProxyMetrics",
E
Enwei Jiao 已提交
3792
			zap.Int64("node_id", paramtable.GetNodeID()),
3793
			zap.String("req", req.Request),
3794
			zap.String("metric_type", metricType))
3795 3796 3797 3798 3799

		return proxyMetrics, nil
	}

	log.Debug("Proxy.GetProxyMetrics failed, request metric type is not implemented yet",
E
Enwei Jiao 已提交
3800
		zap.Int64("node_id", paramtable.GetNodeID()),
3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
		zap.String("req", req.Request),
		zap.String("metric_type", metricType))

	return &milvuspb.GetMetricsResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    metricsinfo.MsgUnimplementedMetric,
		},
	}, nil
}

B
bigsheeper 已提交
3812 3813 3814
// LoadBalance would do a load balancing operation between query nodes
func (node *Proxy) LoadBalance(ctx context.Context, req *milvuspb.LoadBalanceRequest) (*commonpb.Status, error) {
	log.Debug("Proxy.LoadBalance",
E
Enwei Jiao 已提交
3815
		zap.Int64("proxy_id", paramtable.GetNodeID()),
B
bigsheeper 已提交
3816 3817 3818 3819 3820 3821 3822 3823 3824
		zap.Any("req", req))

	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3825 3826 3827 3828 3829 3830 3831

	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	if err != nil {
		log.Error("failed to get collection id", zap.String("collection name", req.GetCollectionName()), zap.Error(err))
		status.Reason = err.Error()
		return status, nil
	}
B
bigsheeper 已提交
3832
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
3833 3834 3835 3836
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_LoadBalanceSegments),
			commonpbutil.WithMsgID(0),
			commonpbutil.WithTimeStamp(0),
E
Enwei Jiao 已提交
3837
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3838
		),
B
bigsheeper 已提交
3839 3840
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3841
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3842
		SealedSegmentIDs: req.SealedSegmentIDs,
3843
		CollectionID:     collectionID,
B
bigsheeper 已提交
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
	})
	if err != nil {
		log.Error("Failed to LoadBalance from Query Coordinator",
			zap.Any("req", req), zap.Error(err))
		status.Reason = err.Error()
		return status, nil
	}
	if infoResp.ErrorCode != commonpb.ErrorCode_Success {
		log.Error("Failed to LoadBalance from Query Coordinator", zap.String("errMsg", infoResp.Reason))
		status.Reason = infoResp.Reason
		return status, nil
	}
	log.Debug("LoadBalance Done", zap.Any("req", req), zap.Any("status", infoResp))
	status.ErrorCode = commonpb.ErrorCode_Success
	return status, nil
}

3861 3862 3863 3864 3865 3866 3867 3868 3869
// GetReplicas gets replica info
func (node *Proxy) GetReplicas(ctx context.Context, req *milvuspb.GetReplicasRequest) (*milvuspb.GetReplicasResponse, error) {
	log.Info("received get replicas request")
	resp := &milvuspb.GetReplicasResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

S
smellthemoon 已提交
3870 3871
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_GetReplicas),
E
Enwei Jiao 已提交
3872
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
S
smellthemoon 已提交
3873
	)
3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885

	resp, err := node.queryCoord.GetReplicas(ctx, req)
	if err != nil {
		log.Error("Failed to get replicas from Query Coordinator", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
	log.Info("received get replicas response", zap.Any("resp", resp), zap.Error(err))
	return resp, nil
}

3886
// GetCompactionState gets the compaction state of multiple segments
3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899
func (node *Proxy) GetCompactionState(ctx context.Context, req *milvuspb.GetCompactionStateRequest) (*milvuspb.GetCompactionStateResponse, error) {
	log.Info("received GetCompactionState request", zap.Int64("compactionID", req.GetCompactionID()))
	resp := &milvuspb.GetCompactionStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionState(ctx, req)
	log.Info("received GetCompactionState response", zap.Int64("compactionID", req.GetCompactionID()), zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

3900
// ManualCompaction invokes compaction on specified collection
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
func (node *Proxy) ManualCompaction(ctx context.Context, req *milvuspb.ManualCompactionRequest) (*milvuspb.ManualCompactionResponse, error) {
	log.Info("received ManualCompaction request", zap.Int64("collectionID", req.GetCollectionID()))
	resp := &milvuspb.ManualCompactionResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.ManualCompaction(ctx, req)
	log.Info("received ManualCompaction response", zap.Int64("collectionID", req.GetCollectionID()), zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

3914
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927
func (node *Proxy) GetCompactionStateWithPlans(ctx context.Context, req *milvuspb.GetCompactionPlansRequest) (*milvuspb.GetCompactionPlansResponse, error) {
	log.Info("received GetCompactionStateWithPlans request", zap.Int64("compactionID", req.GetCompactionID()))
	resp := &milvuspb.GetCompactionPlansResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionStateWithPlans(ctx, req)
	log.Info("received GetCompactionStateWithPlans response", zap.Int64("compactionID", req.GetCompactionID()), zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

B
Bingyi Sun 已提交
3928 3929 3930
// GetFlushState gets the flush state of multiple segments
func (node *Proxy) GetFlushState(ctx context.Context, req *milvuspb.GetFlushStateRequest) (*milvuspb.GetFlushStateResponse, error) {
	log.Info("received get flush state request", zap.Any("request", req))
3931
	var err error
B
Bingyi Sun 已提交
3932 3933 3934 3935 3936 3937 3938
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Info("unable to get flush state because of closed server")
		return resp, nil
	}

3939
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3940 3941 3942 3943
	if err != nil {
		log.Info("failed to get flush state response", zap.Error(err))
		return nil, err
	}
B
Bingyi Sun 已提交
3944 3945 3946 3947
	log.Info("received get flush state response", zap.Any("response", resp))
	return resp, err
}

C
Cai Yudong 已提交
3948 3949
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3950 3951
	code := node.stateCode.Load().(commonpb.StateCode)
	return code == commonpb.StateCode_Healthy
3952 3953
}

3954 3955 3956
func (node *Proxy) checkHealthyAndReturnCode() (commonpb.StateCode, bool) {
	code := node.stateCode.Load().(commonpb.StateCode)
	return code, code == commonpb.StateCode_Healthy
3957 3958
}

3959
// unhealthyStatus returns the proxy not healthy status
3960 3961 3962
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3963
		Reason:    "proxy not healthy",
3964 3965
	}
}
G
groot 已提交
3966 3967 3968

// Import data files(json, numpy, etc.) on MinIO/S3 storage, read and parse them into sealed segments
func (node *Proxy) Import(ctx context.Context, req *milvuspb.ImportRequest) (*milvuspb.ImportResponse, error) {
3969 3970
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
G
groot 已提交
3971 3972
		zap.String("partition name", req.GetPartitionName()),
		zap.Strings("files", req.GetFiles()))
3973 3974 3975 3976 3977 3978
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3979 3980 3981 3982
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3983

3984 3985 3986 3987 3988 3989 3990 3991
	err := importutil.ValidateOptions(req.GetOptions())
	if err != nil {
		log.Error("failed to execute import request", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = "request options is not illegal    \n" + err.Error() + "    \nIllegal option format    \n" + importutil.OptionFormat
		return resp, nil
	}

3992 3993
	method := "Import"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3994
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3995 3996
		metrics.TotalLabel).Inc()

3997
	// Call rootCoord to finish import.
3998 3999
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
E
Enwei Jiao 已提交
4000
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
G
groot 已提交
4001
		log.Error("failed to execute bulk insert request", zap.Error(err))
4002 4003 4004 4005
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
4006

E
Enwei Jiao 已提交
4007 4008
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
4009
	return respFromRC, nil
G
groot 已提交
4010 4011
}

4012
// GetImportState checks import task state from RootCoord.
G
groot 已提交
4013 4014 4015 4016 4017 4018 4019
func (node *Proxy) GetImportState(ctx context.Context, req *milvuspb.GetImportStateRequest) (*milvuspb.GetImportStateResponse, error) {
	log.Info("received get import state request", zap.Int64("taskID", req.GetTask()))
	resp := &milvuspb.GetImportStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
4020 4021
	method := "GetImportState"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
4022
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
4023
		metrics.TotalLabel).Inc()
G
groot 已提交
4024 4025

	resp, err := node.rootCoord.GetImportState(ctx, req)
4026
	if err != nil {
E
Enwei Jiao 已提交
4027
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
4028 4029 4030 4031 4032 4033 4034
		log.Error("failed to execute get import state", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}

	log.Info("successfully received get import state response", zap.Int64("taskID", req.GetTask()), zap.Any("resp", resp), zap.Error(err))
E
Enwei Jiao 已提交
4035 4036
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
4037
	return resp, nil
G
groot 已提交
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047
}

// ListImportTasks get id array of all import tasks from rootcoord
func (node *Proxy) ListImportTasks(ctx context.Context, req *milvuspb.ListImportTasksRequest) (*milvuspb.ListImportTasksResponse, error) {
	log.Info("received list import tasks request")
	resp := &milvuspb.ListImportTasksResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
4048 4049
	method := "ListImportTasks"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
4050
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
4051
		metrics.TotalLabel).Inc()
G
groot 已提交
4052
	resp, err := node.rootCoord.ListImportTasks(ctx, req)
4053
	if err != nil {
E
Enwei Jiao 已提交
4054
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
4055 4056 4057
		log.Error("failed to execute list import tasks", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
X
XuanYang-cn 已提交
4058 4059 4060
		return resp, nil
	}

4061
	log.Info("successfully received list import tasks response", zap.String("collection", req.CollectionName), zap.Any("tasks", resp.Tasks))
E
Enwei Jiao 已提交
4062 4063
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
X
XuanYang-cn 已提交
4064 4065 4066
	return resp, err
}

4067 4068 4069 4070 4071 4072
// InvalidateCredentialCache invalidate the credential cache of specified username.
func (node *Proxy) InvalidateCredentialCache(ctx context.Context, request *proxypb.InvalidateCredCacheRequest) (*commonpb.Status, error) {
	ctx = logutil.WithModule(ctx, moduleName)
	logutil.Logger(ctx).Debug("received request to invalidate credential cache",
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
4073
	if !node.checkHealthy() {
4074
		return unhealthyStatus(), nil
4075
	}
4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096

	username := request.Username
	if globalMetaCache != nil {
		globalMetaCache.RemoveCredential(username) // no need to return error, though credential may be not cached
	}
	logutil.Logger(ctx).Debug("complete to invalidate credential cache",
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
		Reason:    "",
	}, nil
}

// UpdateCredentialCache update the credential cache of specified username.
func (node *Proxy) UpdateCredentialCache(ctx context.Context, request *proxypb.UpdateCredCacheRequest) (*commonpb.Status, error) {
	ctx = logutil.WithModule(ctx, moduleName)
	logutil.Logger(ctx).Debug("received request to update credential cache",
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
4097
	if !node.checkHealthy() {
4098
		return unhealthyStatus(), nil
4099
	}
4100 4101

	credInfo := &internalpb.CredentialInfo{
4102 4103
		Username:       request.Username,
		Sha256Password: request.Password,
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118
	}
	if globalMetaCache != nil {
		globalMetaCache.UpdateCredential(credInfo) // no need to return error, though credential may be not cached
	}
	logutil.Logger(ctx).Debug("complete to update credential cache",
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
		Reason:    "",
	}, nil
}

func (node *Proxy) CreateCredential(ctx context.Context, req *milvuspb.CreateCredentialRequest) (*commonpb.Status, error) {
4119 4120
	log.Debug("CreateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4121
		return unhealthyStatus(), nil
4122
	}
4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153
	// validate params
	username := req.Username
	if err := ValidateUsername(username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
	rawPassword, err := crypto.Base64Decode(req.Password)
	if err != nil {
		log.Error("decode password fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "decode password fail key:" + req.Username,
		}, nil
	}
	if err = ValidatePassword(rawPassword); err != nil {
		log.Error("illegal password", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
	encryptedPassword, err := crypto.PasswordEncrypt(rawPassword)
	if err != nil {
		log.Error("encrypt password fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "encrypt password fail key:" + req.Username,
		}, nil
	}
4154

4155 4156 4157
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
4158
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170
	}
	result, err := node.rootCoord.CreateCredential(ctx, credInfo)
	if err != nil { // for error like conntext timeout etc.
		log.Error("create credential fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}
	return result, err
}

C
codeman 已提交
4171
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
4172 4173
	log.Debug("UpdateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4174
		return unhealthyStatus(), nil
4175
	}
C
codeman 已提交
4176 4177 4178 4179 4180 4181 4182 4183 4184
	rawOldPassword, err := crypto.Base64Decode(req.OldPassword)
	if err != nil {
		log.Error("decode old password fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode old password fail when updating:" + req.Username,
		}, nil
	}
	rawNewPassword, err := crypto.Base64Decode(req.NewPassword)
4185 4186 4187 4188 4189 4190 4191
	if err != nil {
		log.Error("decode password fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
4192 4193
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
4194 4195 4196 4197 4198 4199
		log.Error("illegal password", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
4200 4201

	if !passwordVerify(ctx, req.Username, rawOldPassword, globalMetaCache) {
C
codeman 已提交
4202 4203 4204 4205 4206 4207 4208
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
4209 4210 4211 4212 4213 4214 4215
	if err != nil {
		log.Error("encrypt password fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "encrypt password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
4216
	updateCredReq := &internalpb.CredentialInfo{
4217
		Username:          req.Username,
4218
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
4219 4220
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
4221
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232
	if err != nil { // for error like conntext timeout etc.
		log.Error("update credential fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}
	return result, err
}

func (node *Proxy) DeleteCredential(ctx context.Context, req *milvuspb.DeleteCredentialRequest) (*commonpb.Status, error) {
4233 4234
	log.Debug("DeleteCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4235
		return unhealthyStatus(), nil
4236 4237
	}

4238 4239 4240 4241 4242 4243
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255
	result, err := node.rootCoord.DeleteCredential(ctx, req)
	if err != nil { // for error like conntext timeout etc.
		log.Error("delete credential fail", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}
	return result, err
}

func (node *Proxy) ListCredUsers(ctx context.Context, req *milvuspb.ListCredUsersRequest) (*milvuspb.ListCredUsersResponse, error) {
4256 4257
	log.Debug("ListCredUsers", zap.String("role", typeutil.ProxyRole))
	if !node.checkHealthy() {
4258
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
4259
	}
4260
	rootCoordReq := &milvuspb.ListCredUsersRequest{
4261 4262 4263
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_ListCredUsernames),
		),
4264 4265
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277
	if err != nil {
		return &milvuspb.ListCredUsersResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
	return &milvuspb.ListCredUsersResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
4278
		Usernames: resp.Usernames,
4279 4280
	}, nil
}
4281

4282 4283 4284
func (node *Proxy) CreateRole(ctx context.Context, req *milvuspb.CreateRoleRequest) (*commonpb.Status, error) {
	logger.Debug("CreateRole", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4285
		return errorutil.UnhealthyStatus(code), nil
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295
	}

	var roleName string
	if req.Entity != nil {
		roleName = req.Entity.Name
	}
	if err := ValidateRoleName(roleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4296
		}, nil
4297 4298 4299 4300 4301 4302 4303 4304
	}

	result, err := node.rootCoord.CreateRole(ctx, req)
	if err != nil {
		logger.Error("fail to create role", zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4305
		}, nil
4306 4307
	}
	return result, nil
4308 4309
}

4310 4311 4312
func (node *Proxy) DropRole(ctx context.Context, req *milvuspb.DropRoleRequest) (*commonpb.Status, error) {
	logger.Debug("DropRole", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4313
		return errorutil.UnhealthyStatus(code), nil
4314 4315 4316 4317 4318
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4319
		}, nil
4320
	}
4321 4322 4323 4324 4325
	if IsDefaultRole(req.RoleName) {
		errMsg := fmt.Sprintf("the role[%s] is a default role, which can't be droped", req.RoleName)
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    errMsg,
4326
		}, nil
4327
	}
4328 4329 4330 4331 4332 4333
	result, err := node.rootCoord.DropRole(ctx, req)
	if err != nil {
		logger.Error("fail to drop role", zap.String("role_name", req.RoleName), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4334
		}, nil
4335 4336
	}
	return result, nil
4337 4338
}

4339 4340 4341
func (node *Proxy) OperateUserRole(ctx context.Context, req *milvuspb.OperateUserRoleRequest) (*commonpb.Status, error) {
	logger.Debug("OperateUserRole", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4342
		return errorutil.UnhealthyStatus(code), nil
4343 4344 4345 4346 4347
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4348
		}, nil
4349 4350 4351 4352 4353
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4354
		}, nil
4355 4356 4357 4358 4359 4360 4361 4362
	}

	result, err := node.rootCoord.OperateUserRole(ctx, req)
	if err != nil {
		logger.Error("fail to operate user role", zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4363
		}, nil
4364 4365
	}
	return result, nil
4366 4367
}

4368 4369 4370
func (node *Proxy) SelectRole(ctx context.Context, req *milvuspb.SelectRoleRequest) (*milvuspb.SelectRoleResponse, error) {
	logger.Debug("SelectRole", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4371
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4372 4373 4374 4375 4376 4377 4378 4379 4380
	}

	if req.Role != nil {
		if err := ValidateRoleName(req.Role.Name); err != nil {
			return &milvuspb.SelectRoleResponse{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_IllegalArgument,
					Reason:    err.Error(),
				},
4381
			}, nil
4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
		}
	}

	result, err := node.rootCoord.SelectRole(ctx, req)
	if err != nil {
		logger.Error("fail to select role", zap.Error(err))
		return &milvuspb.SelectRoleResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4393
		}, nil
4394 4395
	}
	return result, nil
4396 4397
}

4398 4399 4400
func (node *Proxy) SelectUser(ctx context.Context, req *milvuspb.SelectUserRequest) (*milvuspb.SelectUserResponse, error) {
	logger.Debug("SelectUser", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4401
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4402 4403 4404 4405 4406 4407 4408 4409 4410
	}

	if req.User != nil {
		if err := ValidateUsername(req.User.Name); err != nil {
			return &milvuspb.SelectUserResponse{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_IllegalArgument,
					Reason:    err.Error(),
				},
4411
			}, nil
4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
		}
	}

	result, err := node.rootCoord.SelectUser(ctx, req)
	if err != nil {
		logger.Error("fail to select user", zap.Error(err))
		return &milvuspb.SelectUserResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4423
		}, nil
4424 4425
	}
	return result, nil
4426 4427
}

4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457
func (node *Proxy) validPrivilegeParams(req *milvuspb.OperatePrivilegeRequest) error {
	if req.Entity == nil {
		return fmt.Errorf("the entity in the request is nil")
	}
	if req.Entity.Grantor == nil {
		return fmt.Errorf("the grantor entity in the grant entity is nil")
	}
	if req.Entity.Grantor.Privilege == nil {
		return fmt.Errorf("the privilege entity in the grantor entity is nil")
	}
	if err := ValidatePrivilege(req.Entity.Grantor.Privilege.Name); err != nil {
		return err
	}
	if req.Entity.Object == nil {
		return fmt.Errorf("the resource entity in the grant entity is nil")
	}
	if err := ValidateObjectType(req.Entity.Object.Name); err != nil {
		return err
	}
	if err := ValidateObjectName(req.Entity.ObjectName); err != nil {
		return err
	}
	if req.Entity.Role == nil {
		return fmt.Errorf("the object entity in the grant entity is nil")
	}
	if err := ValidateRoleName(req.Entity.Role.Name); err != nil {
		return err
	}

	return nil
4458 4459
}

4460 4461 4462
func (node *Proxy) OperatePrivilege(ctx context.Context, req *milvuspb.OperatePrivilegeRequest) (*commonpb.Status, error) {
	logger.Debug("OperatePrivilege", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4463
		return errorutil.UnhealthyStatus(code), nil
4464 4465 4466 4467 4468
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4469
		}, nil
4470 4471 4472 4473 4474 4475
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4476
		}, nil
4477 4478 4479 4480 4481 4482 4483 4484
	}
	req.Entity.Grantor.User = &milvuspb.UserEntity{Name: curUser}
	result, err := node.rootCoord.OperatePrivilege(ctx, req)
	if err != nil {
		logger.Error("fail to operate privilege", zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4485
		}, nil
4486 4487
	}
	return result, nil
4488 4489
}

4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
func (node *Proxy) validGrantParams(req *milvuspb.SelectGrantRequest) error {
	if req.Entity == nil {
		return fmt.Errorf("the grant entity in the request is nil")
	}

	if req.Entity.Object != nil {
		if err := ValidateObjectType(req.Entity.Object.Name); err != nil {
			return err
		}

		if err := ValidateObjectName(req.Entity.ObjectName); err != nil {
			return err
		}
	}

	if req.Entity.Role == nil {
		return fmt.Errorf("the role entity in the grant entity is nil")
	}

	if err := ValidateRoleName(req.Entity.Role.Name); err != nil {
		return err
	}

	return nil
}

func (node *Proxy) SelectGrant(ctx context.Context, req *milvuspb.SelectGrantRequest) (*milvuspb.SelectGrantResponse, error) {
	logger.Debug("SelectGrant", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4519
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4520 4521 4522 4523 4524 4525 4526 4527
	}

	if err := node.validGrantParams(req); err != nil {
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_IllegalArgument,
				Reason:    err.Error(),
			},
4528
		}, nil
4529 4530 4531 4532 4533 4534 4535 4536 4537 4538
	}

	result, err := node.rootCoord.SelectGrant(ctx, req)
	if err != nil {
		logger.Error("fail to select grant", zap.Error(err))
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4539
		}, nil
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567
	}
	return result, nil
}

func (node *Proxy) RefreshPolicyInfoCache(ctx context.Context, req *proxypb.RefreshPolicyInfoCacheRequest) (*commonpb.Status, error) {
	logger.Debug("RefreshPrivilegeInfoCache", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
		return errorutil.UnhealthyStatus(code), errorutil.UnhealthyError()
	}

	if globalMetaCache != nil {
		err := globalMetaCache.RefreshPolicyInfo(typeutil.CacheOp{
			OpType: typeutil.CacheOpType(req.OpType),
			OpKey:  req.OpKey,
		})
		if err != nil {
			log.Error("fail to refresh policy info", zap.Error(err))
			return &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_RefreshPolicyInfoCacheFailure,
				Reason:    err.Error(),
			}, err
		}
	}
	logger.Debug("RefreshPrivilegeInfoCache success")

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
	}, nil
4568
}
4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588

// SetRates limits the rates of requests.
func (node *Proxy) SetRates(ctx context.Context, request *proxypb.SetRatesRequest) (*commonpb.Status, error) {
	resp := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
	if !node.checkHealthy() {
		resp = unhealthyStatus()
		return resp, nil
	}

	err := node.multiRateLimiter.globalRateLimiter.setRates(request.GetRates())
	// TODO: set multiple rate limiter rates
	if err != nil {
		resp.Reason = err.Error()
		return resp, nil
	}
	resp.ErrorCode = commonpb.ErrorCode_Success
	return resp, nil
}
4589 4590 4591 4592

func (node *Proxy) CheckHealth(ctx context.Context, request *milvuspb.CheckHealthRequest) (*milvuspb.CheckHealthResponse, error) {
	if !node.checkHealthy() {
		reason := errorutil.UnHealthReason("proxy", node.session.ServerID, "proxy is unhealthy")
4593 4594 4595 4596
		return &milvuspb.CheckHealthResponse{
			Status:    unhealthyStatus(),
			IsHealthy: false,
			Reasons:   []string{reason}}, nil
4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607
	}

	group, ctx := errgroup.WithContext(ctx)
	errReasons := make([]string, 0)

	mu := &sync.Mutex{}
	fn := func(role string, resp *milvuspb.CheckHealthResponse, err error) error {
		mu.Lock()
		defer mu.Unlock()

		if err != nil {
4608
			log.Warn("check health fail", zap.String("role", role), zap.Error(err))
4609 4610 4611 4612 4613
			errReasons = append(errReasons, fmt.Sprintf("check health fail for %s", role))
			return err
		}

		if !resp.IsHealthy {
4614
			log.Warn("check health fail", zap.String("role", role))
4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
			errReasons = append(errReasons, resp.Reasons...)
		}
		return nil
	}

	group.Go(func() error {
		resp, err := node.rootCoord.CheckHealth(ctx, request)
		return fn("rootcoord", resp, err)
	})

	group.Go(func() error {
		resp, err := node.queryCoord.CheckHealth(ctx, request)
		return fn("querycoord", resp, err)
	})

	group.Go(func() error {
		resp, err := node.dataCoord.CheckHealth(ctx, request)
		return fn("datacoord", resp, err)
	})

	group.Go(func() error {
		resp, err := node.indexCoord.CheckHealth(ctx, request)
		return fn("indexcoord", resp, err)
	})

	err := group.Wait()
	if err != nil || len(errReasons) != 0 {
		return &milvuspb.CheckHealthResponse{
			IsHealthy: false,
			Reasons:   errReasons,
		}, nil
	}

4648 4649 4650 4651 4652 4653 4654
	return &milvuspb.CheckHealthResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		IsHealthy: true,
	}, nil
4655
}