impl.go 158.9 KB
Newer Older
1 2 3 4 5 6
// Licensed to the LF AI & Data foundation under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
7 8
// with the License. You may obtain a copy of the License at
//
9
//     http://www.apache.org/licenses/LICENSE-2.0
10
//
11 12 13 14 15
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
16

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

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

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

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

52 53
const moduleName = "Proxy"

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

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

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

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

109
	collectionName := request.CollectionName
110
	collectionID := request.CollectionID
N
neza2017 已提交
111
	if globalMetaCache != nil {
112 113 114 115 116 117
		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 已提交
118
	}
119 120
	if request.GetBase().GetMsgType() == commonpb.MsgType_DropCollection {
		// no need to handle error, since this Proxy may not create dml stream for the collection.
121 122 123
		node.chMgr.removeDMLStream(request.GetCollectionID())
		// clean up collection level metrics
		metrics.CleanupCollectionMetrics(Params.ProxyCfg.GetNodeID(), collectionName)
124
	}
125
	logutil.Logger(ctx).Info("complete to invalidate collection meta cache",
126
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
127
		zap.String("db", request.DbName),
128 129
		zap.String("collection", collectionName),
		zap.Int64("collectionID", collectionID))
D
dragondriver 已提交
130

131
	return &commonpb.Status{
132
		ErrorCode: commonpb.ErrorCode_Success,
133 134
		Reason:    "",
	}, nil
135 136
}

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

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

150
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
151

152
	cct := &createCollectionTask{
S
sunby 已提交
153
		ctx:                     ctx,
154 155
		Condition:               NewTaskCondition(ctx),
		CreateCollectionRequest: request,
156
		rootCoord:               node.rootCoord,
157 158
	}

159 160 161
	// avoid data race
	lenOfSchema := len(request.Schema)

162 163
	log.Debug(
		rpcReceived(method),
164
		zap.String("traceID", traceID),
165
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
166 167
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
168
		zap.Int("len(schema)", lenOfSchema),
169 170
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
171

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

184
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
185
		return &commonpb.Status{
186
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
187 188 189 190
			Reason:    err.Error(),
		}, nil
	}

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

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

220
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
221
		return &commonpb.Status{
222
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
223 224 225 226
			Reason:    err.Error(),
		}, nil
	}

227 228
	log.Debug(
		rpcDone(method),
229
		zap.String("traceID", traceID),
230
		zap.String("role", typeutil.ProxyRole),
231 232 233 234 235 236
		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),
237 238
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
239

240 241
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
242 243 244
	return cct.result, nil
}

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

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
254 255
	method := "DropCollection"
	tr := timerecord.NewTimeRecorder(method)
256
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
257

258
	dct := &dropCollectionTask{
S
sunby 已提交
259
		ctx:                   ctx,
260 261
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
262
		rootCoord:             node.rootCoord,
263
		chMgr:                 node.chMgr,
S
sunby 已提交
264
		chTicker:              node.chTicker,
265 266
	}

267 268
	log.Debug("DropCollection received",
		zap.String("traceID", traceID),
269
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
270 271
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
272 273 274 275 276

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

281
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
282
		return &commonpb.Status{
283
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
284 285 286 287
			Reason:    err.Error(),
		}, nil
	}

288 289
	log.Debug("DropCollection enqueued",
		zap.String("traceID", traceID),
290
		zap.String("role", typeutil.ProxyRole),
291 292 293
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
294 295
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
296 297 298

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

308
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
309
		return &commonpb.Status{
310
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
311 312 313 314
			Reason:    err.Error(),
		}, nil
	}

315 316
	log.Debug("DropCollection done",
		zap.String("traceID", traceID),
317
		zap.String("role", typeutil.ProxyRole),
318 319 320 321 322 323
		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))

324 325
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
326 327 328
	return dct.result, nil
}

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

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
340 341
	method := "HasCollection"
	tr := timerecord.NewTimeRecorder(method)
342
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
343
		metrics.TotalLabel).Inc()
344 345 346

	log.Debug("HasCollection received",
		zap.String("traceID", traceID),
347
		zap.String("role", typeutil.ProxyRole),
348 349 350
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

351
	hct := &hasCollectionTask{
S
sunby 已提交
352
		ctx:                  ctx,
353 354
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
355
		rootCoord:            node.rootCoord,
356 357
	}

358 359 360 361
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
362
			zap.String("role", typeutil.ProxyRole),
363 364 365
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

366
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
367
			metrics.AbandonLabel).Inc()
368 369
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
370
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
371 372 373 374 375
				Reason:    err.Error(),
			},
		}, nil
	}

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

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

396
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
397
			metrics.FailLabel).Inc()
398 399
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
400
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
401 402 403 404 405
				Reason:    err.Error(),
			},
		}, nil
	}

406 407
	log.Debug("HasCollection done",
		zap.String("traceID", traceID),
408
		zap.String("role", typeutil.ProxyRole),
409 410 411 412 413 414
		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))

415
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
416
		metrics.SuccessLabel).Inc()
417
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
418 419 420
	return hct.result, nil
}

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

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
430 431
	method := "LoadCollection"
	tr := timerecord.NewTimeRecorder(method)
432 433
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
434
	lct := &loadCollectionTask{
S
sunby 已提交
435
		ctx:                   ctx,
436 437
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
438
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
439
		indexCoord:            node.indexCoord,
440 441
	}

442 443
	log.Debug("LoadCollection received",
		zap.String("traceID", traceID),
444
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
445 446
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
447 448 449 450 451

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

456
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
457
			metrics.AbandonLabel).Inc()
458
		return &commonpb.Status{
459
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
460 461 462
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
463

464 465
	log.Debug("LoadCollection enqueued",
		zap.String("traceID", traceID),
466
		zap.String("role", typeutil.ProxyRole),
467 468 469
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
470 471
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
472 473 474

	if err := lct.WaitToFinish(); err != nil {
		log.Warn("LoadCollection failed to WaitToFinish",
D
dragondriver 已提交
475
			zap.Error(err),
476
			zap.String("traceID", traceID),
477
			zap.String("role", typeutil.ProxyRole),
478 479 480
			zap.Int64("MsgID", lct.ID()),
			zap.Uint64("BeginTS", lct.BeginTs()),
			zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
481 482
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))
483
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
484
			metrics.FailLabel).Inc()
485
		return &commonpb.Status{
486
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
487 488 489 490
			Reason:    err.Error(),
		}, nil
	}

491 492
	log.Debug("LoadCollection done",
		zap.String("traceID", traceID),
493
		zap.String("role", typeutil.ProxyRole),
494 495 496 497 498 499
		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))

500
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
501
		metrics.SuccessLabel).Inc()
502
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
503
	return lct.result, nil
504 505
}

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

512
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleaseCollection")
513 514
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
515 516
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
517 518
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
519
	rct := &releaseCollectionTask{
S
sunby 已提交
520
		ctx:                      ctx,
521 522
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
523
		queryCoord:               node.queryCoord,
524
		chMgr:                    node.chMgr,
525 526
	}

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

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

543
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
544
			metrics.AbandonLabel).Inc()
545
		return &commonpb.Status{
546
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
547 548 549 550
			Reason:    err.Error(),
		}, nil
	}

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

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

573
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
574
			metrics.FailLabel).Inc()
575
		return &commonpb.Status{
576
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
577 578 579 580
			Reason:    err.Error(),
		}, nil
	}

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

591
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
592
		metrics.SuccessLabel).Inc()
593
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
594
	return rct.result, nil
595 596
}

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

605
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeCollection")
606 607
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
608 609
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
610 611
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
612

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

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

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

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

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

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

664
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
665
			metrics.FailLabel).Inc()
666

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

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

684
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
685
		metrics.SuccessLabel).Inc()
686
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
687 688 689
	return dct.result, nil
}

690 691 692 693 694 695 696 697 698 699 700 701 702 703
// 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)
704 705
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
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
	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))

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

769
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
			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))

790
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
791
		metrics.SuccessLabel).Inc()
792
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
793 794 795
	return g.result, nil
}

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

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetCollectionStatistics")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
807 808
	method := "GetCollectionStatistics"
	tr := timerecord.NewTimeRecorder(method)
809 810
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
811
	g := &getCollectionStatisticsTask{
G
godchen 已提交
812 813 814
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
815
		dataCoord:                      node.dataCoord,
816 817
	}

