impl.go 153.5 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 25
	"strconv"

26 27 28
	"github.com/golang/protobuf/proto"
	"github.com/milvus-io/milvus/api/commonpb"
	"github.com/milvus-io/milvus/api/milvuspb"
29
	"github.com/milvus-io/milvus/internal/common"
X
Xiangyu Wang 已提交
30
	"github.com/milvus-io/milvus/internal/log"
31
	"github.com/milvus-io/milvus/internal/metrics"
J
jaime 已提交
32
	"github.com/milvus-io/milvus/internal/mq/msgstream"
X
Xiangyu Wang 已提交
33 34 35 36
	"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"
37
	"github.com/milvus-io/milvus/internal/util"
38
	"github.com/milvus-io/milvus/internal/util/crypto"
39
	"github.com/milvus-io/milvus/internal/util/errorutil"
40 41
	"github.com/milvus-io/milvus/internal/util/logutil"
	"github.com/milvus-io/milvus/internal/util/metricsinfo"
42
	"github.com/milvus-io/milvus/internal/util/timerecord"
43
	"github.com/milvus-io/milvus/internal/util/trace"
X
Xiangyu Wang 已提交
44
	"github.com/milvus-io/milvus/internal/util/typeutil"
45 46
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
47 48
)

49 50
const moduleName = "Proxy"

51
// UpdateStateCode updates the state code of Proxy.
C
Cai Yudong 已提交
52
func (node *Proxy) UpdateStateCode(code internalpb.StateCode) {
53
	node.stateCode.Store(code)
Z
zhenshan.cao 已提交
54 55
}

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

C
cxytz01 已提交
86
// GetStatisticsChannel gets statistics channel of Proxy.
C
Cai Yudong 已提交
87
func (node *Proxy) GetStatisticsChannel(ctx context.Context) (*milvuspb.StringResponse, error) {
G
godchen 已提交
88 89 90 91 92 93 94 95 96
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		Value: "",
	}, nil
}

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

106
	collectionName := request.CollectionName
107
	collectionID := request.CollectionID
N
neza2017 已提交
108
	if globalMetaCache != nil {
109 110 111 112 113 114
		if collectionName != "" {
			globalMetaCache.RemoveCollection(ctx, collectionName) // no need to return error, though collection may be not cached
		}
		if request.CollectionID != UniqueID(0) {
			globalMetaCache.RemoveCollectionsByID(ctx, collectionID)
		}
N
neza2017 已提交
115
	}
116 117 118 119
	if request.GetBase().GetMsgType() == commonpb.MsgType_DropCollection {
		// no need to handle error, since this Proxy may not create dml stream for the collection.
		_ = node.chMgr.removeDMLStream(request.GetCollectionID())
	}
120
	logutil.Logger(ctx).Info("complete to invalidate collection meta cache",
121
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
122
		zap.String("db", request.DbName),
123 124
		zap.String("collection", collectionName),
		zap.Int64("collectionID", collectionID))
D
dragondriver 已提交
125

126
	return &commonpb.Status{
127
		ErrorCode: commonpb.ErrorCode_Success,
128 129
		Reason:    "",
	}, nil
130 131
}

132
// CreateCollection create a collection by the schema.
133
// TODO(dragondriver): add more detailed ut for ConsistencyLevel, should we support multiple consistency level in Proxy?
C
Cai Yudong 已提交
134
func (node *Proxy) CreateCollection(ctx context.Context, request *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
135 136 137
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
138 139 140 141

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

X
Xiaofan 已提交
145
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
146

147
	cct := &createCollectionTask{
S
sunby 已提交
148
		ctx:                     ctx,
149 150
		Condition:               NewTaskCondition(ctx),
		CreateCollectionRequest: request,
151
		rootCoord:               node.rootCoord,
152 153
	}

154 155 156
	// avoid data race
	lenOfSchema := len(request.Schema)

157 158
	log.Debug(
		rpcReceived(method),
159
		zap.String("traceID", traceID),
160
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
161 162
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
163
		zap.Int("len(schema)", lenOfSchema),
164 165
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
166

167 168 169
	if err := node.sched.ddQueue.Enqueue(cct); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
170 171
			zap.Error(err),
			zap.String("traceID", traceID),
172
			zap.String("role", typeutil.ProxyRole),
173 174 175
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Int("len(schema)", lenOfSchema),
176 177
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
178

X
Xiaofan 已提交
179
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
180
		return &commonpb.Status{
181
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
182 183 184 185
			Reason:    err.Error(),
		}, nil
	}

186 187
	log.Debug(
		rpcEnqueued(method),
188
		zap.String("traceID", traceID),
189
		zap.String("role", typeutil.ProxyRole),
190 191 192
		zap.Int64("MsgID", cct.ID()),
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
193 194
		zap.Uint64("timestamp", request.Base.Timestamp),
		zap.String("db", request.DbName),
195 196
		zap.String("collection", request.CollectionName),
		zap.Int("len(schema)", lenOfSchema),
197 198
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
199

200 201 202
	if err := cct.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
203
			zap.Error(err),
204
			zap.String("traceID", traceID),
205
			zap.String("role", typeutil.ProxyRole),
206 207 208
			zap.Int64("MsgID", cct.ID()),
			zap.Uint64("BeginTs", cct.BeginTs()),
			zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
209 210
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
211
			zap.Int("len(schema)", lenOfSchema),
212 213
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
D
dragondriver 已提交
214

X
Xiaofan 已提交
215
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
216
		return &commonpb.Status{
217
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
218 219 220 221
			Reason:    err.Error(),
		}, nil
	}

222 223
	log.Debug(
		rpcDone(method),
224
		zap.String("traceID", traceID),
225
		zap.String("role", typeutil.ProxyRole),
226 227 228 229 230 231
		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),
232 233
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
234

X
Xiaofan 已提交
235 236
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
237 238 239
	return cct.result, nil
}

240
// DropCollection drop a collection.
C
Cai Yudong 已提交
241
func (node *Proxy) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
242 243 244
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
245 246 247 248

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
249 250
	method := "DropCollection"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
251
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
252

253
	dct := &dropCollectionTask{
S
sunby 已提交
254
		ctx:                   ctx,
255 256
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
257
		rootCoord:             node.rootCoord,
258
		chMgr:                 node.chMgr,
S
sunby 已提交
259
		chTicker:              node.chTicker,
260 261
	}

262 263
	log.Debug("DropCollection received",
		zap.String("traceID", traceID),
264
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
265 266
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
267 268 269 270 271

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

X
Xiaofan 已提交
276
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
277
		return &commonpb.Status{
278
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
279 280 281 282
			Reason:    err.Error(),
		}, nil
	}

283 284
	log.Debug("DropCollection enqueued",
		zap.String("traceID", traceID),
285
		zap.String("role", typeutil.ProxyRole),
286 287 288
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
289 290
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
291 292 293

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DropCollection failed to WaitToFinish",
D
dragondriver 已提交
294
			zap.Error(err),
295
			zap.String("traceID", traceID),
296
			zap.String("role", typeutil.ProxyRole),
297 298 299
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTs", dct.BeginTs()),
			zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
300 301 302
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
303
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
304
		return &commonpb.Status{
305
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
306 307 308 309
			Reason:    err.Error(),
		}, nil
	}

310 311
	log.Debug("DropCollection done",
		zap.String("traceID", traceID),
312
		zap.String("role", typeutil.ProxyRole),
313 314 315 316 317 318
		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))

X
Xiaofan 已提交
319 320
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
321 322 323
	return dct.result, nil
}

324
// HasCollection check if the specific collection exists in Milvus.
C
Cai Yudong 已提交
325
func (node *Proxy) HasCollection(ctx context.Context, request *milvuspb.HasCollectionRequest) (*milvuspb.BoolResponse, error) {
326 327 328 329 330
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
331 332 333 334

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
335 336
	method := "HasCollection"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
337
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
338
		metrics.TotalLabel).Inc()
339 340 341

	log.Debug("HasCollection received",
		zap.String("traceID", traceID),
342
		zap.String("role", typeutil.ProxyRole),
343 344 345
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

346
	hct := &hasCollectionTask{
S
sunby 已提交
347
		ctx:                  ctx,
348 349
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
350
		rootCoord:            node.rootCoord,
351 352
	}

353 354 355 356
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
357
			zap.String("role", typeutil.ProxyRole),
358 359 360
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
361
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
362
			metrics.AbandonLabel).Inc()
363 364
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
365
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
366 367 368 369 370
				Reason:    err.Error(),
			},
		}, nil
	}

371 372
	log.Debug("HasCollection enqueued",
		zap.String("traceID", traceID),
373
		zap.String("role", typeutil.ProxyRole),
374 375 376
		zap.Int64("MsgID", hct.ID()),
		zap.Uint64("BeginTS", hct.BeginTs()),
		zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
377 378
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
379 380 381

	if err := hct.WaitToFinish(); err != nil {
		log.Warn("HasCollection failed to WaitToFinish",
D
dragondriver 已提交
382
			zap.Error(err),
383
			zap.String("traceID", traceID),
384
			zap.String("role", typeutil.ProxyRole),
385 386 387
			zap.Int64("MsgID", hct.ID()),
			zap.Uint64("BeginTS", hct.BeginTs()),
			zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
388 389 390
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
391
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
392
			metrics.FailLabel).Inc()
393 394
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
395
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
396 397 398 399 400
				Reason:    err.Error(),
			},
		}, nil
	}

401 402
	log.Debug("HasCollection done",
		zap.String("traceID", traceID),
403
		zap.String("role", typeutil.ProxyRole),
404 405 406 407 408 409
		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))

X
Xiaofan 已提交
410
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
411
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
412
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
413 414 415
	return hct.result, nil
}

416
// LoadCollection load a collection into query nodes.
C
Cai Yudong 已提交
417
func (node *Proxy) LoadCollection(ctx context.Context, request *milvuspb.LoadCollectionRequest) (*commonpb.Status, error) {
418 419 420
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
421 422 423 424

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

428
	lct := &loadCollectionTask{
S
sunby 已提交
429
		ctx:                   ctx,
430 431
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
432
		queryCoord:            node.queryCoord,
433 434
	}

435 436
	log.Debug("LoadCollection received",
		zap.String("traceID", traceID),
437
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
438 439
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
440 441 442 443 444

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

X
Xiaofan 已提交
449
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
450
			metrics.AbandonLabel).Inc()
451
		return &commonpb.Status{
452
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
453 454 455
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
456

457 458
	log.Debug("LoadCollection enqueued",
		zap.String("traceID", traceID),
459
		zap.String("role", typeutil.ProxyRole),
460 461 462
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
463 464
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
465 466 467

	if err := lct.WaitToFinish(); err != nil {
		log.Warn("LoadCollection failed to WaitToFinish",
D
dragondriver 已提交
468
			zap.Error(err),
469
			zap.String("traceID", traceID),
470
			zap.String("role", typeutil.ProxyRole),
471 472 473
			zap.Int64("MsgID", lct.ID()),
			zap.Uint64("BeginTS", lct.BeginTs()),
			zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
474 475 476
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
477
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
478
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
479
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
480
			metrics.FailLabel).Inc()
481
		return &commonpb.Status{
482
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
483 484 485 486
			Reason:    err.Error(),
		}, nil
	}

487 488
	log.Debug("LoadCollection done",
		zap.String("traceID", traceID),
489
		zap.String("role", typeutil.ProxyRole),
490 491 492 493 494 495
		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))

X
Xiaofan 已提交
496
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
497
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
498
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
499
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
500
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
501
	return lct.result, nil
502 503
}

504
// ReleaseCollection remove the loaded collection from query nodes.
C
Cai Yudong 已提交
505
func (node *Proxy) ReleaseCollection(ctx context.Context, request *milvuspb.ReleaseCollectionRequest) (*commonpb.Status, error) {
506 507 508
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
509

510
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleaseCollection")
511 512
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
513 514
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
515

516
	rct := &releaseCollectionTask{
S
sunby 已提交
517
		ctx:                      ctx,
518 519
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
520
		queryCoord:               node.queryCoord,
521
		chMgr:                    node.chMgr,
522 523
	}

524 525
	log.Debug(
		rpcReceived(method),
526
		zap.String("traceID", traceID),
527
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
528 529
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
530 531

	if err := node.sched.ddQueue.Enqueue(rct); err != nil {
532 533
		log.Warn(
			rpcFailedToEnqueue(method),
534 535
			zap.Error(err),
			zap.String("traceID", traceID),
536
			zap.String("role", typeutil.ProxyRole),
537 538 539
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
540
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
541
			metrics.AbandonLabel).Inc()
542
		return &commonpb.Status{
543
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
544 545 546 547
			Reason:    err.Error(),
		}, nil
	}

548 549
	log.Debug(
		rpcEnqueued(method),
550
		zap.String("traceID", traceID),
551
		zap.String("role", typeutil.ProxyRole),
552 553 554
		zap.Int64("MsgID", rct.ID()),
		zap.Uint64("BeginTS", rct.BeginTs()),
		zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
555 556
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
557 558

	if err := rct.WaitToFinish(); err != nil {
559 560
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
561
			zap.Error(err),
562
			zap.String("traceID", traceID),
563
			zap.String("role", typeutil.ProxyRole),
564 565 566
			zap.Int64("MsgID", rct.ID()),
			zap.Uint64("BeginTS", rct.BeginTs()),
			zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
567 568 569
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
570
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
571
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
572
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
573
			metrics.FailLabel).Inc()
574
		return &commonpb.Status{
575
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
576 577 578 579
			Reason:    err.Error(),
		}, nil
	}

580 581
	log.Debug(
		rpcDone(method),
582
		zap.String("traceID", traceID),
583
		zap.String("role", typeutil.ProxyRole),
584 585 586 587 588 589
		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))

X
Xiaofan 已提交
590
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
591
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
592
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
593
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
594
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
595
	return rct.result, nil
596 597
}

598
// DescribeCollection get the meta information of specific collection, such as schema, created timestamp and etc.
C
Cai Yudong 已提交
599
func (node *Proxy) DescribeCollection(ctx context.Context, request *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
600 601 602 603 604
	if !node.checkHealthy() {
		return &milvuspb.DescribeCollectionResponse{
			Status: unhealthyStatus(),
		}, nil
	}
605

606
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeCollection")
607 608
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
609 610
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
611

612
	dct := &describeCollectionTask{
S
sunby 已提交
613
		ctx:                       ctx,
614 615
		Condition:                 NewTaskCondition(ctx),
		DescribeCollectionRequest: request,
616
		rootCoord:                 node.rootCoord,
617 618
	}

619 620
	log.Debug("DescribeCollection received",
		zap.String("traceID", traceID),
621
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
622 623
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
624 625 626 627 628

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

X
Xiaofan 已提交
633
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
634
			metrics.AbandonLabel).Inc()
635 636
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
637
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
638 639 640 641 642
				Reason:    err.Error(),
			},
		}, nil
	}

643 644
	log.Debug("DescribeCollection enqueued",
		zap.String("traceID", traceID),
645
		zap.String("role", typeutil.ProxyRole),
646 647 648
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTS", dct.BeginTs()),
		zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
649 650
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
651 652 653

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DescribeCollection failed to WaitToFinish",
D
dragondriver 已提交
654
			zap.Error(err),
655
			zap.String("traceID", traceID),
656
			zap.String("role", typeutil.ProxyRole),
657 658 659
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTS", dct.BeginTs()),
			zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
660 661 662
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
663
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
664
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
665
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
666
			metrics.FailLabel).Inc()
667

668 669
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
670
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
671 672 673 674 675
				Reason:    err.Error(),
			},
		}, nil
	}

676 677
	log.Debug("DescribeCollection done",
		zap.String("traceID", traceID),
678
		zap.String("role", typeutil.ProxyRole),
679 680 681 682 683 684
		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))

X
Xiaofan 已提交
685
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
686
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
687
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
688
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
689
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
690 691 692
	return dct.result, nil
}

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
// 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
	}

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

	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))

		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			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))

		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.TotalLabel).Inc()
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			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))

	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return g.result, nil
}

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

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

816
	g := &getCollectionStatisticsTask{
G
godchen 已提交
817 818 819
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
820
		dataCoord:                      node.dataCoord,
821 822
	}

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

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

X
Xiaofan 已提交
839
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
840
			metrics.AbandonLabel).Inc()
841

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

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

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

X
Xiaofan 已提交
872
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
873
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
874
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
875
			metrics.FailLabel).Inc()
876

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

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

X
Xiaofan 已提交
895
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
896
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
897
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
898
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
899
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
900
	return g.result, nil
901 902
}

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

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

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

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

X
Xiaofan 已提交
941
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
G
godchen 已提交
942
		return &milvuspb.ShowCollectionsResponse{
943
			Status: &commonpb.Status{
944
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
945 946 947 948 949
				Reason:    err.Error(),
			},
		}, nil
	}

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

959 960
	err = sct.WaitToFinish()
	if err != nil {
961 962
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
963
			zap.String("role", typeutil.ProxyRole),
964 965 966 967 968 969 970
			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),
		)

X
Xiaofan 已提交
971
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
972

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

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

X
Xiaofan 已提交
990 991
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
992 993 994
	return sct.result, nil
}

995
// CreatePartition create a partition in specific collection.
C
Cai Yudong 已提交
996
func (node *Proxy) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
997 998 999
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1000

1001
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreatePartition")
1002 1003
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1004 1005
	method := "CreatePartition"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
1006
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1007

1008
	cpt := &createPartitionTask{
S
sunby 已提交
1009
		ctx:                    ctx,
1010 1011
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
1012
		rootCoord:              node.rootCoord,
1013 1014 1015
		result:                 nil,
	}

1016 1017 1018
	log.Debug(
		rpcReceived("CreatePartition"),
		zap.String("traceID", traceID),
1019
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1020 1021 1022
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1023 1024 1025 1026 1027 1028

	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
			zap.Error(err),
			zap.String("traceID", traceID),
1029
			zap.String("role", typeutil.ProxyRole),
1030 1031 1032 1033
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1034
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1035

1036
		return &commonpb.Status{
1037
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1038 1039 1040
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1041

1042 1043 1044
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.String("traceID", traceID),
1045
		zap.String("role", typeutil.ProxyRole),
1046 1047 1048
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1049 1050 1051
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1052 1053 1054 1055

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
1056
			zap.Error(err),
1057
			zap.String("traceID", traceID),
1058
			zap.String("role", typeutil.ProxyRole),
1059 1060 1061
			zap.Int64("MsgID", cpt.ID()),
			zap.Uint64("BeginTS", cpt.BeginTs()),
			zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1062 1063 1064 1065
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1066
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1067

1068
		return &commonpb.Status{
1069
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1070 1071 1072
			Reason:    err.Error(),
		}, nil
	}
1073 1074 1075 1076

	log.Debug(
		rpcDone("CreatePartition"),
		zap.String("traceID", traceID),
1077
		zap.String("role", typeutil.ProxyRole),
1078 1079 1080 1081 1082 1083 1084
		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))