818 819
	log.Debug(
		rpcReceived(method),
820
		zap.String("traceID", traceID),
821
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
822 823
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
824 825

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
826 827
		log.Warn(
			rpcFailedToEnqueue(method),
828 829
			zap.Error(err),
			zap.String("traceID", traceID),
830
			zap.String("role", typeutil.ProxyRole),
831 832 833
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

834
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
835
			metrics.AbandonLabel).Inc()
836

G
godchen 已提交
837
		return &milvuspb.GetCollectionStatisticsResponse{
838
			Status: &commonpb.Status{
839
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
840 841 842 843 844
				Reason:    err.Error(),
			},
		}, nil
	}

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

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

867
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
868
			metrics.FailLabel).Inc()
869

G
godchen 已提交
870
		return &milvuspb.GetCollectionStatisticsResponse{
871
			Status: &commonpb.Status{
872
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
873 874 875 876 877
				Reason:    err.Error(),
			},
		}, nil
	}

878 879
	log.Debug(
		rpcDone(method),
880
		zap.String("traceID", traceID),
881
		zap.String("role", typeutil.ProxyRole),
882
		zap.Int64("msgID", g.ID()),
883 884 885 886 887
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

888
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
889
		metrics.SuccessLabel).Inc()
890
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
891
	return g.result, nil
892 893
}

894
// ShowCollections list all collections in Milvus.
C
Cai Yudong 已提交
895
func (node *Proxy) ShowCollections(ctx context.Context, request *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
896 897 898 899 900
	if !node.checkHealthy() {
		return &milvuspb.ShowCollectionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
901 902
	method := "ShowCollections"
	tr := timerecord.NewTimeRecorder(method)
903
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
904

905
	sct := &showCollectionsTask{
G
godchen 已提交
906 907 908
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
909
		queryCoord:             node.queryCoord,
910
		rootCoord:              node.rootCoord,
911 912
	}

913
	log.Debug("ShowCollections received",
914
		zap.String("role", typeutil.ProxyRole),
915 916 917 918 919 920
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
		zap.Any("CollectionNames", request.CollectionNames),
	)

921
	err := node.sched.ddQueue.Enqueue(sct)
922
	if err != nil {
923 924
		log.Warn("ShowCollections failed to enqueue",
			zap.Error(err),
925
			zap.String("role", typeutil.ProxyRole),
926 927 928 929 930 931
			zap.String("DbName", request.DbName),
			zap.Uint64("TimeStamp", request.TimeStamp),
			zap.String("ShowType", request.Type.String()),
			zap.Any("CollectionNames", request.CollectionNames),
		)

932
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
G
godchen 已提交
933
		return &milvuspb.ShowCollectionsResponse{
934
			Status: &commonpb.Status{
935
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
936 937 938 939 940
				Reason:    err.Error(),
			},
		}, nil
	}

941
	log.Debug("ShowCollections enqueued",
942
		zap.String("role", typeutil.ProxyRole),
943
		zap.Int64("MsgID", sct.ID()),
944
		zap.String("DbName", sct.ShowCollectionsRequest.DbName),
945
		zap.Uint64("TimeStamp", request.TimeStamp),
946 947 948
		zap.String("ShowType", sct.ShowCollectionsRequest.Type.String()),
		zap.Any("CollectionNames", sct.ShowCollectionsRequest.CollectionNames),
	)
D
dragondriver 已提交
949

950 951
	err = sct.WaitToFinish()
	if err != nil {
952 953
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
954
			zap.String("role", typeutil.ProxyRole),
955 956 957 958 959 960 961
			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),
		)

962
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
963

G
godchen 已提交
964
		return &milvuspb.ShowCollectionsResponse{
965
			Status: &commonpb.Status{
966
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
967 968 969 970 971
				Reason:    err.Error(),
			},
		}, nil
	}

972
	log.Debug("ShowCollections Done",
973
		zap.String("role", typeutil.ProxyRole),
974 975 976 977
		zap.Int64("MsgID", sct.ID()),
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
978 979
		zap.Int("len(CollectionNames)", len(request.CollectionNames)),
		zap.Int("num_collections", len(sct.result.CollectionNames)))
980

981 982
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
983 984 985
	return sct.result, nil
}

J
jaime 已提交
986 987 988 989 990 991 992 993 994 995 996
func (node *Proxy) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

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

997
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
J
jaime 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021

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

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

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

1022
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
J
jaime 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

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

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

1052
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
J
jaime 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

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

1069 1070
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
J
jaime 已提交
1071 1072 1073
	return act.result, nil
}

1074
// CreatePartition create a partition in specific collection.
C
Cai Yudong 已提交
1075
func (node *Proxy) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
1076 1077 1078
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1079

1080
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreatePartition")
1081 1082
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1083 1084
	method := "CreatePartition"
	tr := timerecord.NewTimeRecorder(method)
1085
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1086

1087
	cpt := &createPartitionTask{
S
sunby 已提交
1088
		ctx:                    ctx,
1089 1090
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
1091
		rootCoord:              node.rootCoord,
1092 1093 1094
		result:                 nil,
	}

1095 1096 1097
	log.Debug(
		rpcReceived("CreatePartition"),
		zap.String("traceID", traceID),
1098
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1099 1100 1101
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1102 1103 1104 1105 1106 1107

	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
			zap.Error(err),
			zap.String("traceID", traceID),
1108
			zap.String("role", typeutil.ProxyRole),
1109 1110 1111 1112
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1113
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1114

1115
		return &commonpb.Status{
1116
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1117 1118 1119
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1120

1121 1122 1123
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.String("traceID", traceID),
1124
		zap.String("role", typeutil.ProxyRole),
1125 1126 1127
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1128 1129 1130
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1131 1132 1133 1134

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
1135
			zap.Error(err),
1136
			zap.String("traceID", traceID),
1137
			zap.String("role", typeutil.ProxyRole),
1138 1139 1140
			zap.Int64("MsgID", cpt.ID()),
			zap.Uint64("BeginTS", cpt.BeginTs()),
			zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1141 1142 1143 1144
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1145
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1146

1147
		return &commonpb.Status{
1148
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1149 1150 1151
			Reason:    err.Error(),
		}, nil
	}
1152 1153 1154 1155

	log.Debug(
		rpcDone("CreatePartition"),
		zap.String("traceID", traceID),
1156
		zap.String("role", typeutil.ProxyRole),
1157 1158 1159 1160 1161 1162 1163
		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))

1164 1165
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1166 1167 1168
	return cpt.result, nil
}

1169
// DropPartition drop a partition in specific collection.
C
Cai Yudong 已提交
1170
func (node *Proxy) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
1171 1172 1173
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1174

1175
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropPartition")
1176 1177
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1178 1179
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
1180
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1181

1182
	dpt := &dropPartitionTask{
S
sunby 已提交
1183
		ctx:                  ctx,
1184 1185
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
1186
		rootCoord:            node.rootCoord,
1187 1188 1189
		result:               nil,
	}

1190 1191 1192
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1193
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1194 1195 1196
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1197 1198 1199 1200 1201 1202

	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1203
			zap.String("role", typeutil.ProxyRole),
1204 1205 1206 1207
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1208
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
1209

1210
		return &commonpb.Status{
1211
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1212 1213 1214
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1215

1216 1217 1218
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1219
		zap.String("role", typeutil.ProxyRole),
1220 1221 1222
		zap.Int64("MsgID", dpt.ID()),
		zap.Uint64("BeginTS", dpt.BeginTs()),
		zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1223 1224 1225
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1226 1227 1228 1229

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1230
			zap.Error(err),
1231
			zap.String("traceID", traceID),
1232
			zap.String("role", typeutil.ProxyRole),
1233 1234 1235
			zap.Int64("MsgID", dpt.ID()),
			zap.Uint64("BeginTS", dpt.BeginTs()),
			zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1236 1237 1238 1239
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1240
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1241

1242
		return &commonpb.Status{
1243
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1244 1245 1246
			Reason:    err.Error(),
		}, nil
	}
1247 1248 1249 1250

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1251
		zap.String("role", typeutil.ProxyRole),
1252 1253 1254 1255 1256 1257 1258
		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))

1259 1260
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1261 1262 1263
	return dpt.result, nil
}

1264
// HasPartition check if partition exist.
C
Cai Yudong 已提交
1265
func (node *Proxy) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
1266 1267 1268 1269 1270
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
D
dragondriver 已提交
1271

D
dragondriver 已提交
1272
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasPartition")
D
dragondriver 已提交
1273 1274
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1275 1276 1277
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
1278
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1279
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1280

1281
	hpt := &hasPartitionTask{
S
sunby 已提交
1282
		ctx:                 ctx,
1283 1284
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1285
		rootCoord:           node.rootCoord,
1286 1287 1288
		result:              nil,
	}

D
dragondriver 已提交
1289 1290 1291
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1292
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1293 1294 1295
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1296 1297 1298 1299 1300 1301

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

1307
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1308
			metrics.AbandonLabel).Inc()
1309

1310 1311
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1312
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1313 1314 1315 1316 1317
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1318

D
dragondriver 已提交
1319 1320 1321
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1322
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1323 1324 1325
		zap.Int64("MsgID", hpt.ID()),
		zap.Uint64("BeginTS", hpt.BeginTs()),
		zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1326 1327 1328
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1329 1330 1331 1332

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1333
			zap.Error(err),
D
dragondriver 已提交
1334
			zap.String("traceID", traceID),
1335
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1336 1337 1338
			zap.Int64("MsgID", hpt.ID()),
			zap.Uint64("BeginTS", hpt.BeginTs()),
			zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1339 1340 1341 1342
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1343
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1344
			metrics.FailLabel).Inc()
1345

1346 1347
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1348
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1349 1350 1351 1352 1353
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1354 1355 1356 1357

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1358
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1359 1360 1361 1362 1363 1364 1365
		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))

1366
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1367
		metrics.SuccessLabel).Inc()
1368
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1369 1370 1371
	return hpt.result, nil
}

1372
// LoadPartitions load specific partitions into query nodes.
C
Cai Yudong 已提交
1373
func (node *Proxy) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
1374 1375 1376
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1377

D
dragondriver 已提交
1378
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadPartitions")
1379 1380
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1381 1382
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
1383 1384
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
1385
	lpt := &loadPartitionsTask{
G
godchen 已提交
1386 1387 1388
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1389
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
1390
		indexCoord:            node.indexCoord,
1391 1392
	}

1393 1394 1395
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1396
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1397 1398 1399
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1400 1401 1402 1403 1404 1405

	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1406
			zap.String("role", typeutil.ProxyRole),
1407 1408 1409 1410
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

1411
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1412
			metrics.AbandonLabel).Inc()
1413

1414
		return &commonpb.Status{
1415
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1416 1417 1418 1419
			Reason:    err.Error(),
		}, nil
	}

1420 1421 1422
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1423
		zap.String("role", typeutil.ProxyRole),
1424 1425 1426
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1427 1428 1429
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1430 1431 1432 1433

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1434
			zap.Error(err),
1435
			zap.String("traceID", traceID),
1436
			zap.String("role", typeutil.ProxyRole),
1437 1438 1439
			zap.Int64("MsgID", lpt.ID()),
			zap.Uint64("BeginTS", lpt.BeginTs()),
			zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1440 1441 1442 1443
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

1444
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1445
			metrics.FailLabel).Inc()
1446

1447
		return &commonpb.Status{
1448
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1449 1450 1451 1452
			Reason:    err.Error(),
		}, nil
	}

1453 1454 1455
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1456
		zap.String("role", typeutil.ProxyRole),
1457 1458 1459 1460 1461 1462 1463
		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))

1464
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1465
		metrics.SuccessLabel).Inc()
1466
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1467
	return lpt.result, nil
1468 1469
}

1470
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1471
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1472 1473 1474
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1475 1476 1477 1478 1479

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

1480
	rpt := &releasePartitionsTask{
G
godchen 已提交
1481 1482 1483
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1484
		queryCoord:               node.queryCoord,
1485 1486
	}

1487
	method := "ReleasePartitions"
1488
	tr := timerecord.NewTimeRecorder(method)
1489 1490
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
1491 1492 1493
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1494
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1495 1496 1497
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1498 1499 1500 1501 1502 1503

	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1504
			zap.String("role", typeutil.ProxyRole),
1505 1506 1507 1508
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

1509
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1510
			metrics.AbandonLabel).Inc()
1511

1512
		return &commonpb.Status{
1513
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1514 1515 1516 1517
			Reason:    err.Error(),
		}, nil
	}

1518 1519 1520
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1521
		zap.String("role", typeutil.ProxyRole),
1522 1523 1524
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1525 1526 1527
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1528 1529 1530 1531

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1532
			zap.Error(err),
1533
			zap.String("traceID", traceID),
1534
			zap.String("role", typeutil.ProxyRole),
1535 1536 1537
			zap.Int64("msgID", rpt.Base.MsgID),
			zap.Uint64("BeginTS", rpt.BeginTs()),
			zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1538 1539 1540 1541
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

1542
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1543
			metrics.FailLabel).Inc()
1544

1545
		return &commonpb.Status{
1546
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1547 1548 1549 1550
			Reason:    err.Error(),
		}, nil
	}

1551 1552 1553
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1554
		zap.String("role", typeutil.ProxyRole),
1555 1556 1557 1558 1559 1560 1561
		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))

1562
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1563
		metrics.SuccessLabel).Inc()
1564
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1565
	return rpt.result, nil
1566 1567
}

1568
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1569
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1570 1571 1572 1573 1574
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1575 1576 1577 1578

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-GetPartitionStatistics")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1579 1580
	method := "GetPartitionStatistics"
	tr := timerecord.NewTimeRecorder(method)
1581 1582
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
1583

1584
	g := &getPartitionStatisticsTask{
1585 1586 1587
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1588
		dataCoord:                     node.dataCoord,
1589 1590
	}

1591 1592 1593
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1594
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1595 1596 1597
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1598 1599 1600 1601 1602 1603

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1604
			zap.String("role", typeutil.ProxyRole),
1605 1606 1607 1608
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1609
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1610
			metrics.AbandonLabel).Inc()
1611

1612 1613 1614 1615 1616 1617 1618 1619
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1620 1621 1622
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1623
		zap.String("role", typeutil.ProxyRole),
1624 1625 1626
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
1627 1628 1629
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1630 1631 1632 1633

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1634
			zap.Error(err),
1635
			zap.String("traceID", traceID),
1636
			zap.String("role", typeutil.ProxyRole),
1637 1638 1639
			zap.Int64("msgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
1640 1641 1642 1643
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

1644
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1645
			metrics.FailLabel).Inc()
1646

1647 1648 1649 1650 1651 1652 1653 1654
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1655 1656 1657
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1658
		zap.String("role", typeutil.ProxyRole),
1659 1660 1661 1662 1663 1664 1665
		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))

1666
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1667
		metrics.SuccessLabel).Inc()
1668
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1669
	return g.result, nil
1670 1671
}

1672
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1673
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1674 1675 1676 1677 1678
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1679 1680 1681 1682 1683

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

1684
	spt := &showPartitionsTask{
G
godchen 已提交
1685 1686 1687
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1688
		rootCoord:             node.rootCoord,
1689
		queryCoord:            node.queryCoord,
G
godchen 已提交
1690
		result:                nil,
1691 1692
	}

1693
	method := "ShowPartitions"
1694 1695
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
1696
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1697
		metrics.TotalLabel).Inc()
1698 1699 1700 1701

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1702
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1703
		zap.Any("request", request))
1704 1705 1706 1707 1708 1709

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

1713
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1714
			metrics.AbandonLabel).Inc()
1715

G
godchen 已提交
1716
		return &milvuspb.ShowPartitionsResponse{
1717
			Status: &commonpb.Status{
1718
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1719 1720 1721 1722 1723
				Reason:    err.Error(),
			},
		}, nil
	}

1724 1725 1726
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1727
		zap.String("role", typeutil.ProxyRole),
1728 1729 1730
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1731 1732
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1733 1734 1735 1736 1737
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1738
			zap.Error(err),
1739
			zap.String("traceID", traceID),
1740
			zap.String("role", typeutil.ProxyRole),
1741 1742 1743 1744 1745 1746
			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 已提交
1747

1748
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1749
			metrics.FailLabel).Inc()
1750

G
godchen 已提交
1751
		return &milvuspb.ShowPartitionsResponse{
1752
			Status: &commonpb.Status{
1753
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1754 1755 1756 1757
				Reason:    err.Error(),
			},
		}, nil
	}
1758 1759 1760 1761

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1762
		zap.String("role", typeutil.ProxyRole),
1763 1764 1765 1766 1767 1768 1769
		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))

1770
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1771
		metrics.SuccessLabel).Inc()
1772
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1773 1774 1775
	return spt.result, nil
}

S
SimFG 已提交
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
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)
1839
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
S
SimFG 已提交
1840 1841 1842 1843 1844 1845 1846 1847
	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))
1848
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
S
SimFG 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
		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
	}