X
Xiaofan 已提交
1085 1086
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1087 1088 1089
	return cpt.result, nil
}

1090
// DropPartition drop a partition in specific collection.
C
Cai Yudong 已提交
1091
func (node *Proxy) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
1092 1093 1094
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1095

1096
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropPartition")
1097 1098
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1099 1100
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
1101
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1102

1103
	dpt := &dropPartitionTask{
S
sunby 已提交
1104
		ctx:                  ctx,
1105 1106
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
1107
		rootCoord:            node.rootCoord,
1108 1109 1110
		result:               nil,
	}

1111 1112 1113
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1114
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1115 1116 1117
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1118 1119 1120 1121 1122 1123

	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1124
			zap.String("role", typeutil.ProxyRole),
1125 1126 1127 1128
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1129
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1130

1131
		return &commonpb.Status{
1132
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1133 1134 1135
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1136

1137 1138 1139
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1140
		zap.String("role", typeutil.ProxyRole),
1141 1142 1143
		zap.Int64("MsgID", dpt.ID()),
		zap.Uint64("BeginTS", dpt.BeginTs()),
		zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1144 1145 1146
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1147 1148 1149 1150

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1151
			zap.Error(err),
1152
			zap.String("traceID", traceID),
1153
			zap.String("role", typeutil.ProxyRole),
1154 1155 1156
			zap.Int64("MsgID", dpt.ID()),
			zap.Uint64("BeginTS", dpt.BeginTs()),
			zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1157 1158 1159 1160
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1161
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1162

1163
		return &commonpb.Status{
1164
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1165 1166 1167
			Reason:    err.Error(),
		}, nil
	}
1168 1169 1170 1171

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1172
		zap.String("role", typeutil.ProxyRole),
1173 1174 1175 1176 1177 1178 1179
		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))

X
Xiaofan 已提交
1180 1181
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1182 1183 1184
	return dpt.result, nil
}

1185
// HasPartition check if partition exist.
C
Cai Yudong 已提交
1186
func (node *Proxy) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
1187 1188 1189 1190 1191
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
D
dragondriver 已提交
1192

D
dragondriver 已提交
1193
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasPartition")
D
dragondriver 已提交
1194 1195
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1196 1197 1198
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1199
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1200
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1201

1202
	hpt := &hasPartitionTask{
S
sunby 已提交
1203
		ctx:                 ctx,
1204 1205
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1206
		rootCoord:           node.rootCoord,
1207 1208 1209
		result:              nil,
	}

D
dragondriver 已提交
1210 1211 1212
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1213
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1214 1215 1216
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1217 1218 1219 1220 1221 1222

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

X
Xiaofan 已提交
1228
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1229
			metrics.AbandonLabel).Inc()
1230

1231 1232
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1233
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1234 1235 1236 1237 1238
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1239

D
dragondriver 已提交
1240 1241 1242
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1243
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1244 1245 1246
		zap.Int64("MsgID", hpt.ID()),
		zap.Uint64("BeginTS", hpt.BeginTs()),
		zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1247 1248 1249
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1250 1251 1252 1253

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1254
			zap.Error(err),
D
dragondriver 已提交
1255
			zap.String("traceID", traceID),
1256
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1257 1258 1259
			zap.Int64("MsgID", hpt.ID()),
			zap.Uint64("BeginTS", hpt.BeginTs()),
			zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1260 1261 1262 1263
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1264
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1265
			metrics.FailLabel).Inc()
1266

1267 1268
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1269
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1270 1271 1272 1273 1274
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1275 1276 1277 1278

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1279
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1280 1281 1282 1283 1284 1285 1286
		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))

X
Xiaofan 已提交
1287
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1288
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1289
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1290 1291 1292
	return hpt.result, nil
}

1293
// LoadPartitions load specific partitions into query nodes.
C
Cai Yudong 已提交
1294
func (node *Proxy) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
1295 1296 1297
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1298

D
dragondriver 已提交
1299
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadPartitions")
1300 1301
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1302 1303
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
1304

1305
	lpt := &loadPartitionsTask{
G
godchen 已提交
1306 1307 1308
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1309
		queryCoord:            node.queryCoord,
1310 1311
	}

1312 1313 1314
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1315
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1316 1317 1318
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1319 1320 1321 1322 1323 1324

	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1325
			zap.String("role", typeutil.ProxyRole),
1326 1327 1328 1329
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1330
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1331
			metrics.AbandonLabel).Inc()
1332

1333
		return &commonpb.Status{
1334
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1335 1336 1337 1338
			Reason:    err.Error(),
		}, nil
	}

1339 1340 1341
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1342
		zap.String("role", typeutil.ProxyRole),
1343 1344 1345
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1346 1347 1348
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1349 1350 1351 1352

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1353
			zap.Error(err),
1354
			zap.String("traceID", traceID),
1355
			zap.String("role", typeutil.ProxyRole),
1356 1357 1358
			zap.Int64("MsgID", lpt.ID()),
			zap.Uint64("BeginTS", lpt.BeginTs()),
			zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1359 1360 1361 1362
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1363
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1364
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1365
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1366
			metrics.FailLabel).Inc()
1367

1368
		return &commonpb.Status{
1369
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1370 1371 1372 1373
			Reason:    err.Error(),
		}, nil
	}

1374 1375 1376
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1377
		zap.String("role", typeutil.ProxyRole),
1378 1379 1380 1381 1382 1383 1384
		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))

X
Xiaofan 已提交
1385
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1386
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1387
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1388
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1389
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1390
	return lpt.result, nil
1391 1392
}

1393
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1394
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1395 1396 1397
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1398 1399 1400 1401 1402

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

1403
	rpt := &releasePartitionsTask{
G
godchen 已提交
1404 1405 1406
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1407
		queryCoord:               node.queryCoord,
1408 1409
	}

1410
	method := "ReleasePartitions"
1411
	tr := timerecord.NewTimeRecorder(method)
1412 1413 1414 1415

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1416
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1417 1418 1419
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1420 1421 1422 1423 1424 1425

	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1426
			zap.String("role", typeutil.ProxyRole),
1427 1428 1429 1430
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1431
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1432
			metrics.AbandonLabel).Inc()
1433

1434
		return &commonpb.Status{
1435
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1436 1437 1438 1439
			Reason:    err.Error(),
		}, nil
	}

1440 1441 1442
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1443
		zap.String("role", typeutil.ProxyRole),
1444 1445 1446
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1447 1448 1449
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1450 1451 1452 1453

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1454
			zap.Error(err),
1455
			zap.String("traceID", traceID),
1456
			zap.String("role", typeutil.ProxyRole),
1457 1458 1459
			zap.Int64("msgID", rpt.Base.MsgID),
			zap.Uint64("BeginTS", rpt.BeginTs()),
			zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1460 1461 1462 1463
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1464
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1465
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1466
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1467
			metrics.FailLabel).Inc()
1468

1469
		return &commonpb.Status{
1470
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1471 1472 1473 1474
			Reason:    err.Error(),
		}, nil
	}

1475 1476 1477
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1478
		zap.String("role", typeutil.ProxyRole),
1479 1480 1481 1482 1483 1484 1485
		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))

X
Xiaofan 已提交
1486
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1487
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1488
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1489
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1490
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1491
	return rpt.result, nil
1492 1493
}

1494
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1495
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1496 1497 1498 1499 1500
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1501 1502 1503 1504

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

1508
	g := &getPartitionStatisticsTask{
1509 1510 1511
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1512
		dataCoord:                     node.dataCoord,
1513 1514
	}

1515 1516 1517
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1518
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1519 1520 1521
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1522 1523 1524 1525 1526 1527

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1528
			zap.String("role", typeutil.ProxyRole),
1529 1530 1531 1532
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1533
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1534
			metrics.AbandonLabel).Inc()
1535

1536 1537 1538 1539 1540 1541 1542 1543
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1544 1545 1546
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1547
		zap.String("role", typeutil.ProxyRole),
1548 1549 1550
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
1551 1552 1553
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1554 1555 1556 1557

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1558
			zap.Error(err),
1559
			zap.String("traceID", traceID),
1560
			zap.String("role", typeutil.ProxyRole),
1561 1562 1563
			zap.Int64("msgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
1564 1565 1566 1567
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1568
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1569
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1570
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1571
			metrics.FailLabel).Inc()
1572

1573 1574 1575 1576 1577 1578 1579 1580
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1581 1582 1583
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1584
		zap.String("role", typeutil.ProxyRole),
1585 1586 1587 1588 1589 1590 1591
		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))

X
Xiaofan 已提交
1592
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1593
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1594
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1595
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1596
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1597
	return g.result, nil
1598 1599
}

1600
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1601
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1602 1603 1604 1605 1606
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1607 1608 1609 1610 1611

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

1612
	spt := &showPartitionsTask{
G
godchen 已提交
1613 1614 1615
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1616
		rootCoord:             node.rootCoord,
1617
		queryCoord:            node.queryCoord,
G
godchen 已提交
1618
		result:                nil,
1619 1620
	}

1621
	method := "ShowPartitions"
1622 1623
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1624
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1625
		metrics.TotalLabel).Inc()
1626 1627 1628 1629

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1630
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1631
		zap.Any("request", request))
1632 1633 1634 1635 1636 1637

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

X
Xiaofan 已提交
1641
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1642
			metrics.AbandonLabel).Inc()