1863 1864 1865 1866 1867
	msgBase := &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     0,
		Timestamp: 0,
		SourceID:  Params.ProxyCfg.GetNodeID(),
S
SimFG 已提交
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
	}
	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))
1892 1893
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
S
SimFG 已提交
1894 1895 1896 1897 1898 1899 1900 1901
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1902
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1903
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1904 1905 1906
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1907 1908 1909 1910 1911

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

1912
	cit := &createIndexTask{
Z
zhenshan.cao 已提交
1913 1914 1915 1916 1917
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		req:        request,
		rootCoord:  node.rootCoord,
		indexCoord: node.indexCoord,
1918 1919
	}

D
dragondriver 已提交
1920
	method := "CreateIndex"
1921
	tr := timerecord.NewTimeRecorder(method)
1922 1923
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1924 1925 1926
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1927
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1928 1929 1930 1931
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1932 1933 1934 1935 1936 1937

	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1938
			zap.String("role", typeutil.ProxyRole),
Z
zhenshan.cao 已提交
1939 1940 1941 1942
			zap.String("db", request.GetDbName()),
			zap.String("collection", request.GetCollectionName()),
			zap.String("field", request.GetFieldName()),
			zap.Any("extra_params", request.GetExtraParams()))
D
dragondriver 已提交
1943

1944
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1945
			metrics.AbandonLabel).Inc()
1946

1947
		return &commonpb.Status{
1948
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1949 1950 1951 1952
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1953 1954 1955
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1956
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1957 1958 1959
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1960 1961 1962 1963
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1964 1965 1966 1967

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1968
			zap.Error(err),
D
dragondriver 已提交
1969
			zap.String("traceID", traceID),
1970
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1971 1972 1973
			zap.Int64("MsgID", cit.ID()),
			zap.Uint64("BeginTs", cit.BeginTs()),
			zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1974 1975 1976 1977 1978
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

1979
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1980
			metrics.FailLabel).Inc()
1981

1982
		return &commonpb.Status{
1983
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1984 1985 1986 1987
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1988 1989 1990
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1991
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1992 1993 1994 1995 1996 1997 1998 1999
		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))

2000
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2001
		metrics.SuccessLabel).Inc()
2002
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2003 2004 2005
	return cit.result, nil
}

2006
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
2007
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
2008 2009 2010 2011 2012
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2013 2014 2015 2016 2017

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

2018
	dit := &describeIndexTask{
S
sunby 已提交
2019
		ctx:                  ctx,
2020 2021
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
2022
		indexCoord:           node.indexCoord,
2023 2024
	}

2025 2026 2027
	method := "DescribeIndex"
	// avoid data race
	indexName := request.IndexName
2028
	tr := timerecord.NewTimeRecorder(method)
2029 2030
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2031 2032 2033
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2034
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2035 2036 2037
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2038 2039 2040 2041 2042 2043 2044
		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),
2045
			zap.String("role", typeutil.ProxyRole),
2046 2047 2048 2049 2050
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", indexName))

2051
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2052
			metrics.AbandonLabel).Inc()
2053

2054 2055
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
2056
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2057 2058 2059 2060 2061
				Reason:    err.Error(),
			},
		}, nil
	}

2062 2063 2064
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2065
		zap.String("role", typeutil.ProxyRole),
2066 2067 2068
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2069 2070 2071
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2072 2073 2074 2075 2076
		zap.String("index name", indexName))

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2077
			zap.Error(err),
2078
			zap.String("traceID", traceID),
2079
			zap.String("role", typeutil.ProxyRole),
2080 2081 2082
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2083 2084 2085
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
2086
			zap.String("index name", indexName))
D
dragondriver 已提交
2087

Z
zhenshan.cao 已提交
2088 2089 2090 2091
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
2092
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2093
			metrics.FailLabel).Inc()
2094

2095 2096
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
2097
				ErrorCode: errCode,
2098 2099 2100 2101 2102
				Reason:    err.Error(),
			},
		}, nil
	}

2103 2104 2105
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2106
		zap.String("role", typeutil.ProxyRole),
2107 2108 2109 2110 2111 2112 2113 2114
		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))

2115
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2116
		metrics.SuccessLabel).Inc()
2117
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2118 2119 2120
	return dit.result, nil
}

2121
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
2122
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
2123 2124 2125
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2126 2127 2128 2129 2130

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

2131
	dit := &dropIndexTask{
S
sunby 已提交
2132
		ctx:              ctx,
B
BossZou 已提交
2133 2134
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
2135
		indexCoord:       node.indexCoord,
B
BossZou 已提交
2136
	}
G
godchen 已提交
2137

D
dragondriver 已提交
2138
	method := "DropIndex"
2139
	tr := timerecord.NewTimeRecorder(method)
2140 2141
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2142 2143 2144 2145

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2146
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2147 2148 2149 2150 2151
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

D
dragondriver 已提交
2152 2153 2154 2155 2156
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2157
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2158 2159 2160 2161
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
2162
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2163
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2164

B
BossZou 已提交
2165
		return &commonpb.Status{
2166
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2167 2168 2169
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2170

D
dragondriver 已提交
2171 2172 2173
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2174
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2175 2176 2177
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2178 2179 2180 2181
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
D
dragondriver 已提交
2182 2183 2184 2185

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2186
			zap.Error(err),
D
dragondriver 已提交
2187
			zap.String("traceID", traceID),
2188
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2189 2190 2191
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2192 2193 2194 2195 2196
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

2197
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2198
			metrics.FailLabel).Inc()
2199

B
BossZou 已提交
2200
		return &commonpb.Status{
2201
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2202 2203 2204
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2205 2206 2207 2208

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2209
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2210 2211 2212 2213 2214 2215 2216 2217
		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))

2218
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2219
		metrics.SuccessLabel).Inc()
2220
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
2221 2222 2223
	return dit.result, nil
}

2224 2225
// 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.
2226
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2227
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
2228 2229 2230 2231 2232
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2233 2234 2235 2236 2237

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

2238
	gibpt := &getIndexBuildProgressTask{
2239 2240 2241
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
2242 2243
		indexCoord:                   node.indexCoord,
		rootCoord:                    node.rootCoord,
2244
		dataCoord:                    node.dataCoord,
2245 2246
	}

2247
	method := "GetIndexBuildProgress"
2248
	tr := timerecord.NewTimeRecorder(method)
2249 2250
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2251 2252 2253
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2254
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2255 2256 2257 2258
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2259 2260 2261 2262 2263 2264

	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2265
			zap.String("role", typeutil.ProxyRole),
2266 2267 2268 2269
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
2270
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2271
			metrics.AbandonLabel).Inc()
2272

2273 2274 2275 2276 2277 2278 2279 2280
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2281 2282 2283
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2284
		zap.String("role", typeutil.ProxyRole),
2285 2286 2287
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
2288 2289 2290 2291
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2292 2293 2294 2295

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
2296
			zap.Error(err),
2297
			zap.String("traceID", traceID),
2298
			zap.String("role", typeutil.ProxyRole),
2299 2300 2301
			zap.Int64("MsgID", gibpt.ID()),
			zap.Uint64("BeginTs", gibpt.BeginTs()),
			zap.Uint64("EndTs", gibpt.EndTs()),
2302 2303 2304 2305
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
2306
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2307
			metrics.FailLabel).Inc()
2308 2309 2310 2311 2312 2313 2314 2315

		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2316 2317 2318 2319

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2320
		zap.String("role", typeutil.ProxyRole),
2321 2322 2323 2324 2325 2326 2327 2328
		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))
2329

2330
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2331
		metrics.SuccessLabel).Inc()
2332
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2333
	return gibpt.result, nil
2334 2335
}

2336
// GetIndexState get the build-state of index.
2337
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2338
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
2339 2340 2341 2342 2343
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2344 2345 2346 2347 2348

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

2349
	dipt := &getIndexStateTask{
G
godchen 已提交
2350 2351 2352
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
2353 2354
		indexCoord:           node.indexCoord,
		rootCoord:            node.rootCoord,
2355 2356
	}

2357
	method := "GetIndexState"
2358
	tr := timerecord.NewTimeRecorder(method)
2359 2360
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2361 2362 2363
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2364
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2365 2366 2367 2368
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2369 2370 2371 2372 2373 2374

	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2375
			zap.String("role", typeutil.ProxyRole),
2376 2377 2378 2379 2380
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

2381
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2382
			metrics.AbandonLabel).Inc()
2383

G
godchen 已提交
2384
		return &milvuspb.GetIndexStateResponse{
2385
			Status: &commonpb.Status{
2386
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2387 2388 2389 2390 2391
				Reason:    err.Error(),
			},
		}, nil
	}