1643

G
godchen 已提交
1644
		return &milvuspb.ShowPartitionsResponse{
1645
			Status: &commonpb.Status{
1646
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1647 1648 1649 1650 1651
				Reason:    err.Error(),
			},
		}, nil
	}

1652 1653 1654
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1655
		zap.String("role", typeutil.ProxyRole),
1656 1657 1658
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1659 1660
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1661 1662 1663 1664 1665
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1666
			zap.Error(err),
1667
			zap.String("traceID", traceID),
1668
			zap.String("role", typeutil.ProxyRole),
1669 1670 1671 1672 1673 1674
			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 已提交
1675

X
Xiaofan 已提交
1676
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1677
			metrics.FailLabel).Inc()
1678

G
godchen 已提交
1679
		return &milvuspb.ShowPartitionsResponse{
1680
			Status: &commonpb.Status{
1681
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1682 1683 1684 1685
				Reason:    err.Error(),
			},
		}, nil
	}
1686 1687 1688 1689

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1690
		zap.String("role", typeutil.ProxyRole),
1691 1692 1693 1694 1695 1696 1697
		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))

X
Xiaofan 已提交
1698
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1699
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1700
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1701 1702 1703
	return spt.result, nil
}

S
SimFG 已提交
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
func (node *Proxy) getMsgBase() (*commonpb.MsgBase, error) {
	msgID, err := node.idAllocator.AllocOne()
	if err != nil {
		return nil, err
	}
	timestamp, err := node.tsoAllocator.AllocOne()
	if err != nil {
		return nil, err
	}
	return &commonpb.MsgBase{
		MsgID:     msgID,
		Timestamp: timestamp,
		SourceID:  Params.ProxyCfg.GetNodeID(),
	}, nil
}

func (node *Proxy) getCollectionProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest, collectionID int64) (int64, error) {
	resp, err := node.queryCoord.ShowCollections(ctx, &querypb.ShowCollectionsRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowCollections,
			MsgID:     request.Base.MsgID,
			Timestamp: request.Base.Timestamp,
			SourceID:  request.Base.SourceID,
		},
		CollectionIDs: []int64{collectionID},
	})
	if err != nil {
		return 0, err
	}
	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{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowPartitions,
			MsgID:     request.Base.MsgID,
			Timestamp: request.Base.Timestamp,
			SourceID:  request.Base.SourceID,
		},
		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)
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ShowPartitions")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

	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))
		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
	}
	msgBase, err := node.getMsgBase()
	if err != nil {
		return getErrResponse(err), nil
	}
	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))
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1844
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1845
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1846 1847 1848
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1849 1850 1851 1852 1853

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

1854
	cit := &createIndexTask{
Z
zhenshan.cao 已提交
1855 1856 1857 1858 1859
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		req:        request,
		rootCoord:  node.rootCoord,
		indexCoord: node.indexCoord,
1860 1861
	}

D
dragondriver 已提交
1862
	method := "CreateIndex"
1863
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
1864 1865 1866 1867

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1868
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1869 1870 1871 1872
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1873 1874 1875 1876 1877 1878

	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1879
			zap.String("role", typeutil.ProxyRole),
Z
zhenshan.cao 已提交
1880 1881 1882 1883
			zap.String("db", request.GetDbName()),
			zap.String("collection", request.GetCollectionName()),
			zap.String("field", request.GetFieldName()),
			zap.Any("extra_params", request.GetExtraParams()))
D
dragondriver 已提交
1884

X
Xiaofan 已提交
1885
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1886
			metrics.AbandonLabel).Inc()
1887

1888
		return &commonpb.Status{
1889
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1890 1891 1892 1893
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1894 1895 1896
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1897
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1898 1899 1900
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1901 1902 1903 1904
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1905 1906 1907 1908

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1909
			zap.Error(err),
D
dragondriver 已提交
1910
			zap.String("traceID", traceID),
1911
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1912 1913 1914
			zap.Int64("MsgID", cit.ID()),
			zap.Uint64("BeginTs", cit.BeginTs()),
			zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1915 1916 1917 1918 1919
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

X
Xiaofan 已提交
1920
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1921
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1922
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1923
			metrics.FailLabel).Inc()
1924

1925
		return &commonpb.Status{
1926
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1927 1928 1929 1930
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1931 1932 1933
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1934
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1935 1936 1937 1938 1939 1940 1941 1942
		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))

X
Xiaofan 已提交
1943
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1944
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1945
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1946
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1947
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1948 1949 1950
	return cit.result, nil
}

1951
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
1952
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
1953 1954 1955 1956 1957
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1958 1959 1960 1961 1962

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

1963
	dit := &describeIndexTask{
S
sunby 已提交
1964
		ctx:                  ctx,
1965 1966
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
1967
		indexCoord:           node.indexCoord,
1968 1969
	}

1970 1971 1972
	method := "DescribeIndex"
	// avoid data race
	indexName := request.IndexName
1973
	tr := timerecord.NewTimeRecorder(method)
1974 1975 1976 1977

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1978
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1979 1980 1981
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
1982 1983 1984 1985 1986 1987 1988
		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),
1989
			zap.String("role", typeutil.ProxyRole),
1990 1991 1992 1993 1994
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", indexName))

X
Xiaofan 已提交
1995
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1996
			metrics.AbandonLabel).Inc()
1997

1998 1999
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
2000
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2001 2002 2003 2004 2005
				Reason:    err.Error(),
			},
		}, nil
	}

2006 2007 2008
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2009
		zap.String("role", typeutil.ProxyRole),
2010 2011 2012
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2013 2014 2015
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2016 2017 2018 2019 2020
		zap.String("index name", indexName))

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2021
			zap.Error(err),
2022
			zap.String("traceID", traceID),
2023
			zap.String("role", typeutil.ProxyRole),
2024 2025 2026
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2027 2028 2029
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
2030
			zap.String("index name", indexName))
D
dragondriver 已提交
2031

Z
zhenshan.cao 已提交
2032 2033 2034 2035
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
X
Xiaofan 已提交
2036
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2037
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2038
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2039
			metrics.FailLabel).Inc()
2040

2041 2042
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
2043
				ErrorCode: errCode,
2044 2045 2046 2047 2048
				Reason:    err.Error(),
			},
		}, nil
	}

2049 2050 2051
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2052
		zap.String("role", typeutil.ProxyRole),
2053 2054 2055 2056 2057 2058 2059 2060
		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))

X
Xiaofan 已提交
2061
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2062
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2063
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2064
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2065
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2066 2067 2068
	return dit.result, nil
}

2069
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
2070
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
2071 2072 2073
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2074 2075 2076 2077 2078

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

2079
	dit := &dropIndexTask{
S
sunby 已提交
2080
		ctx:              ctx,
B
BossZou 已提交
2081 2082
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
2083
		indexCoord:       node.indexCoord,
B
BossZou 已提交
2084
	}
G
godchen 已提交
2085

D
dragondriver 已提交
2086
	method := "DropIndex"
2087
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
2088 2089 2090 2091

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2092
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2093 2094 2095 2096 2097
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

D
dragondriver 已提交
2098 2099 2100 2101 2102
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2103
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2104 2105 2106 2107
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2108
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2109
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2110

B
BossZou 已提交
2111
		return &commonpb.Status{
2112
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2113 2114 2115
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2116

D
dragondriver 已提交
2117 2118 2119
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2120
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2121 2122 2123
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2124 2125 2126 2127
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
D
dragondriver 已提交
2128 2129 2130 2131

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2132
			zap.Error(err),
D
dragondriver 已提交
2133
			zap.String("traceID", traceID),
2134
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2135 2136 2137
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2138 2139 2140 2141 2142
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2143
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2144
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2145
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2146
			metrics.FailLabel).Inc()
2147

B
BossZou 已提交
2148
		return &commonpb.Status{
2149
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2150 2151 2152
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2153 2154 2155 2156

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2157
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2158 2159 2160 2161 2162 2163 2164 2165
		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))

X
Xiaofan 已提交
2166
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2167
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2168
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2169
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2170
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
2171 2172 2173
	return dit.result, nil
}

2174 2175
// 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.
2176
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2177
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
2178 2179 2180 2181 2182
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2183 2184 2185 2186 2187

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

2188
	gibpt := &getIndexBuildProgressTask{
2189 2190 2191
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
2192 2193
		indexCoord:                   node.indexCoord,
		rootCoord:                    node.rootCoord,
2194
		dataCoord:                    node.dataCoord,
2195 2196
	}

2197
	method := "GetIndexBuildProgress"
2198
	tr := timerecord.NewTimeRecorder(method)
2199 2200 2201 2202

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2203
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2204 2205 2206 2207
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2208 2209 2210 2211 2212 2213

	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2214
			zap.String("role", typeutil.ProxyRole),
2215 2216 2217 2218
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2219
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2220
			metrics.AbandonLabel).Inc()
2221

2222 2223 2224 2225 2226 2227 2228 2229
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2230 2231 2232
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2233
		zap.String("role", typeutil.ProxyRole),
2234 2235 2236
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
2237 2238 2239 2240
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2241 2242 2243 2244

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
2245
			zap.Error(err),
2246
			zap.String("traceID", traceID),
2247
			zap.String("role", typeutil.ProxyRole),
2248 2249 2250
			zap.Int64("MsgID", gibpt.ID()),
			zap.Uint64("BeginTs", gibpt.BeginTs()),
			zap.Uint64("EndTs", gibpt.EndTs()),
2251 2252 2253 2254
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2255
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2256
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2257
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2258
			metrics.FailLabel).Inc()
2259 2260 2261 2262 2263 2264 2265 2266

		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2267 2268 2269 2270

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2271
		zap.String("role", typeutil.ProxyRole),
2272 2273 2274 2275 2276 2277 2278 2279
		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))
2280

X
Xiaofan 已提交
2281
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2282
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2283
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2284
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2285
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2286
	return gibpt.result, nil
2287 2288
}

2289
// GetIndexState get the build-state of index.
2290
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2291
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
2292 2293 2294 2295 2296
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2297 2298 2299 2300 2301

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

2302
	dipt := &getIndexStateTask{
G
godchen 已提交
2303 2304 2305
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
2306 2307
		indexCoord:           node.indexCoord,
		rootCoord:            node.rootCoord,
2308 2309
	}

2310
	method := "GetIndexState"
2311
	tr := timerecord.NewTimeRecorder(method)
2312 2313 2314 2315

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2316
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2317 2318 2319 2320
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2321 2322 2323 2324 2325 2326

	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2327
			zap.String("role", typeutil.ProxyRole),
2328 2329 2330 2331 2332
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2333
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2334
			metrics.AbandonLabel).Inc()
2335

G
godchen 已提交
2336
		return &milvuspb.GetIndexStateResponse{
2337
			Status: &commonpb.Status{
2338
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2339 2340 2341 2342 2343
				Reason:    err.Error(),
			},
		}, nil
	}

2344 2345 2346
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2347
		zap.String("role", typeutil.ProxyRole),
2348 2349 2350
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2351 2352 2353 2354
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2355 2356 2357 2358

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2359
			zap.Error(err),
2360
			zap.String("traceID", traceID),
2361
			zap.String("role", typeutil.ProxyRole),
2362 2363 2364
			zap.Int64("MsgID", dipt.ID()),
			zap.Uint64("BeginTs", dipt.BeginTs()),
			zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2365 2366 2367 2368 2369
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2370
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2371
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2372
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2373
			metrics.FailLabel).Inc()
2374

G
godchen 已提交
2375
		return &milvuspb.GetIndexStateResponse{
2376
			Status: &commonpb.Status{
2377
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2378 2379 2380 2381 2382
				Reason:    err.Error(),
			},
		}, nil
	}

2383 2384 2385
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2386
		zap.String("role", typeutil.ProxyRole),
2387 2388 2389 2390 2391 2392 2393 2394
		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))

X
Xiaofan 已提交
2395
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2396
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2397
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2398
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2399
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2400 2401 2402
	return dipt.result, nil
}

2403
// Insert insert records into collection.
C
Cai Yudong 已提交
2404
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
X
Xiangyu Wang 已提交
2405 2406 2407 2408 2409 2410
	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))

2411 2412 2413 2414 2415
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2416 2417
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
2418
	receiveSize := proto.Size(request)
2419 2420
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Add(float64(receiveSize))
D
dragondriver 已提交
2421

2422 2423 2424 2425 2426
	defer func() {
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.TotalLabel).Inc()
	}()

2427
	it := &insertTask{
2428 2429
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2430
		// req:       request,
2431 2432 2433 2434
		BaseInsertTask: BaseInsertTask{
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2435
			InsertRequest: internalpb.InsertRequest{
2436
				Base: &commonpb.MsgBase{
X
xige-16 已提交
2437 2438
					MsgType:  commonpb.MsgType_Insert,
					MsgID:    0,
X
Xiaofan 已提交
2439
					SourceID: Params.ProxyCfg.GetNodeID(),
2440 2441 2442
				},
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2443 2444 2445
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
				Version:        internalpb.InsertDataVersion_ColumnBased,
2446
				// RowData: transfer column based request to this
2447 2448
			},
		},
2449 2450 2451 2452
		idAllocator:   node.idAllocator,
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2453
	}
2454 2455

	if len(it.PartitionName) <= 0 {
2456
		it.PartitionName = Params.CommonCfg.DefaultPartitionName
2457 2458
	}

X
Xiangyu Wang 已提交
2459
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2460
		numRows := request.NumRows
2461 2462 2463 2464
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2465

X
Xiangyu Wang 已提交
2466 2467 2468 2469 2470 2471 2472
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2473 2474
	}

X
Xiangyu Wang 已提交
2475
	log.Debug("Enqueue insert request in Proxy",
2476
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2477 2478 2479 2480 2481
		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)),
2482 2483
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))
D
dragondriver 已提交
2484

X
Xiangyu Wang 已提交
2485 2486
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Debug("Failed to enqueue insert task: " + err.Error())
2487 2488
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2489
		return constructFailedResponse(err), nil
2490
	}
D
dragondriver 已提交
2491

X
Xiangyu Wang 已提交
2492
	log.Debug("Detail of insert request in Proxy",
2493
		zap.String("role", typeutil.ProxyRole),
X
Xiangyu Wang 已提交
2494
		zap.Int64("msgID", it.Base.MsgID),
D
dragondriver 已提交
2495 2496 2497 2498 2499
		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 已提交
2500 2501 2502 2503 2504
		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))
2505
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2506
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2507 2508 2509 2510 2511
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2512
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
			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 已提交
2524
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2525

2526
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2527
		metrics.SuccessLabel).Inc()
2528 2529
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(successCnt))
2530
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2531 2532 2533
	return it.result, nil
}

2534
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2535
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
2536 2537 2538
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Delete")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2539 2540
	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))
2541

2542
	receiveSize := proto.Size(request)
2543 2544
	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Add(float64(receiveSize))
2545

G
groot 已提交
2546 2547 2548 2549 2550 2551
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2552 2553 2554
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

2555 2556
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2557
	dt := &deleteTask{
X
xige-16 已提交
2558 2559 2560
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
G
godchen 已提交
2561
		BaseDeleteTask: BaseDeleteTask{
G
godchen 已提交
2562 2563 2564
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2565 2566 2567 2568 2569
			DeleteRequest: internalpb.DeleteRequest{
				Base: &commonpb.MsgBase{
					MsgType: commonpb.MsgType_Delete,
					MsgID:   0,
				},
X
xige-16 已提交
2570
				DbName:         request.DbName,
G
godchen 已提交
2571 2572 2573
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2574 2575 2576 2577
			},
		},
		chMgr:    node.chMgr,
		chTicker: node.chTicker,
G
groot 已提交
2578 2579
	}

2580
	log.Debug("Enqueue delete request in Proxy",
2581
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2582 2583 2584 2585
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2586 2587 2588 2589

	// 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))
X
Xiaofan 已提交
2590
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2591
			metrics.FailLabel).Inc()
2592

G
groot 已提交
2593 2594 2595 2596 2597 2598 2599 2600
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2601
	log.Debug("Detail of delete request in Proxy",
2602
		zap.String("role", typeutil.ProxyRole),
G
groot 已提交
2603 2604 2605 2606 2607
		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),
2608 2609
		zap.String("expr", request.Expr),
		zap.String("traceID", traceID))
G
groot 已提交
2610

2611 2612
	if err := dt.WaitToFinish(); err != nil {
		log.Error("Failed to execute delete task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
X
Xiaofan 已提交
2613
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2614
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2615
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2616
			metrics.FailLabel).Inc()
G
groot 已提交
2617 2618 2619 2620 2621 2622 2623 2624
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

X
Xiaofan 已提交
2625
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2626
		metrics.SuccessLabel).Inc()
2627
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2628 2629 2630
	return dt.result, nil
}

2631
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2632
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2633 2634 2635 2636 2637
	receiveSize := proto.Size(request)
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.SearchLabel).Add(float64(receiveSize))

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

2638 2639 2640 2641 2642
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2643 2644
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
2645 2646
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2647

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

2651
	qt := &searchTask{
S
sunby 已提交
2652
		ctx:       ctx,
2653
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2654
		SearchRequest: &internalpb.SearchRequest{
2655
			Base: &commonpb.MsgBase{
2656
				MsgType:  commonpb.MsgType_Search,
X
Xiaofan 已提交
2657
				SourceID: Params.ProxyCfg.GetNodeID(),
2658
			},
2659
			ReqID: Params.ProxyCfg.GetNodeID(),
2660
		},
2661 2662 2663 2664
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2665 2666
	}

2667 2668 2669
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

Z
Zach 已提交
2670
	log.Ctx(ctx).Info(
2671
		rpcReceived(method),
2672
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2673 2674 2675 2676 2677
		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)),
2678 2679 2680 2681
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2682

2683
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2684
		log.Ctx(ctx).Warn(
2685
			rpcFailedToEnqueue(method),
D
dragondriver 已提交
2686
			zap.Error(err),
2687
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2688 2689 2690 2691 2692 2693
			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),
2694 2695 2696
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2697

2698 2699
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
2700

2701 2702
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2703
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2704 2705 2706 2707
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2708
	tr.CtxRecord(ctx, "search request enqueue")
2709

Z
Zach 已提交
2710
	log.Ctx(ctx).Debug(
2711
		rpcEnqueued(method),
2712
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2713
		zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2714 2715 2716 2717 2718
		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),
2719
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2720 2721 2722 2723
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2724

2725
	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2726
		log.Ctx(ctx).Warn(
2727
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2728
			zap.Error(err),
2729
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2730
			zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2731 2732 2733 2734
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
2735
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2736 2737 2738 2739
			zap.Any("OutputFields", request.OutputFields),
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
2740

2741 2742
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
2743

2744 2745
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2746
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2747 2748 2749 2750 2751
				Reason:    err.Error(),
			},
		}, nil
	}