2392 2393 2394
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2395
		zap.String("role", typeutil.ProxyRole),
2396 2397 2398
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2399 2400 2401 2402
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2403 2404 2405 2406

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2407
			zap.Error(err),
2408
			zap.String("traceID", traceID),
2409
			zap.String("role", typeutil.ProxyRole),
2410 2411 2412
			zap.Int64("MsgID", dipt.ID()),
			zap.Uint64("BeginTs", dipt.BeginTs()),
			zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2413 2414 2415 2416
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
2417
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2418
			metrics.FailLabel).Inc()
2419

G
godchen 已提交
2420
		return &milvuspb.GetIndexStateResponse{
2421
			Status: &commonpb.Status{
2422
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2423 2424 2425 2426 2427
				Reason:    err.Error(),
			},
		}, nil
	}

2428 2429 2430
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2431
		zap.String("role", typeutil.ProxyRole),
2432 2433 2434 2435 2436 2437 2438 2439
		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))

2440
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2441
		metrics.SuccessLabel).Inc()
2442
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2443 2444 2445
	return dipt.result, nil
}

2446
// Insert insert records into collection.
C
Cai Yudong 已提交
2447
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
X
Xiangyu Wang 已提交
2448 2449 2450 2451 2452 2453
	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))

2454 2455 2456 2457 2458
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2459 2460
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
2461
	receiveSize := proto.Size(request)
2462 2463
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Add(float64(receiveSize))
D
dragondriver 已提交
2464

2465
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
2466
	it := &insertTask{
2467 2468
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2469
		// req:       request,
2470 2471 2472 2473
		BaseInsertTask: BaseInsertTask{
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2474
			InsertRequest: internalpb.InsertRequest{
2475
				Base: &commonpb.MsgBase{
X
xige-16 已提交
2476 2477
					MsgType:  commonpb.MsgType_Insert,
					MsgID:    0,
X
Xiaofan 已提交
2478
					SourceID: Params.ProxyCfg.GetNodeID(),
2479 2480 2481
				},
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2482 2483 2484
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
				Version:        internalpb.InsertDataVersion_ColumnBased,
2485
				// RowData: transfer column based request to this
2486 2487
			},
		},
2488
		idAllocator:   node.rowIDAllocator,
2489 2490 2491
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2492
	}
2493 2494

	if len(it.PartitionName) <= 0 {
2495
		it.PartitionName = Params.CommonCfg.DefaultPartitionName
2496 2497
	}

X
Xiangyu Wang 已提交
2498
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2499
		numRows := request.NumRows
2500 2501 2502 2503
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2504

X
Xiangyu Wang 已提交
2505 2506 2507 2508 2509 2510 2511
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2512 2513
	}

X
Xiangyu Wang 已提交
2514
	log.Debug("Enqueue insert request in Proxy",
2515
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2516 2517 2518 2519 2520
		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)),
2521 2522
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))
D
dragondriver 已提交
2523

X
Xiangyu Wang 已提交
2524 2525
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Debug("Failed to enqueue insert task: " + err.Error())
2526
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2527
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2528
		return constructFailedResponse(err), nil
2529
	}
D
dragondriver 已提交
2530

X
Xiangyu Wang 已提交
2531
	log.Debug("Detail of insert request in Proxy",
2532
		zap.String("role", typeutil.ProxyRole),
X
Xiangyu Wang 已提交
2533
		zap.Int64("msgID", it.Base.MsgID),
D
dragondriver 已提交
2534 2535 2536 2537 2538
		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 已提交
2539 2540 2541 2542 2543
		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))
2544
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2545
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2546 2547 2548 2549 2550
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2551
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
			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 已提交
2563
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2564

2565
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2566
		metrics.SuccessLabel).Inc()
2567 2568
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(successCnt))
2569
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2570
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
2571 2572 2573
	return it.result, nil
}

2574
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2575
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
2576 2577 2578
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Delete")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2579 2580
	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))
2581

2582
	receiveSize := proto.Size(request)
2583 2584
	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Add(float64(receiveSize))
2585

G
groot 已提交
2586 2587 2588 2589 2590 2591
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2592 2593 2594
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

2595
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2596
		metrics.TotalLabel).Inc()
2597
	dt := &deleteTask{
X
xige-16 已提交
2598 2599 2600
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
G
godchen 已提交
2601
		BaseDeleteTask: BaseDeleteTask{
G
godchen 已提交
2602 2603 2604
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2605 2606 2607 2608 2609
			DeleteRequest: internalpb.DeleteRequest{
				Base: &commonpb.MsgBase{
					MsgType: commonpb.MsgType_Delete,
					MsgID:   0,
				},
X
xige-16 已提交
2610
				DbName:         request.DbName,
G
godchen 已提交
2611 2612 2613
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2614 2615 2616 2617
			},
		},
		chMgr:    node.chMgr,
		chTicker: node.chTicker,
G
groot 已提交
2618 2619
	}

2620
	log.Debug("Enqueue delete request in Proxy",
2621
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2622 2623 2624 2625
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2626 2627 2628 2629

	// 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))
2630 2631
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
2632

G
groot 已提交
2633 2634 2635 2636 2637 2638 2639 2640
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2641
	log.Debug("Detail of delete request in Proxy",
2642
		zap.String("role", typeutil.ProxyRole),
G
groot 已提交
2643 2644 2645 2646 2647
		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),
2648 2649
		zap.String("expr", request.Expr),
		zap.String("traceID", traceID))
G
groot 已提交
2650

2651 2652
	if err := dt.WaitToFinish(); err != nil {
		log.Error("Failed to execute delete task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
2653
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2654
			metrics.FailLabel).Inc()
G
groot 已提交
2655 2656 2657 2658 2659 2660 2661 2662
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2663
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2664
		metrics.SuccessLabel).Inc()
2665
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2666
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2667 2668 2669
	return dt.result, nil
}

2670
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2671
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2672 2673 2674 2675 2676
	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()))

2677 2678 2679 2680 2681
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2682 2683
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
2684
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2685
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2686

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

2690
	qt := &searchTask{
S
sunby 已提交
2691
		ctx:       ctx,
2692
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2693
		SearchRequest: &internalpb.SearchRequest{
2694
			Base: &commonpb.MsgBase{
2695
				MsgType:  commonpb.MsgType_Search,
X
Xiaofan 已提交
2696
				SourceID: Params.ProxyCfg.GetNodeID(),
2697
			},
2698
			ReqID: Params.ProxyCfg.GetNodeID(),
2699
		},
2700 2701 2702 2703
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2704 2705
	}

2706 2707 2708
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

Z
Zach 已提交
2709
	log.Ctx(ctx).Info(
2710
		rpcReceived(method),
2711
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2712 2713 2714 2715 2716
		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)),
2717 2718 2719 2720
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2721

2722
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2723
		log.Ctx(ctx).Warn(
2724
			rpcFailedToEnqueue(method),
D
dragondriver 已提交
2725
			zap.Error(err),
2726
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2727 2728 2729 2730 2731 2732
			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),
2733 2734 2735
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2736

2737
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2738
			metrics.AbandonLabel).Inc()
2739

2740 2741
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2742
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2743 2744 2745 2746
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2747
	tr.CtxRecord(ctx, "search request enqueue")
2748

Z
Zach 已提交
2749
	log.Ctx(ctx).Debug(
2750
		rpcEnqueued(method),
2751
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2752
		zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2753 2754 2755 2756 2757
		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),
2758
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2759 2760 2761 2762
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2763

2764
	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2765
		log.Ctx(ctx).Warn(
2766
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2767
			zap.Error(err),
2768
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2769
			zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2770 2771 2772 2773
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
2774
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2775 2776 2777 2778
			zap.Any("OutputFields", request.OutputFields),
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
2779

2780
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2781
			metrics.FailLabel).Inc()
2782

2783 2784
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2785
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2786 2787 2788 2789 2790
				Reason:    err.Error(),
			},
		}, nil
	}

Z
Zach 已提交
2791
	span := tr.CtxRecord(ctx, "wait search result")
2792 2793
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
2794
	tr.CtxRecord(ctx, "wait search result")
Z
Zach 已提交
2795
	log.Ctx(ctx).Debug(
2796
		rpcDone(method),
2797
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2798 2799 2800 2801 2802 2803
		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)),
2804 2805 2806 2807
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2808

2809
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2810 2811
		metrics.SuccessLabel).Inc()
	metrics.ProxySearchVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(qt.result.GetResults().GetNumQueries()))