Z
Zach 已提交
2752
	span := tr.CtxRecord(ctx, "wait search result")
2753 2754
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
Z
Zach 已提交
2755
	log.Ctx(ctx).Debug(
2756
		rpcDone(method),
2757
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2758 2759 2760 2761 2762 2763
		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)),
2764 2765 2766 2767
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2768

2769 2770 2771
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxySearchVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(qt.result.GetResults().GetNumQueries()))
C
cai.zhang 已提交
2772
	searchDur := tr.ElapseSpan().Milliseconds()
X
Xiaofan 已提交
2773
	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2774
		metrics.SearchLabel).Observe(float64(searchDur))
2775 2776 2777 2778 2779

	if qt.result != nil {
		sentSize := proto.Size(qt.result)
		metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
	}
2780 2781 2782
	return qt.result, nil
}

2783
// Flush notify data nodes to persist the data of collection.
2784 2785 2786 2787 2788 2789 2790
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2791
	if !node.checkHealthy() {
2792 2793
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2794
	}
D
dragondriver 已提交
2795 2796 2797 2798 2799

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

2800
	ft := &flushTask{
T
ThreadDao 已提交
2801 2802 2803
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2804
		dataCoord:    node.dataCoord,
2805 2806
	}

D
dragondriver 已提交
2807
	method := "Flush"
2808
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
2809
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2810 2811 2812 2813

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2814
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2815 2816
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2817 2818 2819 2820 2821 2822

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

X
Xiaofan 已提交
2827
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
2828

2829 2830
		resp.Status.Reason = err.Error()
		return resp, nil
2831 2832
	}

D
dragondriver 已提交
2833 2834 2835
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2836
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2837 2838 2839
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2840 2841
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2842 2843 2844 2845

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2846
			zap.Error(err),
D
dragondriver 已提交
2847
			zap.String("traceID", traceID),
2848
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2849 2850 2851
			zap.Int64("MsgID", ft.ID()),
			zap.Uint64("BeginTs", ft.BeginTs()),
			zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2852 2853 2854
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

X
Xiaofan 已提交
2855
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
2856

D
dragondriver 已提交
2857
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2858 2859
		resp.Status.Reason = err.Error()
		return resp, nil
2860 2861
	}

D
dragondriver 已提交
2862 2863 2864
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2865
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2866 2867 2868 2869 2870 2871
		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))

X
Xiaofan 已提交
2872 2873
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2874
	return ft.result, nil
2875 2876
}

2877
// Query get the records by primary keys.
C
Cai Yudong 已提交
2878
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2879 2880 2881 2882 2883
	receiveSize := proto.Size(request)
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.QueryLabel).Add(float64(receiveSize))

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

2884 2885 2886 2887 2888
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2889

D
dragondriver 已提交
2890 2891
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Query")
	defer sp.Finish()
2892
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2893

2894
	qt := &queryTask{
2895 2896 2897 2898 2899
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
			Base: &commonpb.MsgBase{
				MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
2900
				SourceID: Params.ProxyCfg.GetNodeID(),
2901
			},
2902
			ReqID: Params.ProxyCfg.GetNodeID(),
2903
		},
2904 2905
		request:          request,
		qc:               node.queryCoord,
2906
		queryShardPolicy: mergeRoundRobinPolicy,
2907
		shardMgr:         node.shardMgr,
2908 2909
	}

D
dragondriver 已提交
2910 2911
	method := "Query"

2912 2913 2914
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()

Z
Zach 已提交
2915
	log.Ctx(ctx).Info(
D
dragondriver 已提交
2916
		rpcReceived(method),
2917
		zap.String("role", typeutil.ProxyRole),
2918 2919
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2920 2921 2922 2923 2924
		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 已提交
2925

D
dragondriver 已提交
2926
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2927
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
2928 2929 2930
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("role", typeutil.ProxyRole),
2931 2932 2933
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2934

2935 2936 2937
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()

2938 2939 2940 2941 2942 2943
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
2944
	}
Z
Zach 已提交
2945
	tr.CtxRecord(ctx, "query request enqueue")
2946

Z
Zach 已提交
2947
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
2948
		rpcEnqueued(method),
2949
		zap.String("role", typeutil.ProxyRole),
2950
		zap.Int64("msgID", qt.ID()),
2951 2952
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2953
		zap.Strings("partitions", request.PartitionNames))
D
dragondriver 已提交
2954 2955

	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2956
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
2957 2958
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
2959
			zap.String("role", typeutil.ProxyRole),
2960
			zap.Int64("msgID", qt.ID()),
2961 2962 2963
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
2964

2965 2966
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
2967

2968 2969 2970 2971 2972 2973 2974
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2975
	span := tr.CtxRecord(ctx, "wait query result")
2976 2977
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
Z
Zach 已提交
2978
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
2979 2980
		rpcDone(method),
		zap.String("role", typeutil.ProxyRole),
2981
		zap.Int64("msgID", qt.ID()),
2982 2983 2984
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2985

2986 2987 2988 2989
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()

	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2990
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2991 2992

	ret := &milvuspb.QueryResults{
2993 2994
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
2995 2996 2997 2998
	}
	sentSize := proto.Size(qt.result)
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
	return ret, nil
2999
}
3000

3001
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
3002 3003 3004 3005
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3006 3007 3008 3009 3010

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

Y
Yusup 已提交
3011 3012 3013 3014 3015 3016 3017
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
3018
	method := "CreateAlias"
3019
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3020
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039

	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))

X
Xiaofan 已提交
3040
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
3041

Y
Yusup 已提交
3042 3043 3044 3045 3046 3047
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3048 3049 3050
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3051
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3052 3053 3054 3055
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3056 3057
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3058 3059 3060 3061

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3062
			zap.Error(err),
D
dragondriver 已提交
3063
			zap.String("traceID", traceID),
3064
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3065 3066 3067 3068
			zap.Int64("MsgID", cat.ID()),
			zap.Uint64("BeginTs", cat.BeginTs()),
			zap.Uint64("EndTs", cat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3069 3070
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
X
Xiaofan 已提交
3071
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
3072 3073 3074 3075 3076 3077 3078

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

D
dragondriver 已提交
3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089
	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))

X
Xiaofan 已提交
3090 3091
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3092 3093 3094
	return cat.result, nil
}

3095
// DropAlias alter the alias of collection.
Y
Yusup 已提交
3096 3097 3098 3099
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3100 3101 3102 3103 3104

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

Y
Yusup 已提交
3105 3106 3107 3108 3109 3110 3111
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
3112
	method := "DropAlias"
3113
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3114
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130

	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))
X
Xiaofan 已提交
3131
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3132

Y
Yusup 已提交
3133 3134 3135 3136 3137 3138
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3139 3140 3141
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3142
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3143 3144 3145 3146
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3147
		zap.String("alias", request.Alias))
D
dragondriver 已提交
3148 3149 3150 3151

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3152
			zap.Error(err),
D
dragondriver 已提交
3153
			zap.String("traceID", traceID),
3154
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3155 3156 3157 3158
			zap.Int64("MsgID", dat.ID()),
			zap.Uint64("BeginTs", dat.BeginTs()),
			zap.Uint64("EndTs", dat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3159 3160
			zap.String("alias", request.Alias))

X
Xiaofan 已提交
3161
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3162

Y
Yusup 已提交
3163 3164 3165 3166 3167 3168
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
	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))

X
Xiaofan 已提交
3179 3180
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3181 3182 3183
	return dat.result, nil
}

3184
// AlterAlias alter alias of collection.
Y
Yusup 已提交
3185 3186 3187 3188
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3189 3190 3191 3192 3193

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

Y
Yusup 已提交
3194 3195 3196 3197 3198 3199 3200
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
3201
	method := "AlterAlias"
3202
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3203
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221

	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))
X
Xiaofan 已提交
3222
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3223

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

D
dragondriver 已提交
3230 3231 3232
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3233
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3234 3235 3236 3237
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3238 3239
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3240 3241 3242 3243

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3244
			zap.Error(err),
D
dragondriver 已提交
3245
			zap.String("traceID", traceID),
3246
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3247 3248 3249 3250
			zap.Int64("MsgID", aat.ID()),
			zap.Uint64("BeginTs", aat.BeginTs()),
			zap.Uint64("EndTs", aat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3251 3252 3253
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
3254
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3255

Y
Yusup 已提交
3256 3257 3258 3259 3260 3261
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
	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))

X
Xiaofan 已提交
3273 3274
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3275 3276 3277
	return aat.result, nil
}

3278
// CalcDistance calculates the distances between vectors.
3279
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
3280 3281 3282 3283 3284
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
3285

3286 3287 3288 3289
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CalcDistance")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

3290 3291
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
3292

3293 3294 3295 3296 3297
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
3298 3299
		}

3300
		qt := &queryTask{
3301 3302 3303 3304 3305
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
				Base: &commonpb.MsgBase{
					MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
3306
					SourceID: Params.ProxyCfg.GetNodeID(),
3307
				},
3308
				ReqID: Params.ProxyCfg.GetNodeID(),
3309
			},
3310 3311 3312 3313
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

3314
			queryShardPolicy: mergeRoundRobinPolicy,
3315
			shardMgr:         node.shardMgr,
3316 3317
		}

G
groot 已提交
3318 3319 3320 3321 3322 3323
		items := []zapcore.Field{
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
			zap.Any("OutputFields", queryRequest.OutputFields),
		}

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

3328 3329 3330 3331 3332
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3333
			}, err
3334
		}
3335