C
cai.zhang 已提交
2812
	searchDur := tr.ElapseSpan().Milliseconds()
2813
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2814
		metrics.SearchLabel).Observe(float64(searchDur))
2815 2816
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.SearchLabel, request.CollectionName).Observe(float64(searchDur))
2817 2818 2819
	if qt.result != nil {
		sentSize := proto.Size(qt.result)
		metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
2820
		rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
2821
	}
2822 2823 2824
	return qt.result, nil
}

2825
// Flush notify data nodes to persist the data of collection.
2826 2827 2828 2829 2830 2831 2832
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2833
	if !node.checkHealthy() {
2834 2835
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2836
	}
D
dragondriver 已提交
2837 2838 2839 2840 2841

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

2842
	ft := &flushTask{
T
ThreadDao 已提交
2843 2844 2845
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2846
		dataCoord:    node.dataCoord,
2847 2848
	}

D
dragondriver 已提交
2849
	method := "Flush"
2850
	tr := timerecord.NewTimeRecorder(method)
2851
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2852 2853 2854 2855

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2856
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2857 2858
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2859 2860 2861 2862 2863 2864

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

2869
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
2870

2871 2872
		resp.Status.Reason = err.Error()
		return resp, nil
2873 2874
	}

D
dragondriver 已提交
2875 2876 2877
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2878
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2879 2880 2881
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2882 2883
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2884 2885 2886 2887

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2888
			zap.Error(err),
D
dragondriver 已提交
2889
			zap.String("traceID", traceID),
2890
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2891 2892 2893
			zap.Int64("MsgID", ft.ID()),
			zap.Uint64("BeginTs", ft.BeginTs()),
			zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2894 2895 2896
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

2897
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
2898

D
dragondriver 已提交
2899
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2900 2901
		resp.Status.Reason = err.Error()
		return resp, nil
2902 2903
	}

D
dragondriver 已提交
2904 2905 2906
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2907
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2908 2909 2910 2911 2912 2913
		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))

2914 2915
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2916
	return ft.result, nil
2917 2918
}

2919
// Query get the records by primary keys.
C
Cai Yudong 已提交
2920
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2921 2922 2923 2924 2925
	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)

2926 2927 2928 2929 2930
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2931

D
dragondriver 已提交
2932 2933
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Query")
	defer sp.Finish()
2934
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2935

2936
	qt := &queryTask{
2937 2938 2939 2940 2941
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
			Base: &commonpb.MsgBase{
				MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
2942
				SourceID: Params.ProxyCfg.GetNodeID(),
2943
			},
2944
			ReqID: Params.ProxyCfg.GetNodeID(),
2945
		},
2946 2947
		request:          request,
		qc:               node.queryCoord,
2948
		queryShardPolicy: mergeRoundRobinPolicy,
2949
		shardMgr:         node.shardMgr,
2950 2951
	}

D
dragondriver 已提交
2952 2953
	method := "Query"

2954
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2955 2956
		metrics.TotalLabel).Inc()

Z
Zach 已提交
2957
	log.Ctx(ctx).Info(
D
dragondriver 已提交
2958
		rpcReceived(method),
2959
		zap.String("role", typeutil.ProxyRole),
2960 2961
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2962 2963 2964 2965 2966
		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 已提交
2967

D
dragondriver 已提交
2968
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
2969
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
2970 2971 2972
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("role", typeutil.ProxyRole),
2973 2974 2975
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2976

2977 2978
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
2979

2980 2981 2982 2983 2984 2985
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
2986
	}
Z
Zach 已提交
2987
	tr.CtxRecord(ctx, "query request enqueue")
2988

Z
Zach 已提交
2989
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
2990
		rpcEnqueued(method),
2991
		zap.String("role", typeutil.ProxyRole),
2992
		zap.Int64("msgID", qt.ID()),
2993 2994
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2995
		zap.Strings("partitions", request.PartitionNames))
D
dragondriver 已提交
2996 2997

	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2998
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
2999 3000
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
3001
			zap.String("role", typeutil.ProxyRole),
3002
			zap.Int64("msgID", qt.ID()),
3003 3004 3005
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
3006

3007
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3008
			metrics.FailLabel).Inc()
3009

3010 3011 3012 3013 3014 3015 3016
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
3017
	span := tr.CtxRecord(ctx, "wait query result")
3018 3019
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
3020

Z
Zach 已提交
3021
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
3022 3023
		rpcDone(method),
		zap.String("role", typeutil.ProxyRole),
3024
		zap.Int64("msgID", qt.ID()),
3025 3026 3027
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
3028

3029
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3030 3031
		metrics.SuccessLabel).Inc()

3032
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
3033
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
3034 3035
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.QueryLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
3036 3037

	ret := &milvuspb.QueryResults{
3038 3039
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
3040 3041
	}
	sentSize := proto.Size(qt.result)
3042
	rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
3043 3044
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
	return ret, nil
3045
}
3046

3047
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
3048 3049 3050 3051
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3052 3053 3054 3055 3056

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

Y
Yusup 已提交
3057 3058 3059 3060 3061 3062 3063
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
3064
	method := "CreateAlias"
3065
	tr := timerecord.NewTimeRecorder(method)
3066
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085

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

3086
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
3087

Y
Yusup 已提交
3088 3089 3090 3091 3092 3093
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3094 3095 3096
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3097
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3098 3099 3100 3101
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3102 3103
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3104 3105 3106 3107

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3108
			zap.Error(err),
D
dragondriver 已提交
3109
			zap.String("traceID", traceID),
3110
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3111 3112 3113 3114
			zap.Int64("MsgID", cat.ID()),
			zap.Uint64("BeginTs", cat.BeginTs()),
			zap.Uint64("EndTs", cat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3115 3116
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
3117
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
3118 3119 3120 3121 3122 3123 3124

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

D
dragondriver 已提交
3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
	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))

3136 3137
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3138 3139 3140
	return cat.result, nil
}

3141
// DropAlias alter the alias of collection.
Y
Yusup 已提交
3142 3143 3144 3145
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3146 3147 3148 3149 3150

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

Y
Yusup 已提交
3151 3152 3153 3154 3155 3156 3157
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
3158
	method := "DropAlias"
3159
	tr := timerecord.NewTimeRecorder(method)
3160
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176

	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))
3177
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3178

Y
Yusup 已提交
3179 3180 3181 3182 3183 3184
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3185 3186 3187
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3188
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3189 3190 3191 3192
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3193
		zap.String("alias", request.Alias))
D
dragondriver 已提交
3194 3195 3196 3197

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3198
			zap.Error(err),
D
dragondriver 已提交
3199
			zap.String("traceID", traceID),
3200
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3201 3202 3203 3204
			zap.Int64("MsgID", dat.ID()),
			zap.Uint64("BeginTs", dat.BeginTs()),
			zap.Uint64("EndTs", dat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3205 3206
			zap.String("alias", request.Alias))

3207
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3208

Y
Yusup 已提交
3209 3210 3211 3212 3213 3214
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
	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))

3225 3226
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3227 3228 3229
	return dat.result, nil
}

3230
// AlterAlias alter alias of collection.
Y
Yusup 已提交
3231 3232 3233 3234
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3235 3236 3237 3238 3239

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

Y
Yusup 已提交
3240 3241 3242 3243 3244 3245 3246
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
3247
	method := "AlterAlias"
3248
	tr := timerecord.NewTimeRecorder(method)
3249
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267

	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))
3268
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3269

Y
Yusup 已提交
3270 3271 3272 3273 3274 3275
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3276 3277 3278
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3279
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3280 3281 3282 3283
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3284 3285
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3286 3287 3288 3289

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3290
			zap.Error(err),
D
dragondriver 已提交
3291
			zap.String("traceID", traceID),
3292
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3293 3294 3295 3296
			zap.Int64("MsgID", aat.ID()),
			zap.Uint64("BeginTs", aat.BeginTs()),
			zap.Uint64("EndTs", aat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3297 3298 3299
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

3300
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3301

Y
Yusup 已提交
3302 3303 3304 3305 3306 3307
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
	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))

3319 3320
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3321 3322 3323
	return aat.result, nil
}

3324
// CalcDistance calculates the distances between vectors.
3325
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
3326 3327 3328 3329 3330
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
3331

3332 3333 3334 3335
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CalcDistance")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

3336 3337
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
3338

3339 3340 3341 3342 3343
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
3344 3345
		}

3346
		qt := &queryTask{
3347 3348 3349 3350 3351
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
				Base: &commonpb.MsgBase{
					MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
3352
					SourceID: Params.ProxyCfg.GetNodeID(),
3353
				},
3354
				ReqID: Params.ProxyCfg.GetNodeID(),
3355
			},
3356 3357 3358 3359
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

3360
			queryShardPolicy: mergeRoundRobinPolicy,
3361
			shardMgr:         node.shardMgr,
3362 3363
		}

G
groot 已提交
3364 3365 3366 3367 3368 3369
		items := []zapcore.Field{
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
			zap.Any("OutputFields", queryRequest.OutputFields),
		}

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

3374 3375 3376 3377 3378
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3379
			}, err
3380
		}
3381

G
groot 已提交
3382
		log.Debug("CalcDistance queryTask enqueued", items...)
3383 3384 3385

		err = qt.WaitToFinish()
		if err != nil {
G
groot 已提交
3386
			log.Error("CalcDistance queryTask failed to WaitToFinish", append(items, zap.Error(err))...)
3387 3388 3389 3390 3391 3392

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3393
			}, err
3394
		}
3395

G
groot 已提交
3396
		log.Debug("CalcDistance queryTask Done", items...)
3397 3398

		return &milvuspb.QueryResults{
3399 3400
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
3401 3402 3403
		}, nil
	}

G
groot 已提交
3404 3405 3406 3407
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
		traceID:   traceID,
		queryFunc: query,
3408 3409
	}

G
groot 已提交
3410
	return task.Execute(ctx, request)
3411 3412
}

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

3418
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3419
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
D
dragondriver 已提交
3420
	log.Debug("GetPersistentSegmentInfo",
3421
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3422 3423 3424
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3425
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3426
		Status: &commonpb.Status{
3427
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3428 3429
		},
	}
3430 3431 3432 3433
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3434 3435
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
3436
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3437
		metrics.TotalLabel).Inc()
3438 3439 3440

	// list segments
	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
X
XuanYang-cn 已提交
3441
	if err != nil {
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		resp.Status.Reason = fmt.Errorf("getCollectionID failed, err:%w", err).Error()
		return resp, nil
	}

	getSegmentsByStatesResponse, err := node.dataCoord.GetSegmentsByStates(ctx, &datapb.GetSegmentsByStatesRequest{
		CollectionID: collectionID,
		// -1 means list all partition segemnts
		PartitionID: -1,
		States:      []commonpb.SegmentState{commonpb.SegmentState_Flushing, commonpb.SegmentState_Flushed, commonpb.SegmentState_Sealed},
	})
	if err != nil {
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3455
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3456 3457
		return resp, nil
	}
3458 3459

	// get Segment info
3460
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
X
XuanYang-cn 已提交
3461
		Base: &commonpb.MsgBase{
3462
			MsgType:   commonpb.MsgType_SegmentInfo,
X
XuanYang-cn 已提交
3463 3464
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3465
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3466
		},
3467
		SegmentIDs: getSegmentsByStatesResponse.Segments,
X
XuanYang-cn 已提交
3468 3469
	})
	if err != nil {
3470 3471 3472
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
		log.Warn("GetPersistentSegmentInfo fail", zap.Error(err))
3473
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3474 3475
		return resp, nil
	}
3476
	log.Debug("GetPersistentSegmentInfo ", zap.Int("len(infos)", len(infoResp.Infos)), zap.Any("status", infoResp.Status))
3477
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
3478 3479
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
X
XuanYang-cn 已提交
3480 3481 3482 3483 3484 3485
		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 已提交
3486
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3487 3488
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3489
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3490 3491 3492
			State:        info.State,
		}
	}
3493
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3494
		metrics.SuccessLabel).Inc()
3495
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3496
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3497 3498 3499 3500
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3501
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3502
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
D
dragondriver 已提交
3503
	log.Debug("GetQuerySegmentInfo",
3504
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3505 3506 3507
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3508
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3509
		Status: &commonpb.Status{
3510
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3511 3512
		},
	}
3513 3514 3515 3516
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3517

3518 3519 3520 3521 3522
	method := "GetQuerySegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()

3523 3524
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
3525
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3526 3527 3528
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3529
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
Z
zhenshan.cao 已提交
3530
		Base: &commonpb.MsgBase{
3531
			MsgType:   commonpb.MsgType_SegmentInfo,
Z
zhenshan.cao 已提交
3532 3533
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3534
			SourceID:  Params.ProxyCfg.GetNodeID(),
Z
zhenshan.cao 已提交
3535
		},
3536
		CollectionID: collID,
Z
zhenshan.cao 已提交
3537 3538
	})
	if err != nil {
3539 3540
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		log.Error("Failed to get segment info from QueryCoord", zap.Error(err))
Z
zhenshan.cao 已提交
3541 3542 3543
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3544
	log.Debug("GetQuerySegmentInfo ", zap.Any("infos", infoResp.Infos), zap.Any("status", infoResp.Status))
3545
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
3546
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3547
		log.Error("Failed to get segment info from QueryCoord", zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560
		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 已提交
3561
			State:        info.SegmentState,
3562
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3563 3564
		}
	}
3565 3566 3567

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3568
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3569 3570 3571 3572
	resp.Infos = queryInfos
	return resp, nil
}

J
jingkl 已提交
3573
// Dummy handles dummy request
C
Cai Yudong 已提交
3574
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
	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
	}

3586 3587
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3588
		if err != nil {
3589
			log.Debug("Failed to parse dummy query request")
3590 3591 3592
			return failedResponse, nil
		}

3593
		request := &milvuspb.QueryRequest{
3594 3595 3596
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3597
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3598 3599
		}

3600
		_, err = node.Query(ctx, request)
3601
		if err != nil {
3602
			log.Debug("Failed to execute dummy query")
3603 3604
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3605 3606 3607 3608 3609 3610

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

3611 3612
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3613 3614
}

J
jingkl 已提交
3615
// RegisterLink registers a link
C
Cai Yudong 已提交
3616
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
3617
	code := node.stateCode.Load().(commonpb.StateCode)
D
dragondriver 已提交
3618
	log.Debug("RegisterLink",
3619
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3620
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3621

3622
	if code != commonpb.StateCode_Healthy {
3623 3624 3625
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3626
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3627
				Reason:    "proxy not healthy",
3628 3629 3630
			},
		}, nil
	}
X
Xiaofan 已提交
3631
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Inc()
3632 3633 3634
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3635
			ErrorCode: commonpb.ErrorCode_Success,
3636
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3637 3638 3639
		},
	}, nil
}
3640

3641
// GetMetrics gets the metrics of proxy
3642 3643 3644
// 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 已提交
3645
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3646 3647 3648 3649
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
X
Xiaofan 已提交
3650
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3651
			zap.String("req", req.Request),
X
Xiaofan 已提交
3652
			zap.Error(errProxyIsUnhealthy(Params.ProxyCfg.GetNodeID())))
3653 3654 3655 3656

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
Xiaofan 已提交
3657
				Reason:    msgProxyIsUnhealthy(Params.ProxyCfg.GetNodeID()),
3658 3659 3660 3661 3662 3663 3664 3665
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
X
Xiaofan 已提交
3666
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681
			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 已提交
3682 3683
	req.Base = &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
3684
		MsgID:     0,
D
dragondriver 已提交
3685
		Timestamp: 0,
X
Xiaofan 已提交
3686
		SourceID:  Params.ProxyCfg.GetNodeID(),
D
dragondriver 已提交
3687 3688
	}

3689
	if metricType == metricsinfo.SystemInfoMetrics {
3690 3691 3692 3693 3694 3695 3696
		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))

3697
		metrics, err := getSystemInfoMetrics(ctx, req, node)
3698 3699

		log.Debug("Proxy.GetMetrics",
X
Xiaofan 已提交
3700
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3701 3702 3703 3704 3705
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3706 3707
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3708
		return metrics, nil
3709 3710 3711
	}

	log.Debug("Proxy.GetMetrics failed, request metric type is not implemented yet",
X
Xiaofan 已提交
3712
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724
		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
}

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

	req.Base = &commonpb.MsgBase{
3765 3766 3767 3768
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     0,
		Timestamp: 0,
		SourceID:  Params.ProxyCfg.GetNodeID(),
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 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808
	}

	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 已提交
3809 3810 3811
// 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 已提交
3812
		zap.Int64("proxy_id", Params.ProxyCfg.GetNodeID()),
B
bigsheeper 已提交
3813 3814 3815 3816 3817 3818 3819 3820 3821
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3822 3823 3824 3825 3826 3827 3828

	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 已提交