G
groot 已提交
3336
		log.Debug("CalcDistance queryTask enqueued", items...)
3337 3338 3339

		err = qt.WaitToFinish()
		if err != nil {
G
groot 已提交
3340
			log.Error("CalcDistance queryTask failed to WaitToFinish", append(items, zap.Error(err))...)
3341 3342 3343 3344 3345 3346

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3347
			}, err
3348
		}
3349

G
groot 已提交
3350
		log.Debug("CalcDistance queryTask Done", items...)
3351 3352

		return &milvuspb.QueryResults{
3353 3354
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
3355 3356 3357
		}, nil
	}

G
groot 已提交
3358 3359 3360 3361
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
		traceID:   traceID,
		queryFunc: query,
3362 3363
	}

G
groot 已提交
3364
	return task.Execute(ctx, request)
3365 3366
}

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

3372
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3373
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
D
dragondriver 已提交
3374
	log.Debug("GetPersistentSegmentInfo",
3375
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3376 3377 3378
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3379
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3380
		Status: &commonpb.Status{
3381
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3382 3383
		},
	}
3384 3385 3386 3387
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3388 3389
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3390
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3391
		metrics.TotalLabel).Inc()
G
godchen 已提交
3392
	segments, err := node.getSegmentsOfCollection(ctx, req.DbName, req.CollectionName)
X
XuanYang-cn 已提交
3393
	if err != nil {
3394
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3395 3396
		return resp, nil
	}
3397
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
X
XuanYang-cn 已提交
3398
		Base: &commonpb.MsgBase{
3399
			MsgType:   commonpb.MsgType_SegmentInfo,
X
XuanYang-cn 已提交
3400 3401
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3402
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3403 3404 3405 3406
		},
		SegmentIDs: segments,
	})
	if err != nil {
3407
		log.Debug("GetPersistentSegmentInfo fail", zap.Error(err))
3408
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3409 3410
		return resp, nil
	}
3411
	log.Debug("GetPersistentSegmentInfo ", zap.Int("len(infos)", len(infoResp.Infos)), zap.Any("status", infoResp.Status))
3412
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3413 3414 3415 3416 3417 3418
		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 已提交
3419
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3420 3421
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3422
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3423 3424 3425
			State:        info.State,
		}
	}
X
Xiaofan 已提交
3426
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3427
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
3428
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3429
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3430 3431 3432 3433
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3434
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3435
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
D
dragondriver 已提交
3436
	log.Debug("GetQuerySegmentInfo",
3437
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3438 3439 3440
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3441
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3442
		Status: &commonpb.Status{
3443
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3444 3445
		},
	}
3446 3447 3448 3449
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3450

3451 3452 3453 3454 3455
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3456
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
Z
zhenshan.cao 已提交
3457
		Base: &commonpb.MsgBase{
3458
			MsgType:   commonpb.MsgType_SegmentInfo,
Z
zhenshan.cao 已提交
3459 3460
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3461
			SourceID:  Params.ProxyCfg.GetNodeID(),
Z
zhenshan.cao 已提交
3462
		},
3463
		CollectionID: collID,
Z
zhenshan.cao 已提交
3464 3465
	})
	if err != nil {
3466
		log.Error("Failed to get segment info from QueryCoord",
3467
			zap.Error(err))
Z
zhenshan.cao 已提交
3468 3469 3470
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3471
	log.Debug("GetQuerySegmentInfo ", zap.Any("infos", infoResp.Infos), zap.Any("status", infoResp.Status))
3472
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
3473
		log.Error("Failed to get segment info from QueryCoord", zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
		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 已提交
3487
			State:        info.SegmentState,
3488
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3489 3490
		}
	}
3491
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3492 3493 3494 3495
	resp.Infos = queryInfos
	return resp, nil
}

C
Cai Yudong 已提交
3496
func (node *Proxy) getSegmentsOfCollection(ctx context.Context, dbName string, collectionName string) ([]UniqueID, error) {
3497
	describeCollectionResponse, err := node.rootCoord.DescribeCollection(ctx, &milvuspb.DescribeCollectionRequest{
X
XuanYang-cn 已提交
3498
		Base: &commonpb.MsgBase{
3499
			MsgType:   commonpb.MsgType_DescribeCollection,
X
XuanYang-cn 已提交
3500 3501
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3502
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3503 3504 3505 3506 3507 3508 3509
		},
		DbName:         dbName,
		CollectionName: collectionName,
	})
	if err != nil {
		return nil, err
	}
3510
	if describeCollectionResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3511 3512 3513
		return nil, errors.New(describeCollectionResponse.Status.Reason)
	}
	collectionID := describeCollectionResponse.CollectionID
3514
	showPartitionsResp, err := node.rootCoord.ShowPartitions(ctx, &milvuspb.ShowPartitionsRequest{
X
XuanYang-cn 已提交
3515
		Base: &commonpb.MsgBase{
3516
			MsgType:   commonpb.MsgType_ShowPartitions,
X
XuanYang-cn 已提交
3517 3518
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3519
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3520 3521 3522 3523 3524 3525 3526 3527
		},
		DbName:         dbName,
		CollectionName: collectionName,
		CollectionID:   collectionID,
	})
	if err != nil {
		return nil, err
	}
3528
	if showPartitionsResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3529 3530 3531 3532 3533
		return nil, errors.New(showPartitionsResp.Status.Reason)
	}

	ret := make([]UniqueID, 0)
	for _, partitionID := range showPartitionsResp.PartitionIDs {
3534
		getSegmentsByStatesResponse, err := node.dataCoord.GetSegmentsByStates(ctx, &datapb.GetSegmentsByStatesRequest{
X
XuanYang-cn 已提交
3535 3536
			CollectionID: collectionID,
			PartitionID:  partitionID,
3537
			States:       []commonpb.SegmentState{commonpb.SegmentState_Flushing, commonpb.SegmentState_Flushed, commonpb.SegmentState_Sealed},
X
XuanYang-cn 已提交
3538 3539 3540 3541
		})
		if err != nil {
			return nil, err
		}
3542 3543
		if getSegmentsByStatesResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
			return nil, errors.New(getSegmentsByStatesResponse.Status.Reason)
X
XuanYang-cn 已提交
3544
		}
3545
		ret = append(ret, getSegmentsByStatesResponse.GetSegments()...)
X
XuanYang-cn 已提交
3546 3547 3548
	}
	return ret, nil
}
3549

J
jingkl 已提交
3550
// Dummy handles dummy request
C
Cai Yudong 已提交
3551
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562
	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
	}

3563 3564
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3565
		if err != nil {
3566
			log.Debug("Failed to parse dummy query request")
3567 3568 3569
			return failedResponse, nil
		}

3570
		request := &milvuspb.QueryRequest{
3571 3572 3573
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3574
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3575 3576
		}

3577
		_, err = node.Query(ctx, request)
3578
		if err != nil {
3579
			log.Debug("Failed to execute dummy query")
3580 3581
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3582 3583 3584 3585 3586 3587

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

3588 3589
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3590 3591
}

J
jingkl 已提交
3592
// RegisterLink registers a link
C
Cai Yudong 已提交
3593
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
G
godchen 已提交
3594
	code := node.stateCode.Load().(internalpb.StateCode)
D
dragondriver 已提交
3595
	log.Debug("RegisterLink",
3596
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3597
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3598

G
godchen 已提交
3599
	if code != internalpb.StateCode_Healthy {
3600 3601 3602
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3603
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3604
				Reason:    "proxy not healthy",
3605 3606 3607
			},
		}, nil
	}
X
Xiaofan 已提交
3608
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Inc()
3609 3610 3611
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3612
			ErrorCode: commonpb.ErrorCode_Success,
3613
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3614 3615 3616
		},
	}, nil
}
3617

3618
// GetMetrics gets the metrics of proxy
3619 3620 3621
// 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",
X
Xiaofan 已提交
3622
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3623 3624 3625 3626
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
X
Xiaofan 已提交
3627
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3628
			zap.String("req", req.Request),
X
Xiaofan 已提交
3629
			zap.Error(errProxyIsUnhealthy(Params.ProxyCfg.GetNodeID())))
3630 3631 3632 3633

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
Xiaofan 已提交
3634
				Reason:    msgProxyIsUnhealthy(Params.ProxyCfg.GetNodeID()),
3635 3636 3637 3638 3639 3640 3641 3642
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
X
Xiaofan 已提交
3643
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658
			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))

D
dragondriver 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668
	msgID := UniqueID(0)
	msgID, err = node.idAllocator.AllocOne()
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to allocate id",
			zap.Error(err))
	}
	req.Base = &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     msgID,
		Timestamp: 0,
X
Xiaofan 已提交
3669
		SourceID:  Params.ProxyCfg.GetNodeID(),
D
dragondriver 已提交
3670 3671
	}

3672
	if metricType == metricsinfo.SystemInfoMetrics {
3673 3674 3675 3676 3677 3678 3679
		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))

3680
		metrics, err := getSystemInfoMetrics(ctx, req, node)
3681 3682

		log.Debug("Proxy.GetMetrics",
X
Xiaofan 已提交
3683
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3684 3685 3686 3687 3688
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3689 3690
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3691
		return metrics, nil
3692 3693 3694
	}

	log.Debug("Proxy.GetMetrics failed, request metric type is not implemented yet",
X
Xiaofan 已提交
3695
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
		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
}