3829 3830 3831 3832 3833
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_LoadBalanceSegments,
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3834
			SourceID:  Params.ProxyCfg.GetNodeID(),
B
bigsheeper 已提交
3835 3836 3837
		},
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3838
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3839
		SealedSegmentIDs: req.SealedSegmentIDs,
3840
		CollectionID:     collectionID,
B
bigsheeper 已提交
3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
	})
	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
}

3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
// 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
	}

	req.Base = &commonpb.MsgBase{
		MsgType:  commonpb.MsgType_GetReplicas,
		SourceID: Params.ProxyCfg.GetNodeID(),
	}

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

J
jingkl 已提交
3883
//GetCompactionState gets the compaction state of multiple segments
3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896
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
}

3897
// ManualCompaction invokes compaction on specified collection
3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
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
}

3911
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924
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 已提交
3925 3926 3927
// 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))
3928
	var err error
B
Bingyi Sun 已提交
3929 3930 3931 3932 3933 3934 3935
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Info("unable to get flush state because of closed server")
		return resp, nil
	}

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

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

3951 3952 3953
func (node *Proxy) checkHealthyAndReturnCode() (commonpb.StateCode, bool) {
	code := node.stateCode.Load().(commonpb.StateCode)
	return code, code == commonpb.StateCode_Healthy
3954 3955
}

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

// 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) {
3966 3967 3968
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
		zap.Bool("row-based", req.GetRowBased()))
3969 3970 3971 3972 3973 3974
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3975 3976 3977 3978
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3979 3980 3981 3982 3983 3984

	method := "Import"
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()

3985
	// Call rootCoord to finish import.
3986 3987
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
3988
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3989 3990 3991 3992 3993
		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
	}
3994 3995 3996

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3997
	return respFromRC, nil
G
groot 已提交
3998 3999
}

4000
// GetImportState checks import task state from RootCoord.
G
groot 已提交
4001 4002 4003 4004 4005 4006 4007
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
	}
4008 4009 4010 4011
	method := "GetImportState"
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
G
groot 已提交
4012 4013

	resp, err := node.rootCoord.GetImportState(ctx, req)
4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025
	if err != nil {
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		log.Error("failed to execute get import state", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}

	log.Info("successfully received get import state response", zap.Int64("taskID", req.GetTask()), zap.Any("resp", resp), zap.Error(err))
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return resp, nil
G
groot 已提交
4026 4027 4028 4029 4030 4031 4032 4033 4034 4035
}

// 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
	}
4036 4037 4038 4039
	method := "ListImportTasks"
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
G
groot 已提交
4040
	resp, err := node.rootCoord.ListImportTasks(ctx, req)
4041 4042 4043 4044 4045
	if err != nil {
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		log.Error("failed to execute list import tasks", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
X
XuanYang-cn 已提交
4046 4047 4048
		return resp, nil
	}

4049 4050 4051
	log.Info("successfully received list import tasks response", zap.String("collection", req.CollectionName), zap.Any("tasks", resp.Tasks))
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
X
XuanYang-cn 已提交
4052 4053 4054
	return resp, err
}

4055 4056 4057 4058 4059 4060
// 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))
4061
	if !node.checkHealthy() {
4062
		return unhealthyStatus(), nil
4063
	}
4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084

	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))
4085
	if !node.checkHealthy() {
4086
		return unhealthyStatus(), nil
4087
	}
4088 4089

	credInfo := &internalpb.CredentialInfo{
4090 4091
		Username:       request.Username,
		Sha256Password: request.Password,
4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106
	}
	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) {
4107 4108
	log.Debug("CreateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4109
		return unhealthyStatus(), nil
4110
	}
4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141
	// 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
	}
4142

4143 4144 4145
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
4146
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158
	}
	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 已提交
4159
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
4160 4161
	log.Debug("UpdateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4162
		return unhealthyStatus(), nil
4163
	}
C
codeman 已提交
4164 4165 4166 4167 4168 4169 4170 4171 4172
	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)
4173 4174 4175 4176 4177 4178 4179
	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 已提交
4180 4181
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
4182 4183 4184 4185 4186 4187
		log.Error("illegal password", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
4188 4189

	if !passwordVerify(ctx, req.Username, rawOldPassword, globalMetaCache) {
C
codeman 已提交
4190 4191 4192 4193 4194 4195 4196
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
4197 4198 4199 4200 4201 4202 4203
	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 已提交
4204
	updateCredReq := &internalpb.CredentialInfo{
4205
		Username:          req.Username,
4206
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
4207 4208
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
4209
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220
	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) {
4221 4222
	log.Debug("DeleteCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
4223
		return unhealthyStatus(), nil
4224 4225
	}

4226 4227 4228 4229 4230 4231
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243
	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) {
4244 4245
	log.Debug("ListCredUsers", zap.String("role", typeutil.ProxyRole))
	if !node.checkHealthy() {
4246
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
4247
	}
4248 4249 4250 4251 4252 4253
	rootCoordReq := &milvuspb.ListCredUsersRequest{
		Base: &commonpb.MsgBase{
			MsgType: commonpb.MsgType_ListCredUsernames,
		},
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
	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,
		},
4266
		Usernames: resp.Usernames,
4267 4268
	}, nil
}
4269

4270 4271 4272
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 {
4273
		return errorutil.UnhealthyStatus(code), nil
4274 4275 4276 4277 4278 4279 4280 4281 4282 4283
	}

	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(),
4284
		}, nil
4285 4286 4287 4288 4289 4290 4291 4292
	}

	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(),
4293
		}, nil
4294 4295
	}
	return result, nil
4296 4297
}

4298 4299 4300
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 {
4301
		return errorutil.UnhealthyStatus(code), nil
4302 4303 4304 4305 4306
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4307
		}, nil
4308
	}
4309 4310 4311 4312 4313
	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,
4314
		}, nil
4315
	}
4316 4317 4318 4319 4320 4321
	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(),
4322
		}, nil
4323 4324
	}
	return result, nil
4325 4326
}

4327 4328 4329
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 {
4330
		return errorutil.UnhealthyStatus(code), nil
4331 4332 4333 4334 4335
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4336
		}, nil
4337 4338 4339 4340 4341
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4342
		}, nil
4343 4344 4345 4346 4347 4348 4349 4350
	}

	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(),
4351
		}, nil
4352 4353
	}
	return result, nil
4354 4355
}

4356 4357 4358
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 {
4359
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4360 4361 4362 4363 4364 4365 4366 4367 4368
	}

	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(),
				},
4369
			}, nil
4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380
		}
	}

	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(),
			},
4381
		}, nil
4382 4383
	}
	return result, nil
4384 4385
}

4386 4387 4388
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 {
4389
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4390 4391 4392 4393 4394 4395 4396 4397 4398
	}

	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(),
				},
4399
			}, nil
4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410
		}
	}

	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(),
			},
4411
		}, nil
4412 4413
	}
	return result, nil
4414 4415
}

4416 4417 4418 4419 4420 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
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
4446 4447
}

4448 4449 4450
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 {
4451
		return errorutil.UnhealthyStatus(code), nil
4452 4453 4454 4455 4456
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4457
		}, nil
4458 4459 4460 4461 4462 4463
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4464
		}, nil
4465 4466 4467 4468 4469 4470 4471 4472
	}
	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(),
4473
		}, nil
4474 4475
	}
	return result, nil
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 4501 4502 4503 4504 4505 4506
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 {
4507
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4508 4509 4510 4511 4512 4513 4514 4515
	}

	if err := node.validGrantParams(req); err != nil {
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_IllegalArgument,
				Reason:    err.Error(),
			},
4516
		}, nil
4517 4518 4519 4520 4521 4522 4523 4524 4525 4526
	}

	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(),
			},
4527
		}, nil
4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555
	}
	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
4556
}
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577

// 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
}
4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635

func (node *Proxy) CheckHealth(ctx context.Context, request *milvuspb.CheckHealthRequest) (*milvuspb.CheckHealthResponse, error) {
	if !node.checkHealthy() {
		reason := errorutil.UnHealthReason("proxy", node.session.ServerID, "proxy is unhealthy")
		return &milvuspb.CheckHealthResponse{IsHealthy: false, Reasons: []string{reason}}, nil
	}

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

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

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

		if !resp.IsHealthy {
			log.Warn("check health fail,", zap.String("role", role))
			errReasons = append(errReasons, resp.Reasons...)
		}
		return nil
	}

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

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

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

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

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

	return &milvuspb.CheckHealthResponse{IsHealthy: true}, nil
}