3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796
// 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) {
	log.Debug("Proxy.GetProxyMetrics",
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetProxyMetrics failed",
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
			zap.String("req", req.Request),
			zap.Error(errProxyIsUnhealthy(Params.ProxyCfg.GetNodeID())))

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    msgProxyIsUnhealthy(Params.ProxyCfg.GetNodeID()),
			},
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetProxyMetrics failed to parse metric type",
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
			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",
		zap.String("metric_type", metricType))

	msgID := UniqueID(0)
	msgID, err = node.idAllocator.AllocOne()
	if err != nil {
		log.Warn("Proxy.GetProxyMetrics failed to allocate id",
			zap.Error(err))
	}
	req.Base = &commonpb.MsgBase{
		MsgType:  commonpb.MsgType_SystemInfo,
		MsgID:    msgID,
		SourceID: Params.ProxyCfg.GetNodeID(),
	}

	if metricType == metricsinfo.SystemInfoMetrics {
		proxyMetrics, err := getProxyMetrics(ctx, req, node)
		if err != nil {
			log.Warn("Proxy.GetProxyMetrics failed to getProxyMetrics",
				zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
				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",
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Error(err))

		return proxyMetrics, nil
	}

	log.Debug("Proxy.GetProxyMetrics failed, request metric type is not implemented yet",
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
		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 已提交
3797 3798 3799
// 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",
X
Xiaofan 已提交
3800
		zap.Int64("proxy_id", Params.ProxyCfg.GetNodeID()),
B
bigsheeper 已提交
3801 3802 3803 3804 3805 3806 3807 3808 3809
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3810 3811 3812 3813 3814 3815 3816

	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 已提交
3817 3818 3819 3820 3821
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_LoadBalanceSegments,
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3822
			SourceID:  Params.ProxyCfg.GetNodeID(),
B
bigsheeper 已提交
3823 3824 3825
		},
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3826
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3827
		SealedSegmentIDs: req.SealedSegmentIDs,
3828
		CollectionID:     collectionID,
B
bigsheeper 已提交
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845
	})
	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
}

J
jingkl 已提交
3846
//GetCompactionState gets the compaction state of multiple segments
3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
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
}

3860
// ManualCompaction invokes compaction on specified collection
3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
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
}

3874
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
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 已提交
3888 3889 3890
// 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))
3891
	var err error
B
Bingyi Sun 已提交
3892 3893 3894 3895 3896 3897 3898
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Info("unable to get flush state because of closed server")
		return resp, nil
	}

3899
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3900 3901 3902 3903
	if err != nil {
		log.Info("failed to get flush state response", zap.Error(err))
		return nil, err
	}
B
Bingyi Sun 已提交
3904 3905 3906 3907
	log.Info("received get flush state response", zap.Any("response", resp))
	return resp, err
}

C
Cai Yudong 已提交
3908 3909
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3910 3911 3912 3913
	code := node.stateCode.Load().(internalpb.StateCode)
	return code == internalpb.StateCode_Healthy
}

3914 3915 3916 3917 3918
func (node *Proxy) checkHealthyAndReturnCode() (internalpb.StateCode, bool) {
	code := node.stateCode.Load().(internalpb.StateCode)
	return code, code == internalpb.StateCode_Healthy
}

J
jingkl 已提交
3919
//unhealthyStatus returns the proxy not healthy status
3920 3921 3922
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3923
		Reason:    "proxy not healthy",
3924 3925
	}
}
G
groot 已提交
3926 3927 3928

// 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) {
3929 3930 3931
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
		zap.Bool("row-based", req.GetRowBased()))
3932 3933 3934 3935 3936 3937
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3938 3939 3940 3941
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3942
	// Call rootCoord to finish import.
3943 3944 3945 3946 3947 3948 3949 3950
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
		log.Error("failed to execute bulk load request", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
	return respFromRC, nil
G
groot 已提交
3951 3952
}

3953
// GetImportState checks import task state from RootCoord.
G
groot 已提交
3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
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
	}

	resp, err := node.rootCoord.GetImportState(ctx, req)
	log.Info("received get import state response", zap.Int64("taskID", req.GetTask()), zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

// 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
	}

	resp, err := node.rootCoord.ListImportTasks(ctx, req)
	log.Info("received list import tasks response")
	return resp, err
}

X
XuanYang-cn 已提交
3981 3982 3983 3984 3985 3986 3987 3988 3989
// 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
	}

3990 3991
	req.Base = &commonpb.MsgBase{
		MsgType:  commonpb.MsgType_GetReplicas,
X
Xiaofan 已提交
3992
		SourceID: Params.ProxyCfg.GetNodeID(),
3993 3994
	}

X
XuanYang-cn 已提交
3995 3996 3997 3998 3999
	resp, err := node.queryCoord.GetReplicas(ctx, req)
	log.Info("received get replicas response", zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

4000 4001 4002 4003 4004 4005
// 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))
4006
	if !node.checkHealthy() {
4007
		return unhealthyStatus(), nil
4008
	}
4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029

	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))
4030
	if !node.checkHealthy() {
4031
		return unhealthyStatus(), nil
4032
	}
4033 4034

	credInfo := &internalpb.CredentialInfo{
4035 4036
		Username:       request.Username,
		Sha256Password: request.Password,
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051
	}
	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) {
4052 4053
	log.Debug("CreateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4054
		return unhealthyStatus(), nil
4055
	}
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086
	// 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
	}
4087

4088 4089 4090
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
4091
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
	}
	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 已提交
4104
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
4105 4106
	log.Debug("UpdateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4107
		return unhealthyStatus(), nil
4108
	}
C
codeman 已提交
4109 4110 4111 4112 4113 4114 4115 4116 4117
	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)
4118 4119 4120 4121 4122 4123 4124
	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 已提交
4125 4126
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
4127 4128 4129 4130 4131 4132
		log.Error("illegal password", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
4133 4134

	if !passwordVerify(ctx, req.Username, rawOldPassword, globalMetaCache) {
C
codeman 已提交
4135 4136 4137 4138 4139 4140 4141
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
4142 4143 4144 4145 4146 4147 4148
	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 已提交
4149
	updateCredReq := &internalpb.CredentialInfo{
4150
		Username:          req.Username,
4151
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
4152 4153
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
4154
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
	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) {
4166 4167
	log.Debug("DeleteCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4168
		return unhealthyStatus(), nil
4169 4170
	}

4171 4172 4173 4174 4175 4176
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188
	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) {
4189 4190
	log.Debug("ListCredUsers", zap.String("role", typeutil.ProxyRole))
	if !node.checkHealthy() {
4191
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
4192
	}
4193 4194 4195 4196 4197 4198
	rootCoordReq := &milvuspb.ListCredUsersRequest{
		Base: &commonpb.MsgBase{
			MsgType: commonpb.MsgType_ListCredUsernames,
		},
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210
	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,
		},
4211
		Usernames: resp.Usernames,
4212 4213
	}, nil
}
4214

4215 4216 4217
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 {
4218
		return errorutil.UnhealthyStatus(code), nil
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228
	}

	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(),
4229
		}, nil
4230 4231 4232 4233 4234 4235 4236 4237
	}

	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(),
4238
		}, nil
4239 4240
	}
	return result, nil
4241 4242
}

4243 4244 4245
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 {
4246
		return errorutil.UnhealthyStatus(code), nil
4247 4248 4249 4250 4251
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4252
		}, nil
4253
	}
4254 4255 4256 4257 4258
	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,
4259
		}, nil
4260
	}
4261 4262 4263 4264 4265 4266
	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(),
4267
		}, nil
4268 4269
	}
	return result, nil
4270 4271
}

4272 4273 4274
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 {
4275
		return errorutil.UnhealthyStatus(code), nil
4276 4277 4278 4279 4280
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4281
		}, nil
4282 4283 4284 4285 4286
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4287
		}, nil
4288 4289 4290 4291 4292 4293 4294 4295
	}

	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(),
4296
		}, nil
4297 4298
	}
	return result, nil
4299 4300
}

4301 4302 4303
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 {
4304
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4305 4306 4307 4308 4309 4310 4311 4312 4313
	}

	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(),
				},
4314
			}, nil
4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325
		}
	}

	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(),
			},
4326
		}, nil
4327 4328
	}
	return result, nil
4329 4330
}

4331 4332 4333
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 {
4334
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4335 4336 4337 4338 4339 4340 4341 4342 4343
	}

	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(),
				},
4344
			}, nil
4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
		}
	}

	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(),
			},
4356
		}, nil
4357 4358
	}
	return result, nil
4359 4360
}

4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390
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
4391 4392
}

4393 4394 4395
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 {
4396
		return errorutil.UnhealthyStatus(code), nil
4397 4398 4399 4400 4401
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4402
		}, nil
4403 4404 4405 4406 4407 4408
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4409
		}, nil
4410 4411 4412 4413 4414 4415 4416 4417
	}
	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(),
4418
		}, nil
4419 4420
	}
	return result, nil
4421 4422
}

4423 4424 4425 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
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 {
4452
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4453 4454 4455 4456 4457 4458 4459 4460
	}

	if err := node.validGrantParams(req); err != nil {
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_IllegalArgument,
				Reason:    err.Error(),
			},
4461
		}, nil
4462 4463 4464 4465 4466 4467 4468 4469 4470 4471
	}

	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(),
			},
4472
		}, nil
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500
	}
	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
4501
}
4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522

// SetRates limits the rates of requests.
func (node *Proxy) SetRates(ctx context.Context, request *proxypb.SetRatesRequest) (*commonpb.Status, error) {
	log.Debug("SetRates", zap.String("role", typeutil.ProxyRole), zap.Any("rates", request.GetRates()))
	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
}