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

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

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

26
	"github.com/cockroachdb/errors"
J
jaime 已提交
27
	"github.com/golang/protobuf/proto"
28
	"github.com/samber/lo"
E
Enwei Jiao 已提交
29
	"go.opentelemetry.io/otel"
J
jaime 已提交
30
	"go.uber.org/zap"
31
	"golang.org/x/sync/errgroup"
32

S
SimFG 已提交
33
	"github.com/milvus-io/milvus-proto/go-api/commonpb"
Y
yihao.dai 已提交
34
	"github.com/milvus-io/milvus-proto/go-api/federpb"
S
SimFG 已提交
35
	"github.com/milvus-io/milvus-proto/go-api/milvuspb"
36
	"github.com/milvus-io/milvus-proto/go-api/msgpb"
S
smellthemoon 已提交
37
	"github.com/milvus-io/milvus-proto/go-api/schemapb"
38
	"github.com/milvus-io/milvus/internal/common"
X
Xiangyu Wang 已提交
39
	"github.com/milvus-io/milvus/internal/log"
40
	"github.com/milvus-io/milvus/internal/metrics"
J
jaime 已提交
41
	"github.com/milvus-io/milvus/internal/mq/msgstream"
X
Xiangyu Wang 已提交
42 43 44 45
	"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"
46
	"github.com/milvus-io/milvus/internal/util"
47
	"github.com/milvus-io/milvus/internal/util/commonpbutil"
48
	"github.com/milvus-io/milvus/internal/util/crypto"
49
	"github.com/milvus-io/milvus/internal/util/errorutil"
50
	"github.com/milvus-io/milvus/internal/util/importutil"
51
	"github.com/milvus-io/milvus/internal/util/logutil"
S
smellthemoon 已提交
52
	"github.com/milvus-io/milvus/internal/util/merr"
53
	"github.com/milvus-io/milvus/internal/util/metricsinfo"
E
Enwei Jiao 已提交
54
	"github.com/milvus-io/milvus/internal/util/paramtable"
55
	"github.com/milvus-io/milvus/internal/util/ratelimitutil"
56
	"github.com/milvus-io/milvus/internal/util/timerecord"
Y
yihao.dai 已提交
57
	"github.com/milvus-io/milvus/internal/util/tsoutil"
X
Xiangyu Wang 已提交
58
	"github.com/milvus-io/milvus/internal/util/typeutil"
59 60
)

61 62
const moduleName = "Proxy"

63
// UpdateStateCode updates the state code of Proxy.
64
func (node *Proxy) UpdateStateCode(code commonpb.StateCode) {
65
	node.stateCode.Store(code)
Z
zhenshan.cao 已提交
66 67
}

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

C
cxytz01 已提交
98
// GetStatisticsChannel gets statistics channel of Proxy.
C
Cai Yudong 已提交
99
func (node *Proxy) GetStatisticsChannel(ctx context.Context) (*milvuspb.StringResponse, error) {
G
godchen 已提交
100 101 102 103 104 105 106 107 108
	return &milvuspb.StringResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
		Value: "",
	}, nil
}

109
// InvalidateCollectionMetaCache invalidate the meta cache of specific collection.
C
Cai Yudong 已提交
110
func (node *Proxy) InvalidateCollectionMetaCache(ctx context.Context, request *proxypb.InvalidateCollMetaCacheRequest) (*commonpb.Status, error) {
111 112 113
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
114
	ctx = logutil.WithModule(ctx, moduleName)
E
Enwei Jiao 已提交
115 116 117

	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-InvalidateCollectionMetaCache")
	defer sp.End()
118
	log := log.Ctx(ctx).With(
119
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
120
		zap.String("db", request.DbName),
121 122
		zap.String("collectionName", request.CollectionName),
		zap.Int64("collectionID", request.CollectionID))
D
dragondriver 已提交
123

124 125
	log.Info("received request to invalidate collection meta cache")

126
	collectionName := request.CollectionName
127
	collectionID := request.CollectionID
X
Xiaofan 已提交
128 129

	var aliasName []string
N
neza2017 已提交
130
	if globalMetaCache != nil {
131 132 133 134
		if collectionName != "" {
			globalMetaCache.RemoveCollection(ctx, collectionName) // no need to return error, though collection may be not cached
		}
		if request.CollectionID != UniqueID(0) {
X
Xiaofan 已提交
135
			aliasName = globalMetaCache.RemoveCollectionsByID(ctx, collectionID)
136
		}
N
neza2017 已提交
137
	}
138 139
	if request.GetBase().GetMsgType() == commonpb.MsgType_DropCollection {
		// no need to handle error, since this Proxy may not create dml stream for the collection.
140 141
		node.chMgr.removeDMLStream(request.GetCollectionID())
		// clean up collection level metrics
E
Enwei Jiao 已提交
142
		metrics.CleanupCollectionMetrics(paramtable.GetNodeID(), collectionName)
X
Xiaofan 已提交
143
		for _, alias := range aliasName {
E
Enwei Jiao 已提交
144
			metrics.CleanupCollectionMetrics(paramtable.GetNodeID(), alias)
X
Xiaofan 已提交
145
		}
146
	}
147
	log.Info("complete to invalidate collection meta cache")
D
dragondriver 已提交
148

149
	return &commonpb.Status{
150
		ErrorCode: commonpb.ErrorCode_Success,
151 152
		Reason:    "",
	}, nil
153 154
}

155
// CreateCollection create a collection by the schema.
156
// TODO(dragondriver): add more detailed ut for ConsistencyLevel, should we support multiple consistency level in Proxy?
C
Cai Yudong 已提交
157
func (node *Proxy) CreateCollection(ctx context.Context, request *milvuspb.CreateCollectionRequest) (*commonpb.Status, error) {
158 159 160
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
161

E
Enwei Jiao 已提交
162 163
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateCollection")
	defer sp.End()
164 165 166
	method := "CreateCollection"
	tr := timerecord.NewTimeRecorder(method)

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

169
	cct := &createCollectionTask{
S
sunby 已提交
170
		ctx:                     ctx,
171 172
		Condition:               NewTaskCondition(ctx),
		CreateCollectionRequest: request,
173
		rootCoord:               node.rootCoord,
174 175
	}

176 177 178
	// avoid data race
	lenOfSchema := len(request.Schema)

179
	log := log.Ctx(ctx).With(
180
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
181 182
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
183
		zap.Int("len(schema)", lenOfSchema),
184 185
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
186

187 188
	log.Debug(rpcReceived(method))

189 190 191
	if err := node.sched.ddQueue.Enqueue(cct); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
192
			zap.Error(err))
193

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

201 202
	log.Debug(
		rpcEnqueued(method),
203 204
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
205
		zap.Uint64("timestamp", request.Base.Timestamp))
206

207 208 209
	if err := cct.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
210
			zap.Error(err),
211
			zap.Uint64("BeginTs", cct.BeginTs()),
212
			zap.Uint64("EndTs", cct.EndTs()))
D
dragondriver 已提交
213

E
Enwei Jiao 已提交
214
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
215
		return &commonpb.Status{
216
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
217 218 219 220
			Reason:    err.Error(),
		}, nil
	}

221 222
	log.Debug(
		rpcDone(method),
223
		zap.Uint64("BeginTs", cct.BeginTs()),
224
		zap.Uint64("EndTs", cct.EndTs()))
225

E
Enwei Jiao 已提交
226 227
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
228 229 230
	return cct.result, nil
}

231
// DropCollection drop a collection.
C
Cai Yudong 已提交
232
func (node *Proxy) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
233 234 235
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
236

E
Enwei Jiao 已提交
237 238
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropCollection")
	defer sp.End()
239 240
	method := "DropCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
241
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
242

243
	dct := &dropCollectionTask{
S
sunby 已提交
244
		ctx:                   ctx,
245 246
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
247
		rootCoord:             node.rootCoord,
248
		chMgr:                 node.chMgr,
S
sunby 已提交
249
		chTicker:              node.chTicker,
250 251
	}

252
	log := log.Ctx(ctx).With(
253
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
254 255
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
256

257 258
	log.Debug("DropCollection received")

259 260
	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DropCollection failed to enqueue",
261
			zap.Error(err))
262

E
Enwei Jiao 已提交
263
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
264
		return &commonpb.Status{
265
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
266 267 268 269
			Reason:    err.Error(),
		}, nil
	}

270 271
	log.Debug("DropCollection enqueued",
		zap.Uint64("BeginTs", dct.BeginTs()),
272
		zap.Uint64("EndTs", dct.EndTs()))
273 274 275

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DropCollection failed to WaitToFinish",
D
dragondriver 已提交
276
			zap.Error(err),
277
			zap.Uint64("BeginTs", dct.BeginTs()),
278
			zap.Uint64("EndTs", dct.EndTs()))
D
dragondriver 已提交
279

E
Enwei Jiao 已提交
280
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
281
		return &commonpb.Status{
282
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
283 284 285 286
			Reason:    err.Error(),
		}, nil
	}

287 288
	log.Debug("DropCollection done",
		zap.Uint64("BeginTs", dct.BeginTs()),
289
		zap.Uint64("EndTs", dct.EndTs()))
290

E
Enwei Jiao 已提交
291 292
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
293 294 295
	return dct.result, nil
}

296
// HasCollection check if the specific collection exists in Milvus.
C
Cai Yudong 已提交
297
func (node *Proxy) HasCollection(ctx context.Context, request *milvuspb.HasCollectionRequest) (*milvuspb.BoolResponse, error) {
298 299 300 301 302
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
303

E
Enwei Jiao 已提交
304 305
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-HasCollection")
	defer sp.End()
306 307
	method := "HasCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
308
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
309
		metrics.TotalLabel).Inc()
310

311
	log := log.Ctx(ctx).With(
312
		zap.String("role", typeutil.ProxyRole),
313 314 315
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

316 317
	log.Debug("HasCollection received")

318
	hct := &hasCollectionTask{
S
sunby 已提交
319
		ctx:                  ctx,
320 321
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
322
		rootCoord:            node.rootCoord,
323 324
	}

325 326
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
327
			zap.Error(err))
328

E
Enwei Jiao 已提交
329
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
330
			metrics.AbandonLabel).Inc()
331 332
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
333
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
334 335 336 337 338
				Reason:    err.Error(),
			},
		}, nil
	}

339 340
	log.Debug("HasCollection enqueued",
		zap.Uint64("BeginTS", hct.BeginTs()),
341
		zap.Uint64("EndTS", hct.EndTs()))
342 343 344

	if err := hct.WaitToFinish(); err != nil {
		log.Warn("HasCollection failed to WaitToFinish",
D
dragondriver 已提交
345
			zap.Error(err),
346
			zap.Uint64("BeginTS", hct.BeginTs()),
347
			zap.Uint64("EndTS", hct.EndTs()))
D
dragondriver 已提交
348

E
Enwei Jiao 已提交
349
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
350
			metrics.FailLabel).Inc()
351 352
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
353
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
354 355 356 357 358
				Reason:    err.Error(),
			},
		}, nil
	}

359 360
	log.Debug("HasCollection done",
		zap.Uint64("BeginTS", hct.BeginTs()),
361
		zap.Uint64("EndTS", hct.EndTs()))
362

E
Enwei Jiao 已提交
363
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
364
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
365
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
366 367 368
	return hct.result, nil
}

369
// LoadCollection load a collection into query nodes.
C
Cai Yudong 已提交
370
func (node *Proxy) LoadCollection(ctx context.Context, request *milvuspb.LoadCollectionRequest) (*commonpb.Status, error) {
371 372 373
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
374

E
Enwei Jiao 已提交
375 376
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-LoadCollection")
	defer sp.End()
377 378
	method := "LoadCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
379
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
380
		metrics.TotalLabel).Inc()
381
	lct := &loadCollectionTask{
S
sunby 已提交
382
		ctx:                   ctx,
383 384
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
385
		queryCoord:            node.queryCoord,
386
		datacoord:             node.dataCoord,
387 388
	}

389
	log := log.Ctx(ctx).With(
390
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
391
		zap.String("db", request.DbName),
392 393
		zap.String("collection", request.CollectionName),
		zap.Bool("refreshMode", request.Refresh))
394

395 396
	log.Debug("LoadCollection received")

397 398
	if err := node.sched.ddQueue.Enqueue(lct); err != nil {
		log.Warn("LoadCollection failed to enqueue",
399
			zap.Error(err))
400

E
Enwei Jiao 已提交
401
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
402
			metrics.AbandonLabel).Inc()
403
		return &commonpb.Status{
404
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
405 406 407
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
408

409 410
	log.Debug("LoadCollection enqueued",
		zap.Uint64("BeginTS", lct.BeginTs()),
411
		zap.Uint64("EndTS", lct.EndTs()))
412 413 414

	if err := lct.WaitToFinish(); err != nil {
		log.Warn("LoadCollection failed to WaitToFinish",
D
dragondriver 已提交
415
			zap.Error(err),
416
			zap.Uint64("BeginTS", lct.BeginTs()),
417
			zap.Uint64("EndTS", lct.EndTs()))
E
Enwei Jiao 已提交
418
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
419
			metrics.FailLabel).Inc()
420
		return &commonpb.Status{
421
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
422 423 424 425
			Reason:    err.Error(),
		}, nil
	}

426 427
	log.Debug("LoadCollection done",
		zap.Uint64("BeginTS", lct.BeginTs()),
428
		zap.Uint64("EndTS", lct.EndTs()))
429

E
Enwei Jiao 已提交
430
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
431
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
432
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
433
	return lct.result, nil
434 435
}

436
// ReleaseCollection remove the loaded collection from query nodes.
C
Cai Yudong 已提交
437
func (node *Proxy) ReleaseCollection(ctx context.Context, request *milvuspb.ReleaseCollectionRequest) (*commonpb.Status, error) {
438 439 440
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
441

E
Enwei Jiao 已提交
442 443
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ReleaseCollection")
	defer sp.End()
444 445
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
446
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
447
		metrics.TotalLabel).Inc()
448
	rct := &releaseCollectionTask{
S
sunby 已提交
449
		ctx:                      ctx,
450 451
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
452
		queryCoord:               node.queryCoord,
453
		chMgr:                    node.chMgr,
454 455
	}

456
	log := log.Ctx(ctx).With(
457
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
458 459
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
460

461 462
	log.Debug(rpcReceived(method))

463
	if err := node.sched.ddQueue.Enqueue(rct); err != nil {
464 465
		log.Warn(
			rpcFailedToEnqueue(method),
466
			zap.Error(err))
467

E
Enwei Jiao 已提交
468
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
469
			metrics.AbandonLabel).Inc()
470
		return &commonpb.Status{
471
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
472 473 474 475
			Reason:    err.Error(),
		}, nil
	}

476 477
	log.Debug(
		rpcEnqueued(method),
478
		zap.Uint64("BeginTS", rct.BeginTs()),
479
		zap.Uint64("EndTS", rct.EndTs()))
480 481

	if err := rct.WaitToFinish(); err != nil {
482 483
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
484
			zap.Error(err),
485
			zap.Uint64("BeginTS", rct.BeginTs()),
486
			zap.Uint64("EndTS", rct.EndTs()))
D
dragondriver 已提交
487

E
Enwei Jiao 已提交
488
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
489
			metrics.FailLabel).Inc()
490
		return &commonpb.Status{
491
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
492 493 494 495
			Reason:    err.Error(),
		}, nil
	}

496 497
	log.Debug(
		rpcDone(method),
498
		zap.Uint64("BeginTS", rct.BeginTs()),
499
		zap.Uint64("EndTS", rct.EndTs()))
500

E
Enwei Jiao 已提交
501
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
502
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
503
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
504
	return rct.result, nil
505 506
}

507
// DescribeCollection get the meta information of specific collection, such as schema, created timestamp and etc.
C
Cai Yudong 已提交
508
func (node *Proxy) DescribeCollection(ctx context.Context, request *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
509 510 511 512 513
	if !node.checkHealthy() {
		return &milvuspb.DescribeCollectionResponse{
			Status: unhealthyStatus(),
		}, nil
	}
514

E
Enwei Jiao 已提交
515 516
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DescribeCollection")
	defer sp.End()
517 518
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
519
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
520
		metrics.TotalLabel).Inc()
521

522
	dct := &describeCollectionTask{
S
sunby 已提交
523
		ctx:                       ctx,
524 525
		Condition:                 NewTaskCondition(ctx),
		DescribeCollectionRequest: request,
526
		rootCoord:                 node.rootCoord,
527 528
	}

529
	log := log.Ctx(ctx).With(
530
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
531 532
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
533

534 535
	log.Debug("DescribeCollection received")

536 537
	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DescribeCollection failed to enqueue",
538
			zap.Error(err))
539

E
Enwei Jiao 已提交
540
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
541
			metrics.AbandonLabel).Inc()
542 543
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
544
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
545 546 547 548 549
				Reason:    err.Error(),
			},
		}, nil
	}

550 551
	log.Debug("DescribeCollection enqueued",
		zap.Uint64("BeginTS", dct.BeginTs()),
552
		zap.Uint64("EndTS", dct.EndTs()))
553 554 555

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DescribeCollection failed to WaitToFinish",
D
dragondriver 已提交
556
			zap.Error(err),
557
			zap.Uint64("BeginTS", dct.BeginTs()),
558
			zap.Uint64("EndTS", dct.EndTs()))
D
dragondriver 已提交
559

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

563 564
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
565
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
566 567 568 569 570
				Reason:    err.Error(),
			},
		}, nil
	}

571 572
	log.Debug("DescribeCollection done",
		zap.Uint64("BeginTS", dct.BeginTs()),
573
		zap.Uint64("EndTS", dct.EndTs()))
574

E
Enwei Jiao 已提交
575
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
576
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
577
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
578 579 580
	return dct.result, nil
}

581 582 583 584 585 586 587 588 589
// 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
	}

E
Enwei Jiao 已提交
590 591
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetStatistics")
	defer sp.End()
592 593
	method := "GetStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
594
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
595
		metrics.TotalLabel).Inc()
596 597 598 599 600 601 602 603 604 605
	g := &getStatisticsTask{
		request:   request,
		Condition: NewTaskCondition(ctx),
		ctx:       ctx,
		tr:        tr,
		dc:        node.dataCoord,
		qc:        node.queryCoord,
		shardMgr:  node.shardMgr,
	}

606
	log := log.Ctx(ctx).With(
607 608
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
609 610 611 612
		zap.String("collection", request.CollectionName))

	log.Debug(
		rpcReceived(method),
613 614 615 616 617 618 619 620
		zap.Strings("partitions", request.PartitionNames))

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.Strings("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
621
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
			metrics.AbandonLabel).Inc()

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

	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.Strings("partitions", request.PartitionNames))

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
			zap.Strings("partitions", request.PartitionNames))

E
Enwei Jiao 已提交
646
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
647 648 649 650 651 652 653 654 655 656 657 658 659
			metrics.FailLabel).Inc()

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

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", g.BeginTs()),
660
		zap.Uint64("EndTS", g.EndTs()))
661

E
Enwei Jiao 已提交
662
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
663
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
664
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
665 666 667
	return g.result, nil
}

668
// GetCollectionStatistics get the collection statistics, such as `num_rows`.
C
Cai Yudong 已提交
669
func (node *Proxy) GetCollectionStatistics(ctx context.Context, request *milvuspb.GetCollectionStatisticsRequest) (*milvuspb.GetCollectionStatisticsResponse, error) {
670 671 672 673 674
	if !node.checkHealthy() {
		return &milvuspb.GetCollectionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
675

E
Enwei Jiao 已提交
676 677
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetCollectionStatistics")
	defer sp.End()
678 679
	method := "GetCollectionStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
680
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
681
		metrics.TotalLabel).Inc()
682
	g := &getCollectionStatisticsTask{
G
godchen 已提交
683 684 685
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
686
		dataCoord:                      node.dataCoord,
687 688
	}

689
	log := log.Ctx(ctx).With(
690
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
691 692
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
693

694 695
	log.Debug(rpcReceived(method))

696
	if err := node.sched.ddQueue.Enqueue(g); err != nil {
697 698
		log.Warn(
			rpcFailedToEnqueue(method),
699
			zap.Error(err))
700

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

G
godchen 已提交
704
		return &milvuspb.GetCollectionStatisticsResponse{
705
			Status: &commonpb.Status{
706
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
707 708 709 710 711
				Reason:    err.Error(),
			},
		}, nil
	}

712 713
	log.Debug(
		rpcEnqueued(method),
714
		zap.Uint64("BeginTS", g.BeginTs()),
715
		zap.Uint64("EndTS", g.EndTs()))
716 717

	if err := g.WaitToFinish(); err != nil {
718 719
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
720
			zap.Error(err),
721
			zap.Uint64("BeginTS", g.BeginTs()),
722
			zap.Uint64("EndTS", g.EndTs()))
D
dragondriver 已提交
723

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

G
godchen 已提交
727
		return &milvuspb.GetCollectionStatisticsResponse{
728
			Status: &commonpb.Status{
729
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
730 731 732 733 734
				Reason:    err.Error(),
			},
		}, nil
	}

735 736
	log.Debug(
		rpcDone(method),
737
		zap.Uint64("BeginTS", g.BeginTs()),
738
		zap.Uint64("EndTS", g.EndTs()))
739

E
Enwei Jiao 已提交
740
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
741
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
742
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
743
	return g.result, nil
744 745
}

746
// ShowCollections list all collections in Milvus.
C
Cai Yudong 已提交
747
func (node *Proxy) ShowCollections(ctx context.Context, request *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
748 749 750 751 752
	if !node.checkHealthy() {
		return &milvuspb.ShowCollectionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
E
Enwei Jiao 已提交
753 754
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ShowCollections")
	defer sp.End()
755 756
	method := "ShowCollections"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
757
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
758

759
	sct := &showCollectionsTask{
G
godchen 已提交
760 761 762
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
763
		queryCoord:             node.queryCoord,
764
		rootCoord:              node.rootCoord,
765 766
	}

767
	log := log.Ctx(ctx).With(
768
		zap.String("role", typeutil.ProxyRole),
769 770
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
771 772 773 774
		zap.String("ShowType", request.Type.String()))

	log.Debug("ShowCollections received",
		zap.Any("CollectionNames", request.CollectionNames))
775

776
	err := node.sched.ddQueue.Enqueue(sct)
777
	if err != nil {
778 779
		log.Warn("ShowCollections failed to enqueue",
			zap.Error(err),
780
			zap.Any("CollectionNames", request.CollectionNames))
781

E
Enwei Jiao 已提交
782
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
G
godchen 已提交
783
		return &milvuspb.ShowCollectionsResponse{
784
			Status: &commonpb.Status{
785
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
786 787 788 789 790
				Reason:    err.Error(),
			},
		}, nil
	}

791
	log.Debug("ShowCollections enqueued",
792
		zap.Any("CollectionNames", request.CollectionNames))
D
dragondriver 已提交
793

794 795
	err = sct.WaitToFinish()
	if err != nil {
796 797
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
798
			zap.Any("CollectionNames", request.CollectionNames))
799

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

G
godchen 已提交
802
		return &milvuspb.ShowCollectionsResponse{
803
			Status: &commonpb.Status{
804
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
805 806 807 808 809
				Reason:    err.Error(),
			},
		}, nil
	}

810
	log.Debug("ShowCollections Done",
811 812
		zap.Int("len(CollectionNames)", len(request.CollectionNames)),
		zap.Int("num_collections", len(sct.result.CollectionNames)))
813

E
Enwei Jiao 已提交
814 815
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
816 817 818
	return sct.result, nil
}

J
jaime 已提交
819 820 821 822 823
func (node *Proxy) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

E
Enwei Jiao 已提交
824 825
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-AlterCollection")
	defer sp.End()
J
jaime 已提交
826 827 828
	method := "AlterCollection"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
829
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
J
jaime 已提交
830 831 832 833 834 835 836 837

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

838
	log := log.Ctx(ctx).With(
J
jaime 已提交
839 840 841 842
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

843 844 845
	log.Debug(
		rpcReceived(method))

J
jaime 已提交
846 847 848
	if err := node.sched.ddQueue.Enqueue(act); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
849
			zap.Error(err))
J
jaime 已提交
850

E
Enwei Jiao 已提交
851
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
J
jaime 已提交
852 853 854 855 856 857 858 859 860 861
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", act.BeginTs()),
		zap.Uint64("EndTs", act.EndTs()),
862
		zap.Uint64("timestamp", request.Base.Timestamp))
J
jaime 已提交
863 864 865 866 867 868

	if err := act.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
			zap.Uint64("BeginTs", act.BeginTs()),
869
			zap.Uint64("EndTs", act.EndTs()))
J
jaime 已提交
870

E
Enwei Jiao 已提交
871
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
J
jaime 已提交
872 873 874 875 876 877 878 879 880
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", act.BeginTs()),
881
		zap.Uint64("EndTs", act.EndTs()))
J
jaime 已提交
882

E
Enwei Jiao 已提交
883 884
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
J
jaime 已提交
885 886 887
	return act.result, nil
}

888
// CreatePartition create a partition in specific collection.
C
Cai Yudong 已提交
889
func (node *Proxy) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
890 891 892
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
893

E
Enwei Jiao 已提交
894 895
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreatePartition")
	defer sp.End()
896 897
	method := "CreatePartition"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
898
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
899

900
	cpt := &createPartitionTask{
S
sunby 已提交
901
		ctx:                    ctx,
902 903
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
904
		rootCoord:              node.rootCoord,
905 906 907
		result:                 nil,
	}

908
	log := log.Ctx(ctx).With(
909
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
910 911 912
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
913

914 915
	log.Debug(rpcReceived("CreatePartition"))

916 917 918
	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
919
			zap.Error(err))
920

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

923
		return &commonpb.Status{
924
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
925 926 927
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
928

929 930 931
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.Uint64("BeginTS", cpt.BeginTs()),
932
		zap.Uint64("EndTS", cpt.EndTs()))
933 934 935 936

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
937
			zap.Error(err),
938
			zap.Uint64("BeginTS", cpt.BeginTs()),
939
			zap.Uint64("EndTS", cpt.EndTs()))
D
dragondriver 已提交
940

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

943
		return &commonpb.Status{
944
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
945 946 947
			Reason:    err.Error(),
		}, nil
	}
948 949 950 951

	log.Debug(
		rpcDone("CreatePartition"),
		zap.Uint64("BeginTS", cpt.BeginTs()),
952
		zap.Uint64("EndTS", cpt.EndTs()))
953

E
Enwei Jiao 已提交
954 955
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
956 957 958
	return cpt.result, nil
}

959
// DropPartition drop a partition in specific collection.
C
Cai Yudong 已提交
960
func (node *Proxy) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
961 962 963
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
964

E
Enwei Jiao 已提交
965 966
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropPartition")
	defer sp.End()
967 968
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
969
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
970

971
	dpt := &dropPartitionTask{
S
sunby 已提交
972
		ctx:                  ctx,
973 974
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
975
		rootCoord:            node.rootCoord,
C
cai.zhang 已提交
976
		queryCoord:           node.queryCoord,
977 978 979
		result:               nil,
	}

980
	log := log.Ctx(ctx).With(
981
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
982 983 984
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
985

986 987
	log.Debug(rpcReceived(method))

988 989 990
	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
991
			zap.Error(err))
992

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

995
		return &commonpb.Status{
996
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
997 998 999
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1000

1001 1002 1003
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", dpt.BeginTs()),
1004
		zap.Uint64("EndTS", dpt.EndTs()))
1005 1006 1007 1008

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1009
			zap.Error(err),
1010
			zap.Uint64("BeginTS", dpt.BeginTs()),
1011
			zap.Uint64("EndTS", dpt.EndTs()))
D
dragondriver 已提交
1012

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

1015
		return &commonpb.Status{
1016
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1017 1018 1019
			Reason:    err.Error(),
		}, nil
	}
1020 1021 1022 1023

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", dpt.BeginTs()),
1024
		zap.Uint64("EndTS", dpt.EndTs()))
1025

E
Enwei Jiao 已提交
1026 1027
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1028 1029 1030
	return dpt.result, nil
}

1031
// HasPartition check if partition exist.
C
Cai Yudong 已提交
1032
func (node *Proxy) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
1033 1034 1035 1036 1037
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
D
dragondriver 已提交
1038

E
Enwei Jiao 已提交
1039 1040
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-HasPartition")
	defer sp.End()
1041 1042 1043
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
E
Enwei Jiao 已提交
1044
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1045
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1046

1047
	hpt := &hasPartitionTask{
S
sunby 已提交
1048
		ctx:                 ctx,
1049 1050
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1051
		rootCoord:           node.rootCoord,
1052 1053 1054
		result:              nil,
	}

1055
	log := log.Ctx(ctx).With(
1056
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1057 1058 1059
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1060

1061 1062
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
1063 1064 1065
	if err := node.sched.ddQueue.Enqueue(hpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1066
			zap.Error(err))
D
dragondriver 已提交
1067

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

1071 1072
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1073
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1074 1075 1076 1077 1078
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1079

D
dragondriver 已提交
1080 1081 1082
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", hpt.BeginTs()),
1083
		zap.Uint64("EndTS", hpt.EndTs()))
D
dragondriver 已提交
1084 1085 1086 1087

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1088
			zap.Error(err),
D
dragondriver 已提交
1089
			zap.Uint64("BeginTS", hpt.BeginTs()),
1090
			zap.Uint64("EndTS", hpt.EndTs()))
D
dragondriver 已提交
1091

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

1095 1096
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1097
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1098 1099 1100 1101 1102
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1103 1104 1105 1106

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", hpt.BeginTs()),
1107
		zap.Uint64("EndTS", hpt.EndTs()))
D
dragondriver 已提交
1108

E
Enwei Jiao 已提交
1109
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1110
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1111
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1112 1113 1114
	return hpt.result, nil
}

1115
// LoadPartitions load specific partitions into query nodes.
C
Cai Yudong 已提交
1116
func (node *Proxy) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
1117 1118 1119
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1120

E
Enwei Jiao 已提交
1121 1122
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-LoadPartitions")
	defer sp.End()
1123 1124
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1125
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1126
		metrics.TotalLabel).Inc()
1127
	lpt := &loadPartitionsTask{
G
godchen 已提交
1128 1129 1130
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1131
		queryCoord:            node.queryCoord,
1132
		datacoord:             node.dataCoord,
1133 1134
	}

1135
	log := log.Ctx(ctx).With(
1136
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1137 1138
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
1139 1140
		zap.Strings("partitions", request.PartitionNames),
		zap.Bool("refreshMode", request.Refresh))
1141

1142 1143
	log.Debug(rpcReceived(method))

1144 1145 1146
	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1147
			zap.Error(err))
1148

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

1152
		return &commonpb.Status{
1153
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1154 1155 1156 1157
			Reason:    err.Error(),
		}, nil
	}

1158 1159 1160
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", lpt.BeginTs()),
1161
		zap.Uint64("EndTS", lpt.EndTs()))
1162 1163 1164 1165

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1166
			zap.Error(err),
1167
			zap.Uint64("BeginTS", lpt.BeginTs()),
1168
			zap.Uint64("EndTS", lpt.EndTs()))
D
dragondriver 已提交
1169

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

1173
		return &commonpb.Status{
1174
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1175 1176 1177 1178
			Reason:    err.Error(),
		}, nil
	}

1179 1180 1181
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", lpt.BeginTs()),
1182
		zap.Uint64("EndTS", lpt.EndTs()))
1183

E
Enwei Jiao 已提交
1184
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1185
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1186
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1187
	return lpt.result, nil
1188 1189
}

1190
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1191
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1192 1193 1194
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1195

E
Enwei Jiao 已提交
1196 1197
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ReleasePartitions")
	defer sp.End()
1198

1199
	rpt := &releasePartitionsTask{
G
godchen 已提交
1200 1201 1202
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1203
		queryCoord:               node.queryCoord,
1204 1205
	}

1206
	method := "ReleasePartitions"
1207
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1208
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1209
		metrics.TotalLabel).Inc()
1210 1211

	log := log.Ctx(ctx).With(
1212
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1213 1214 1215
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1216

1217 1218
	log.Debug(rpcReceived(method))

1219 1220 1221
	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1222
			zap.Error(err))
1223

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

1227
		return &commonpb.Status{
1228
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1229 1230 1231 1232
			Reason:    err.Error(),
		}, nil
	}

1233 1234 1235
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", rpt.BeginTs()),
1236
		zap.Uint64("EndTS", rpt.EndTs()))
1237 1238 1239 1240

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1241
			zap.Error(err),
1242
			zap.Uint64("BeginTS", rpt.BeginTs()),
1243
			zap.Uint64("EndTS", rpt.EndTs()))
D
dragondriver 已提交
1244

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

1248
		return &commonpb.Status{
1249
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1250 1251 1252 1253
			Reason:    err.Error(),
		}, nil
	}

1254 1255 1256
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", rpt.BeginTs()),
1257
		zap.Uint64("EndTS", rpt.EndTs()))
1258

E
Enwei Jiao 已提交
1259
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1260
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1261
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1262
	return rpt.result, nil
1263 1264
}

1265
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1266
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1267 1268 1269 1270 1271
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1272

E
Enwei Jiao 已提交
1273 1274
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetPartitionStatistics")
	defer sp.End()
1275 1276
	method := "GetPartitionStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1277
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1278
		metrics.TotalLabel).Inc()
1279

1280
	g := &getPartitionStatisticsTask{
1281 1282 1283
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1284
		dataCoord:                     node.dataCoord,
1285 1286
	}

1287
	log := log.Ctx(ctx).With(
1288
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1289 1290 1291
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1292

1293 1294
	log.Debug(rpcReceived(method))

1295 1296 1297
	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1298
			zap.Error(err))
1299

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

1303 1304 1305 1306 1307 1308 1309 1310
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1311 1312 1313
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", g.BeginTs()),
1314
		zap.Uint64("EndTS", g.EndTs()))
1315 1316 1317 1318

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1319
			zap.Error(err),
1320
			zap.Uint64("BeginTS", g.BeginTs()),
1321
			zap.Uint64("EndTS", g.EndTs()))
1322

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

1326 1327 1328 1329 1330 1331 1332 1333
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1334 1335 1336
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", g.BeginTs()),
1337
		zap.Uint64("EndTS", g.EndTs()))
1338

E
Enwei Jiao 已提交
1339
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1340
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1341
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1342
	return g.result, nil
1343 1344
}

1345
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1346
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1347 1348 1349 1350 1351
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1352

E
Enwei Jiao 已提交
1353 1354
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ShowPartitions")
	defer sp.End()
1355

1356
	spt := &showPartitionsTask{
G
godchen 已提交
1357 1358 1359
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1360
		rootCoord:             node.rootCoord,
1361
		queryCoord:            node.queryCoord,
G
godchen 已提交
1362
		result:                nil,
1363 1364
	}

1365
	method := "ShowPartitions"
1366 1367
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
E
Enwei Jiao 已提交
1368
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1369
		metrics.TotalLabel).Inc()
1370

1371 1372
	log := log.Ctx(ctx).With(zap.String("role", typeutil.ProxyRole))

1373 1374
	log.Debug(
		rpcReceived(method),
G
godchen 已提交
1375
		zap.Any("request", request))
1376 1377 1378 1379 1380 1381 1382

	if err := node.sched.ddQueue.Enqueue(spt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.Any("request", request))

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

G
godchen 已提交
1386
		return &milvuspb.ShowPartitionsResponse{
1387
			Status: &commonpb.Status{
1388
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1389 1390 1391 1392 1393
				Reason:    err.Error(),
			},
		}, nil
	}

1394 1395 1396 1397
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1398 1399
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1400 1401 1402 1403 1404
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1405
			zap.Error(err),
1406 1407 1408 1409 1410
			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 已提交
1411

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

G
godchen 已提交
1415
		return &milvuspb.ShowPartitionsResponse{
1416
			Status: &commonpb.Status{
1417
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1418 1419 1420 1421
				Reason:    err.Error(),
			},
		}, nil
	}
1422 1423 1424 1425 1426 1427 1428 1429 1430

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

E
Enwei Jiao 已提交
1431
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1432
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1433
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1434 1435 1436
	return spt.result, nil
}

S
SimFG 已提交
1437 1438 1439 1440 1441 1442
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)
E
Enwei Jiao 已提交
1443 1444
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetLoadingProgress")
	defer sp.End()
E
Enwei Jiao 已提交
1445
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1446 1447 1448
	log := log.Ctx(ctx)

	log.Debug(
S
SimFG 已提交
1449 1450 1451 1452
		rpcReceived(method),
		zap.Any("request", request))

	getErrResponse := func(err error) *milvuspb.GetLoadingProgressResponse {
J
Jiquan Long 已提交
1453
		log.Warn("fail to get loading progress",
1454
			zap.String("collection_name", request.CollectionName),
S
SimFG 已提交
1455 1456
			zap.Strings("partition_name", request.PartitionNames),
			zap.Error(err))
E
Enwei Jiao 已提交
1457
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1458 1459 1460 1461 1462
		if errors.Is(err, ErrInsufficientMemory) {
			return &milvuspb.GetLoadingProgressResponse{
				Status: InSufficientMemoryStatus(request.GetCollectionName()),
			}
		}
S
SimFG 已提交
1463
		return &milvuspb.GetLoadingProgressResponse{
S
smellthemoon 已提交
1464
			Status: merr.Status(err),
S
SimFG 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473
		}
	}
	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
	}
S
SimFG 已提交
1474

1475 1476 1477
	msgBase := commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
1478
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
1479
	)
S
SimFG 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	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 {
S
SimFG 已提交
1490
		if progress, err = getCollectionProgress(ctx, node.queryCoord, request.GetBase(), collectionID); err != nil {
S
SimFG 已提交
1491 1492 1493
			return getErrResponse(err), nil
		}
	} else {
S
SimFG 已提交
1494 1495
		if progress, err = getPartitionProgress(ctx, node.queryCoord, request.GetBase(),
			request.GetPartitionNames(), request.GetCollectionName(), collectionID); err != nil {
S
SimFG 已提交
1496 1497 1498 1499
			return getErrResponse(err), nil
		}
	}

1500
	log.Debug(
S
SimFG 已提交
1501 1502
		rpcDone(method),
		zap.Any("request", request))
E
Enwei Jiao 已提交
1503 1504
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
S
SimFG 已提交
1505 1506 1507 1508 1509 1510 1511 1512
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1513
func (node *Proxy) GetLoadState(ctx context.Context, request *milvuspb.GetLoadStateRequest) (*milvuspb.GetLoadStateResponse, error) {
S
SimFG 已提交
1514 1515 1516 1517 1518
	if !node.checkHealthy() {
		return &milvuspb.GetLoadStateResponse{Status: unhealthyStatus()}, nil
	}
	method := "GetLoadState"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1519 1520
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetLoadState")
	defer sp.End()
S
SimFG 已提交
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
	log := log.Ctx(ctx)

	log.Debug(
		rpcReceived(method),
		zap.Any("request", request))

	getErrResponse := func(err error) *milvuspb.GetLoadStateResponse {
		log.Warn("fail to get load state",
			zap.String("collection_name", request.CollectionName),
			zap.Strings("partition_name", request.PartitionNames),
			zap.Error(err))
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		return &milvuspb.GetLoadStateResponse{
S
smellthemoon 已提交
1535
			Status: merr.Status(err),
S
SimFG 已提交
1536 1537 1538 1539 1540 1541 1542
		}
	}

	if err := validateCollectionName(request.CollectionName); err != nil {
		return getErrResponse(err), nil
	}

1543 1544
	// TODO(longjiquan): https://github.com/milvus-io/milvus/issues/21485, Remove `GetComponentStates` after error code
	// 	is ready to distinguish case whether the querycoord is not healthy or the collection is not even loaded.
S
SimFG 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
	if statesResp, err := node.queryCoord.GetComponentStates(ctx); err != nil {
		return getErrResponse(err), nil
	} else if statesResp.State == nil || statesResp.State.StateCode != commonpb.StateCode_Healthy {
		return getErrResponse(fmt.Errorf("the querycoord server isn't healthy, state: %v", statesResp.State)), nil
	}

	successResponse := &milvuspb.GetLoadStateResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
	}
	defer func() {
		log.Debug(
			rpcDone(method),
			zap.Any("request", request))
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
		metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	}()

	collectionID, err := globalMetaCache.GetCollectionID(ctx, request.CollectionName)
	if err != nil {
		successResponse.State = commonpb.LoadState_LoadStateNotExist
		return successResponse, nil
	}

	msgBase := commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
	)
	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 = getCollectionProgress(ctx, node.queryCoord, request.GetBase(), collectionID); err != nil {
1586 1587 1588 1589 1590
			if errors.Is(err, ErrInsufficientMemory) {
				return &milvuspb.GetLoadStateResponse{
					Status: InSufficientMemoryStatus(request.GetCollectionName()),
				}, nil
			}
S
SimFG 已提交
1591 1592 1593 1594 1595 1596
			successResponse.State = commonpb.LoadState_LoadStateNotLoad
			return successResponse, nil
		}
	} else {
		if progress, err = getPartitionProgress(ctx, node.queryCoord, request.GetBase(),
			request.GetPartitionNames(), request.GetCollectionName(), collectionID); err != nil {
1597 1598 1599 1600 1601
			if errors.Is(err, ErrInsufficientMemory) {
				return &milvuspb.GetLoadStateResponse{
					Status: InSufficientMemoryStatus(request.GetCollectionName()),
				}, nil
			}
S
SimFG 已提交
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
			successResponse.State = commonpb.LoadState_LoadStateNotLoad
			return successResponse, nil
		}
	}
	if progress >= 100 {
		successResponse.State = commonpb.LoadState_LoadStateLoaded
	} else {
		successResponse.State = commonpb.LoadState_LoadStateLoading
	}
	return successResponse, nil
1612 1613
}

1614
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1615
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1616 1617 1618
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1619

E
Enwei Jiao 已提交
1620 1621
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateIndex")
	defer sp.End()
D
dragondriver 已提交
1622

1623
	cit := &createIndexTask{
Z
zhenshan.cao 已提交
1624 1625 1626 1627
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		req:        request,
		rootCoord:  node.rootCoord,
1628
		datacoord:  node.dataCoord,
1629
		queryCoord: node.queryCoord,
1630 1631
	}

D
dragondriver 已提交
1632
	method := "CreateIndex"
1633
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1634
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1635
		metrics.TotalLabel).Inc()
1636 1637

	log := log.Ctx(ctx).With(
1638
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1639 1640 1641 1642
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1643

1644 1645
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
1646 1647 1648
	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1649
			zap.Error(err))
D
dragondriver 已提交
1650

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

1654
		return &commonpb.Status{
1655
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1656 1657 1658 1659
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1660 1661 1662
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", cit.BeginTs()),
1663
		zap.Uint64("EndTs", cit.EndTs()))
D
dragondriver 已提交
1664 1665 1666 1667

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1668
			zap.Error(err),
D
dragondriver 已提交
1669
			zap.Uint64("BeginTs", cit.BeginTs()),
1670
			zap.Uint64("EndTs", cit.EndTs()))
D
dragondriver 已提交
1671

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

1675
		return &commonpb.Status{
1676
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1677 1678 1679 1680
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1681 1682 1683
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", cit.BeginTs()),
1684
		zap.Uint64("EndTs", cit.EndTs()))
D
dragondriver 已提交
1685

E
Enwei Jiao 已提交
1686
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1687
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1688
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1689 1690 1691
	return cit.result, nil
}

1692
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
1693
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
1694 1695 1696 1697 1698
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1699

E
Enwei Jiao 已提交
1700 1701
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DescribeIndex")
	defer sp.End()
1702

1703
	dit := &describeIndexTask{
S
sunby 已提交
1704
		ctx:                  ctx,
1705 1706
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
1707
		datacoord:            node.dataCoord,
1708 1709
	}

1710 1711
	method := "DescribeIndex"
	// avoid data race
1712
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1713
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1714
		metrics.TotalLabel).Inc()
1715 1716

	log := log.Ctx(ctx).With(
1717
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1718 1719 1720
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
1721 1722 1723
		zap.String("index name", request.IndexName))

	log.Debug(rpcReceived(method))
1724 1725 1726 1727

	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1728
			zap.Error(err))
1729

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

1733 1734
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
1735
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1736 1737 1738 1739 1740
				Reason:    err.Error(),
			},
		}, nil
	}

1741 1742 1743
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", dit.BeginTs()),
1744
		zap.Uint64("EndTs", dit.EndTs()))
1745 1746 1747 1748

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1749
			zap.Error(err),
1750
			zap.Uint64("BeginTs", dit.BeginTs()),
1751
			zap.Uint64("EndTs", dit.EndTs()))
D
dragondriver 已提交
1752

Z
zhenshan.cao 已提交
1753 1754 1755 1756
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
E
Enwei Jiao 已提交
1757
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1758
			metrics.FailLabel).Inc()
1759

1760 1761
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
1762
				ErrorCode: errCode,
1763 1764 1765 1766 1767
				Reason:    err.Error(),
			},
		}, nil
	}

1768 1769 1770
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", dit.BeginTs()),
1771
		zap.Uint64("EndTs", dit.EndTs()))
1772

E
Enwei Jiao 已提交
1773
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1774
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1775
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1776 1777 1778
	return dit.result, nil
}

1779
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
1780
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
1781 1782 1783
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1784

E
Enwei Jiao 已提交
1785 1786
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropIndex")
	defer sp.End()
D
dragondriver 已提交
1787

1788
	dit := &dropIndexTask{
S
sunby 已提交
1789
		ctx:              ctx,
B
BossZou 已提交
1790 1791
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
1792
		dataCoord:        node.dataCoord,
1793
		queryCoord:       node.queryCoord,
B
BossZou 已提交
1794
	}
G
godchen 已提交
1795

D
dragondriver 已提交
1796
	method := "DropIndex"
1797
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1798
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1799
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1800

1801
	log := log.Ctx(ctx).With(
1802
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1803 1804 1805 1806 1807
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

1808 1809
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
1810 1811 1812
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1813
			zap.Error(err))
E
Enwei Jiao 已提交
1814
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1815
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
1816

B
BossZou 已提交
1817
		return &commonpb.Status{
1818
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
1819 1820 1821
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1822

D
dragondriver 已提交
1823 1824 1825
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", dit.BeginTs()),
1826
		zap.Uint64("EndTs", dit.EndTs()))
D
dragondriver 已提交
1827 1828 1829 1830

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1831
			zap.Error(err),
D
dragondriver 已提交
1832
			zap.Uint64("BeginTs", dit.BeginTs()),
1833
			zap.Uint64("EndTs", dit.EndTs()))
D
dragondriver 已提交
1834

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

B
BossZou 已提交
1838
		return &commonpb.Status{
1839
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
1840 1841 1842
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1843 1844 1845 1846

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", dit.BeginTs()),
1847
		zap.Uint64("EndTs", dit.EndTs()))
D
dragondriver 已提交
1848

E
Enwei Jiao 已提交
1849
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1850
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1851
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
1852 1853 1854
	return dit.result, nil
}

1855 1856
// 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.
1857
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
1858
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
1859 1860 1861 1862 1863
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1864

E
Enwei Jiao 已提交
1865 1866
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetIndexBuildProgress")
	defer sp.End()
1867

1868
	gibpt := &getIndexBuildProgressTask{
1869 1870 1871
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
1872
		rootCoord:                    node.rootCoord,
1873
		dataCoord:                    node.dataCoord,
1874 1875
	}

1876
	method := "GetIndexBuildProgress"
1877
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1878
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1879
		metrics.TotalLabel).Inc()
1880 1881

	log := log.Ctx(ctx).With(
1882
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1883 1884 1885 1886
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
1887

1888 1889
	log.Debug(rpcReceived(method))

1890 1891 1892
	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1893
			zap.Error(err))
E
Enwei Jiao 已提交
1894
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1895
			metrics.AbandonLabel).Inc()
1896

1897 1898 1899 1900 1901 1902 1903 1904
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1905 1906 1907
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
1908
		zap.Uint64("EndTs", gibpt.EndTs()))
1909 1910 1911 1912

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1913
			zap.Error(err),
1914
			zap.Uint64("BeginTs", gibpt.BeginTs()),
1915
			zap.Uint64("EndTs", gibpt.EndTs()))
E
Enwei Jiao 已提交
1916
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1917
			metrics.FailLabel).Inc()
1918 1919 1920 1921 1922 1923 1924 1925

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

	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
1930
		zap.Uint64("EndTs", gibpt.EndTs()))
1931

E
Enwei Jiao 已提交
1932
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1933
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1934
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1935
	return gibpt.result, nil
1936 1937
}

1938
// GetIndexState get the build-state of index.
1939
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
1940
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
1941 1942 1943 1944 1945
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1946

E
Enwei Jiao 已提交
1947 1948
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Insert")
	defer sp.End()
1949

1950
	dipt := &getIndexStateTask{
G
godchen 已提交
1951 1952 1953
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
1954
		dataCoord:            node.dataCoord,
1955
		rootCoord:            node.rootCoord,
1956 1957
	}

1958
	method := "GetIndexState"
1959
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1960
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1961
		metrics.TotalLabel).Inc()
1962 1963

	log := log.Ctx(ctx).With(
1964
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1965 1966 1967 1968
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
1969

1970 1971
	log.Debug(rpcReceived(method))

1972 1973 1974
	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1975
			zap.Error(err))
1976

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

G
godchen 已提交
1980
		return &milvuspb.GetIndexStateResponse{
1981
			Status: &commonpb.Status{
1982
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1983 1984 1985 1986 1987
				Reason:    err.Error(),
			},
		}, nil
	}

1988 1989 1990
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", dipt.BeginTs()),
1991
		zap.Uint64("EndTs", dipt.EndTs()))
1992 1993 1994 1995

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1996
			zap.Error(err),
1997
			zap.Uint64("BeginTs", dipt.BeginTs()),
1998
			zap.Uint64("EndTs", dipt.EndTs()))
E
Enwei Jiao 已提交
1999
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2000
			metrics.FailLabel).Inc()
2001

G
godchen 已提交
2002
		return &milvuspb.GetIndexStateResponse{
2003
			Status: &commonpb.Status{
2004
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2005 2006 2007 2008 2009
				Reason:    err.Error(),
			},
		}, nil
	}

2010 2011 2012
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", dipt.BeginTs()),
2013
		zap.Uint64("EndTs", dipt.EndTs()))
2014

E
Enwei Jiao 已提交
2015
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2016
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2017
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2018 2019 2020
	return dipt.result, nil
}

2021
// Insert insert records into collection.
C
Cai Yudong 已提交
2022
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
E
Enwei Jiao 已提交
2023 2024
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Insert")
	defer sp.End()
X
Xiangyu Wang 已提交
2025

2026 2027 2028 2029 2030
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2031 2032
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
S
smellthemoon 已提交
2033
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel).Add(float64(proto.Size(request)))
E
Enwei Jiao 已提交
2034
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
S
smellthemoon 已提交
2035

2036
	it := &insertTask{
2037 2038
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2039
		// req:       request,
2040
		insertMsg: &msgstream.InsertMsg{
2041 2042 2043
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
2044
			InsertRequest: msgpb.InsertRequest{
2045 2046 2047
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Insert),
					commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
2048
					commonpbutil.WithSourceID(paramtable.GetNodeID()),
2049
				),
2050 2051
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2052 2053
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
2054
				Version:        msgpb.InsertDataVersion_ColumnBased,
2055
				// RowData: transfer column based request to this
2056 2057
			},
		},
2058
		idAllocator:   node.rowIDAllocator,
2059 2060 2061
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2062
	}
2063

2064 2065
	if len(it.insertMsg.PartitionName) <= 0 {
		it.insertMsg.PartitionName = Params.CommonCfg.DefaultPartitionName.GetValue()
2066 2067
	}

X
Xiangyu Wang 已提交
2068
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2069
		numRows := request.NumRows
2070 2071 2072 2073
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2074

X
Xiangyu Wang 已提交
2075 2076 2077 2078 2079 2080 2081
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2082 2083
	}

X
Xiangyu Wang 已提交
2084
	log.Debug("Enqueue insert request in Proxy",
2085
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2086 2087 2088 2089 2090
		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)),
2091
		zap.Uint32("NumRows", request.NumRows))
D
dragondriver 已提交
2092

X
Xiangyu Wang 已提交
2093
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
J
Jiquan Long 已提交
2094
		log.Warn("Failed to enqueue insert task: " + err.Error())
E
Enwei Jiao 已提交
2095
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2096
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2097
		return constructFailedResponse(err), nil
2098
	}
D
dragondriver 已提交
2099

X
Xiangyu Wang 已提交
2100
	log.Debug("Detail of insert request in Proxy",
2101
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2102 2103 2104 2105 2106
		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),
2107
		zap.Uint32("NumRows", request.NumRows))
X
Xiangyu Wang 已提交
2108 2109

	if err := it.WaitToFinish(); err != nil {
2110
		log.Warn("Failed to execute insert task in task scheduler: " + err.Error())
E
Enwei Jiao 已提交
2111
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2112
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2113 2114 2115 2116 2117
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2118
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
			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 已提交
2130
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2131

S
smellthemoon 已提交
2132 2133 2134
	receiveSize := proto.Size(it.insertMsg)
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(receiveSize))

E
Enwei Jiao 已提交
2135
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2136
		metrics.SuccessLabel).Inc()
2137
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
E
Enwei Jiao 已提交
2138 2139 2140
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(successCnt))
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.InsertLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
2141 2142 2143
	return it.result, nil
}

2144
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2145
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
E
Enwei Jiao 已提交
2146 2147
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Delete")
	defer sp.End()
2148 2149 2150
	log := log.Ctx(ctx)
	log.Debug("Start processing delete request in Proxy")
	defer log.Debug("Finish processing delete request in Proxy")
2151

S
smellthemoon 已提交
2152
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel).Add(float64(proto.Size(request)))
2153

G
groot 已提交
2154 2155 2156 2157 2158 2159
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2160 2161 2162
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
2163
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2164
		metrics.TotalLabel).Inc()
2165
	dt := &deleteTask{
X
xige-16 已提交
2166 2167 2168
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
2169
		deleteMsg: &BaseDeleteTask{
G
godchen 已提交
2170 2171 2172
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
2173
			DeleteRequest: msgpb.DeleteRequest{
2174 2175 2176 2177
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Delete),
					commonpbutil.WithMsgID(0),
				),
X
xige-16 已提交
2178
				DbName:         request.DbName,
G
godchen 已提交
2179 2180 2181
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2182 2183
			},
		},
S
smellthemoon 已提交
2184 2185 2186
		idAllocator: node.rowIDAllocator,
		chMgr:       node.chMgr,
		chTicker:    node.chTicker,
G
groot 已提交
2187 2188
	}

2189
	log.Debug("Enqueue delete request in Proxy",
2190
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2191 2192 2193 2194
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2195 2196 2197

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

G
groot 已提交
2202 2203 2204 2205 2206 2207 2208 2209
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2210
	log.Debug("Detail of delete request in Proxy",
2211
		zap.String("role", typeutil.ProxyRole),
2212
		zap.Uint64("timestamp", dt.deleteMsg.Base.Timestamp),
G
groot 已提交
2213 2214 2215
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
2216
		zap.String("expr", request.Expr))
G
groot 已提交
2217

2218
	if err := dt.WaitToFinish(); err != nil {
2219
		log.Error("Failed to execute delete task in task scheduler: " + err.Error())
E
Enwei Jiao 已提交
2220
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2221
			metrics.FailLabel).Inc()
G
groot 已提交
2222 2223 2224 2225 2226 2227 2228 2229
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

S
smellthemoon 已提交
2230 2231 2232
	receiveSize := proto.Size(dt.deleteMsg)
	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(receiveSize))

E
Enwei Jiao 已提交
2233
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2234
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2235 2236
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.DeleteLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2237 2238 2239
	return dt.result, nil
}

S
smellthemoon 已提交
2240 2241
// Upsert upsert records into collection.
func (node *Proxy) Upsert(ctx context.Context, request *milvuspb.UpsertRequest) (*milvuspb.MutationResult, error) {
E
Enwei Jiao 已提交
2242 2243
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Upsert")
	defer sp.End()
S
smellthemoon 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.Uint32("NumRows", request.NumRows),
	)
	log.Debug("Start processing upsert request in Proxy")

	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
	method := "Upsert"
	tr := timerecord.NewTimeRecorder(method)

	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.UpsertLabel).Add(float64(proto.Size(request)))
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()

	it := &upsertTask{
		baseMsg: msgstream.BaseMsg{
			HashValues: request.HashKeys,
		},
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),

		req: &milvuspb.UpsertRequest{
			Base: commonpbutil.NewMsgBase(
2274
				commonpbutil.WithMsgType(commonpb.MsgType_Upsert),
S
smellthemoon 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
				commonpbutil.WithSourceID(paramtable.GetNodeID()),
			),
			CollectionName: request.CollectionName,
			PartitionName:  request.PartitionName,
			FieldsData:     request.FieldsData,
			NumRows:        request.NumRows,
		},

		result: &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_Success,
			},
			IDs: &schemapb.IDs{
				IdField: nil,
			},
		},

		idAllocator:   node.rowIDAllocator,
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
	}

	if len(it.req.PartitionName) <= 0 {
		it.req.PartitionName = Params.CommonCfg.DefaultPartitionName.GetValue()
	}

	constructFailedResponse := func(err error, errCode commonpb.ErrorCode) *milvuspb.MutationResult {
		numRows := request.NumRows
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}

		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: errCode,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
	}

	log.Debug("Enqueue upsert request in Proxy",
		zap.Int("len(FieldsData)", len(request.FieldsData)),
		zap.Int("len(HashKeys)", len(request.HashKeys)))

	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Info("Failed to enqueue upsert task",
			zap.Error(err))
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

	log.Debug("Detail of upsert request in Proxy",
		zap.Uint64("BeginTS", it.BeginTs()),
		zap.Uint64("EndTS", it.EndTs()))

	if err := it.WaitToFinish(); err != nil {
		log.Info("Failed to execute insert task in task scheduler",
			zap.Error(err))
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
S
smellthemoon 已提交
2344 2345 2346 2347 2348
		// Not every error case changes the status internally
		// change status there to handle it
		if it.result.Status.ErrorCode == commonpb.ErrorCode_Success {
			it.result.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		}
S
smellthemoon 已提交
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378
		return constructFailedResponse(err, it.result.Status.ErrorCode), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
			numRows := request.NumRows
			errIndex := make([]uint32, numRows)
			for i := uint32(0); i < numRows; i++ {
				errIndex[i] = i
			}
			it.result.ErrIndex = errIndex
		}
		setErrorIndex()
	}

	insertReceiveSize := proto.Size(it.upsertMsg.InsertMsg)
	deleteReceiveSize := proto.Size(it.upsertMsg.DeleteMsg)

	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(deleteReceiveSize))
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(insertReceiveSize))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.UpsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
	metrics.ProxyCollectionMutationLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.UpsertLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))

	log.Debug("Finish processing upsert request in Proxy")
	return it.result, nil
}

2379
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2380
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2381
	receiveSize := proto.Size(request)
E
Enwei Jiao 已提交
2382
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.SearchLabel).Add(float64(receiveSize))
2383 2384 2385

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

2386 2387 2388 2389 2390
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2391 2392
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2393
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2394
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2395

E
Enwei Jiao 已提交
2396 2397
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Search")
	defer sp.End()
D
dragondriver 已提交
2398

2399
	qt := &searchTask{
S
sunby 已提交
2400
		ctx:       ctx,
2401
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2402
		SearchRequest: &internalpb.SearchRequest{
2403 2404
			Base: commonpbutil.NewMsgBase(
				commonpbutil.WithMsgType(commonpb.MsgType_Search),
E
Enwei Jiao 已提交
2405
				commonpbutil.WithSourceID(paramtable.GetNodeID()),
2406
			),
E
Enwei Jiao 已提交
2407
			ReqID: paramtable.GetNodeID(),
2408
		},
2409 2410 2411 2412
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2413 2414
	}

2415 2416 2417
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

2418
	log := log.Ctx(ctx).With(
2419
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2420 2421 2422 2423 2424
		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)),
2425 2426 2427 2428
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2429

2430 2431 2432
	log.Debug(
		rpcReceived(method))

2433
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
2434
		log.Warn(
2435
			rpcFailedToEnqueue(method),
2436
			zap.Error(err))
D
dragondriver 已提交
2437

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

2441 2442
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2443
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2444 2445 2446 2447
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2448
	tr.CtxRecord(ctx, "search request enqueue")
2449

2450
	log.Debug(
2451
		rpcEnqueued(method),
2452
		zap.Uint64("timestamp", qt.Base.Timestamp))
D
dragondriver 已提交
2453

2454
	if err := qt.WaitToFinish(); err != nil {
2455
		log.Warn(
2456
			rpcFailedToWaitToFinish(method),
2457
			zap.Error(err))
2458

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

2462 2463
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2464
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2465 2466 2467 2468 2469
				Reason:    err.Error(),
			},
		}, nil
	}

Z
Zach 已提交
2470
	span := tr.CtxRecord(ctx, "wait search result")
E
Enwei Jiao 已提交
2471
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2472
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
2473
	tr.CtxRecord(ctx, "wait search result")
2474
	log.Debug(rpcDone(method))
D
dragondriver 已提交
2475

E
Enwei Jiao 已提交
2476
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2477
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
2478
	metrics.ProxySearchVectors.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(qt.result.GetResults().GetNumQueries()))
C
cai.zhang 已提交
2479
	searchDur := tr.ElapseSpan().Milliseconds()
E
Enwei Jiao 已提交
2480
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2481
		metrics.SearchLabel).Observe(float64(searchDur))
E
Enwei Jiao 已提交
2482
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2483
		metrics.SearchLabel, request.CollectionName).Observe(float64(searchDur))
2484 2485
	if qt.result != nil {
		sentSize := proto.Size(qt.result)
E
Enwei Jiao 已提交
2486
		metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(sentSize))
2487
		rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
2488
	}
2489 2490 2491
	return qt.result, nil
}

2492
// Flush notify data nodes to persist the data of collection.
2493 2494 2495 2496 2497 2498 2499
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2500
	if !node.checkHealthy() {
2501 2502
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2503
	}
D
dragondriver 已提交
2504

E
Enwei Jiao 已提交
2505 2506
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Flush")
	defer sp.End()
D
dragondriver 已提交
2507

2508
	ft := &flushTask{
T
ThreadDao 已提交
2509 2510 2511
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2512
		dataCoord:    node.dataCoord,
2513 2514
	}

D
dragondriver 已提交
2515
	method := "Flush"
2516
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2517
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2518

2519
	log := log.Ctx(ctx).With(
2520
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2521 2522
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2523

2524 2525
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2526 2527 2528
	if err := node.sched.ddQueue.Enqueue(ft); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2529
			zap.Error(err))
D
dragondriver 已提交
2530

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

2533 2534
		resp.Status.Reason = err.Error()
		return resp, nil
2535 2536
	}

D
dragondriver 已提交
2537 2538 2539
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", ft.BeginTs()),
2540
		zap.Uint64("EndTs", ft.EndTs()))
D
dragondriver 已提交
2541 2542 2543 2544

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2545
			zap.Error(err),
D
dragondriver 已提交
2546
			zap.Uint64("BeginTs", ft.BeginTs()),
2547
			zap.Uint64("EndTs", ft.EndTs()))
D
dragondriver 已提交
2548

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

D
dragondriver 已提交
2551
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2552 2553
		resp.Status.Reason = err.Error()
		return resp, nil
2554 2555
	}

D
dragondriver 已提交
2556 2557 2558
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", ft.BeginTs()),
2559
		zap.Uint64("EndTs", ft.EndTs()))
D
dragondriver 已提交
2560

E
Enwei Jiao 已提交
2561 2562
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2563
	return ft.result, nil
2564 2565
}

2566
// Query get the records by primary keys.
C
Cai Yudong 已提交
2567
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2568
	receiveSize := proto.Size(request)
E
Enwei Jiao 已提交
2569
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), metrics.QueryLabel).Add(float64(receiveSize))
2570 2571 2572

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

2573 2574 2575 2576 2577
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2578

E
Enwei Jiao 已提交
2579 2580
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Query")
	defer sp.End()
2581
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2582

2583
	qt := &queryTask{
2584 2585 2586
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
2587 2588
			Base: commonpbutil.NewMsgBase(
				commonpbutil.WithMsgType(commonpb.MsgType_Retrieve),
E
Enwei Jiao 已提交
2589
				commonpbutil.WithSourceID(paramtable.GetNodeID()),
2590
			),
E
Enwei Jiao 已提交
2591
			ReqID: paramtable.GetNodeID(),
2592
		},
2593 2594
		request:          request,
		qc:               node.queryCoord,
2595
		queryShardPolicy: mergeRoundRobinPolicy,
2596
		shardMgr:         node.shardMgr,
2597 2598
	}

D
dragondriver 已提交
2599 2600
	method := "Query"

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

2604
	log := log.Ctx(ctx).With(
2605
		zap.String("role", typeutil.ProxyRole),
2606 2607
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2608 2609 2610 2611
		zap.Strings("partitions", request.PartitionNames))

	log.Debug(
		rpcReceived(method),
2612 2613 2614 2615
		zap.String("expr", request.Expr),
		zap.Strings("OutputFields", request.OutputFields),
		zap.Uint64("travel_timestamp", request.TravelTimestamp),
		zap.Uint64("guarantee_timestamp", request.GuaranteeTimestamp))
G
godchen 已提交
2616

D
dragondriver 已提交
2617
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
2618
		log.Warn(
D
dragondriver 已提交
2619
			rpcFailedToEnqueue(method),
2620
			zap.Error(err))
D
dragondriver 已提交
2621

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

2625 2626 2627 2628 2629 2630
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
2631
	}
Z
Zach 已提交
2632
	tr.CtxRecord(ctx, "query request enqueue")
2633

2634
	log.Debug(rpcEnqueued(method))
D
dragondriver 已提交
2635 2636

	if err := qt.WaitToFinish(); err != nil {
2637
		log.Warn(
D
dragondriver 已提交
2638
			rpcFailedToWaitToFinish(method),
2639
			zap.Error(err))
2640

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

2644 2645 2646 2647 2648 2649 2650
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2651
	span := tr.CtxRecord(ctx, "wait query result")
E
Enwei Jiao 已提交
2652
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2653
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
2654

2655
	log.Debug(rpcDone(method))
D
dragondriver 已提交
2656

E
Enwei Jiao 已提交
2657
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2658 2659
		metrics.SuccessLabel).Inc()

E
Enwei Jiao 已提交
2660
	metrics.ProxySQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2661
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
E
Enwei Jiao 已提交
2662
	metrics.ProxyCollectionSQLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10),
2663
		metrics.QueryLabel, request.CollectionName).Observe(float64(tr.ElapseSpan().Milliseconds()))
2664 2665

	ret := &milvuspb.QueryResults{
2666 2667
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
2668 2669
	}
	sentSize := proto.Size(qt.result)
2670
	rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
E
Enwei Jiao 已提交
2671
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Add(float64(sentSize))
2672
	return ret, nil
2673
}
2674

2675
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
2676 2677 2678 2679
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2680

E
Enwei Jiao 已提交
2681 2682
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateAlias")
	defer sp.End()
D
dragondriver 已提交
2683

Y
Yusup 已提交
2684 2685 2686 2687 2688 2689 2690
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
2691
	method := "CreateAlias"
2692
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2693
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2694

2695
	log := log.Ctx(ctx).With(
D
dragondriver 已提交
2696 2697 2698 2699 2700
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

2701 2702
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2703 2704 2705
	if err := node.sched.ddQueue.Enqueue(cat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2706
			zap.Error(err))
D
dragondriver 已提交
2707

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

Y
Yusup 已提交
2710 2711 2712 2713 2714 2715
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2716 2717 2718
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", cat.BeginTs()),
2719
		zap.Uint64("EndTs", cat.EndTs()))
D
dragondriver 已提交
2720 2721 2722 2723

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2724
			zap.Error(err),
D
dragondriver 已提交
2725
			zap.Uint64("BeginTs", cat.BeginTs()),
2726
			zap.Uint64("EndTs", cat.EndTs()))
E
Enwei Jiao 已提交
2727
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
2728 2729 2730 2731 2732 2733 2734

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

D
dragondriver 已提交
2735 2736 2737
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", cat.BeginTs()),
2738
		zap.Uint64("EndTs", cat.EndTs()))
D
dragondriver 已提交
2739

E
Enwei Jiao 已提交
2740 2741
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
2742 2743 2744
	return cat.result, nil
}

Y
yihao.dai 已提交
2745 2746 2747 2748 2749 2750 2751 2752
func (node *Proxy) DescribeAlias(ctx context.Context, request *milvuspb.DescribeAliasRequest) (*milvuspb.DescribeAliasResponse, error) {
	panic("TODO: implement me")
}

func (node *Proxy) ListAliases(ctx context.Context, request *milvuspb.ListAliasesRequest) (*milvuspb.ListAliasesResponse, error) {
	panic("TODO: implement me")
}

2753
// DropAlias alter the alias of collection.
Y
Yusup 已提交
2754 2755 2756 2757
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2758

E
Enwei Jiao 已提交
2759 2760
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropAlias")
	defer sp.End()
D
dragondriver 已提交
2761

Y
Yusup 已提交
2762 2763 2764 2765 2766 2767 2768
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
2769
	method := "DropAlias"
2770
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2771
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2772

2773
	log := log.Ctx(ctx).With(
D
dragondriver 已提交
2774 2775 2776 2777
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias))

2778 2779
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2780 2781 2782
	if err := node.sched.ddQueue.Enqueue(dat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2783
			zap.Error(err))
E
Enwei Jiao 已提交
2784
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2785

Y
Yusup 已提交
2786 2787 2788 2789 2790 2791
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2792 2793 2794
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", dat.BeginTs()),
2795
		zap.Uint64("EndTs", dat.EndTs()))
D
dragondriver 已提交
2796 2797 2798 2799

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2800
			zap.Error(err),
D
dragondriver 已提交
2801
			zap.Uint64("BeginTs", dat.BeginTs()),
2802
			zap.Uint64("EndTs", dat.EndTs()))
Y
Yusup 已提交
2803

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

Y
Yusup 已提交
2806 2807 2808 2809 2810 2811
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2812 2813 2814
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", dat.BeginTs()),
2815
		zap.Uint64("EndTs", dat.EndTs()))
D
dragondriver 已提交
2816

E
Enwei Jiao 已提交
2817 2818
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
2819 2820 2821
	return dat.result, nil
}

2822
// AlterAlias alter alias of collection.
Y
Yusup 已提交
2823 2824 2825 2826
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2827

E
Enwei Jiao 已提交
2828 2829
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-AlterAlias")
	defer sp.End()
D
dragondriver 已提交
2830

Y
Yusup 已提交
2831 2832 2833 2834 2835 2836 2837
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
2838
	method := "AlterAlias"
2839
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2840
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2841

2842
	log := log.Ctx(ctx).With(
D
dragondriver 已提交
2843 2844 2845 2846 2847
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

2848 2849
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2850 2851 2852
	if err := node.sched.ddQueue.Enqueue(aat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2853
			zap.Error(err))
E
Enwei Jiao 已提交
2854
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2855

Y
Yusup 已提交
2856 2857 2858 2859 2860 2861
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2862 2863 2864
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", aat.BeginTs()),
2865
		zap.Uint64("EndTs", aat.EndTs()))
D
dragondriver 已提交
2866 2867 2868 2869

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2870
			zap.Error(err),
D
dragondriver 已提交
2871
			zap.Uint64("BeginTs", aat.BeginTs()),
2872
			zap.Uint64("EndTs", aat.EndTs()))
Y
Yusup 已提交
2873

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

Y
Yusup 已提交
2876 2877 2878 2879 2880 2881
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2882 2883 2884
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", aat.BeginTs()),
2885
		zap.Uint64("EndTs", aat.EndTs()))
D
dragondriver 已提交
2886

E
Enwei Jiao 已提交
2887 2888
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
2889 2890 2891
	return aat.result, nil
}

2892
// CalcDistance calculates the distances between vectors.
2893
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
2894 2895 2896 2897 2898
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
2899

E
Enwei Jiao 已提交
2900 2901
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CalcDistance")
	defer sp.End()
2902

2903 2904
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
2905

2906 2907 2908 2909 2910
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
2911 2912
		}

2913
		qt := &queryTask{
2914 2915 2916
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
2917 2918
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Retrieve),
E
Enwei Jiao 已提交
2919
					commonpbutil.WithSourceID(paramtable.GetNodeID()),
2920
				),
E
Enwei Jiao 已提交
2921
				ReqID: paramtable.GetNodeID(),
2922
			},
2923 2924 2925 2926
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

2927
			queryShardPolicy: mergeRoundRobinPolicy,
2928
			shardMgr:         node.shardMgr,
2929 2930
		}

2931
		log := log.Ctx(ctx).With(
G
groot 已提交
2932 2933
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
2934
			zap.Any("OutputFields", queryRequest.OutputFields))
G
groot 已提交
2935

2936
		err := node.sched.dqQueue.Enqueue(qt)
2937
		if err != nil {
2938 2939
			log.Error("CalcDistance queryTask failed to enqueue",
				zap.Error(err))
2940

2941 2942 2943 2944 2945
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
2946
			}, err
2947
		}
2948

2949
		log.Debug("CalcDistance queryTask enqueued")
2950 2951 2952

		err = qt.WaitToFinish()
		if err != nil {
2953 2954
			log.Error("CalcDistance queryTask failed to WaitToFinish",
				zap.Error(err))
2955 2956 2957 2958 2959 2960

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
2961
			}, err
2962
		}
2963

2964
		log.Debug("CalcDistance queryTask Done")
2965 2966

		return &milvuspb.QueryResults{
2967 2968
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
2969 2970 2971
		}, nil
	}

G
groot 已提交
2972 2973
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
E
Enwei Jiao 已提交
2974
		traceID:   sp.SpanContext().TraceID().String(),
G
groot 已提交
2975
		queryFunc: query,
2976 2977
	}

G
groot 已提交
2978
	return task.Execute(ctx, request)
2979 2980
}

Y
yihao.dai 已提交
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
// FlushAll notifies Proxy to flush all collection's DML messages.
func (node *Proxy) FlushAll(ctx context.Context, _ *milvuspb.FlushAllRequest) (*milvuspb.FlushAllResponse, error) {
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-FlushAll")
	defer sp.End()

	resp := &milvuspb.FlushAllResponse{
		Status: &commonpb.Status{ErrorCode: commonpb.ErrorCode_UnexpectedError},
	}
	if !node.checkHealthy() {
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
	}
	log.Info(rpcReceived("FlushAll"))

	// Flush all collections to accelerate the flushAll progress
	showColRsp, err := node.ShowCollections(ctx, &milvuspb.ShowCollectionsRequest{
		Base: commonpbutil.NewMsgBase(commonpbutil.WithMsgType(commonpb.MsgType_ShowCollections)),
	})
	if err != nil {
		resp.Status = &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}
		log.Warn("FlushAll failed", zap.String("err", err.Error()))
		return resp, nil
	}
	if showColRsp.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
		log.Warn("FlushAll failed", zap.String("err", showColRsp.GetStatus().GetReason()))
		resp.Status = showColRsp.GetStatus()
		return resp, nil
	}
	flushRsp, err := node.Flush(ctx, &milvuspb.FlushRequest{
		Base:            commonpbutil.NewMsgBase(commonpbutil.WithMsgType(commonpb.MsgType_Flush)),
		CollectionNames: showColRsp.GetCollectionNames(),
	})
	if err != nil {
		resp.Status = &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}
		log.Warn("FlushAll failed", zap.String("err", err.Error()))
		return resp, nil
	}
	if flushRsp.GetStatus().GetErrorCode() != commonpb.ErrorCode_Success {
		log.Warn("FlushAll failed", zap.String("err", flushRsp.GetStatus().GetReason()))
		resp.Status = flushRsp.GetStatus()
		return resp, nil
	}

	// allocate current ts as FlushAllTs
	ts, err := node.tsoAllocator.AllocOne(ctx)
	if err != nil {
		log.Warn("FlushAll failed", zap.Error(err))
		resp.Status.Reason = err.Error()
		return resp, nil
	}

	resp.FlushAllTs = ts
	resp.Status.ErrorCode = commonpb.ErrorCode_Success

	log.Info(rpcDone("FlushAll"), zap.Uint64("FlushAllTs", ts),
		zap.Time("FlushAllTime", tsoutil.PhysicalTime(ts)))
	return resp, nil
}

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

3051
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3052
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
E
Enwei Jiao 已提交
3053 3054
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetPersistentSegmentInfo")
	defer sp.End()
3055 3056 3057

	log := log.Ctx(ctx)

D
dragondriver 已提交
3058
	log.Debug("GetPersistentSegmentInfo",
3059
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3060 3061 3062
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3063
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3064
		Status: &commonpb.Status{
3065
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3066 3067
		},
	}
3068 3069 3070 3071
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3072 3073
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3074
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3075
		metrics.TotalLabel).Inc()
3076 3077 3078

	// list segments
	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
X
XuanYang-cn 已提交
3079
	if err != nil {
E
Enwei Jiao 已提交
3080
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
		resp.Status.Reason = fmt.Errorf("getCollectionID failed, err:%w", err).Error()
		return resp, nil
	}

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

	// get Segment info
3098
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
3099 3100 3101
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3102
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3103
		),
3104
		SegmentIDs: getSegmentsByStatesResponse.Segments,
X
XuanYang-cn 已提交
3105 3106
	})
	if err != nil {
E
Enwei Jiao 已提交
3107
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3108
			metrics.FailLabel).Inc()
3109 3110
		log.Warn("GetPersistentSegmentInfo fail",
			zap.Error(err))
3111
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3112 3113
		return resp, nil
	}
3114 3115 3116
	log.Debug("GetPersistentSegmentInfo",
		zap.Int("len(infos)", len(infoResp.Infos)),
		zap.Any("status", infoResp.Status))
3117
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3118
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3119
			metrics.FailLabel).Inc()
X
XuanYang-cn 已提交
3120 3121 3122 3123 3124 3125
		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 已提交
3126
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3127 3128
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3129
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3130 3131 3132
			State:        info.State,
		}
	}
E
Enwei Jiao 已提交
3133
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3134
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
3135
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3136
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3137 3138 3139 3140
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3141
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3142
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
E
Enwei Jiao 已提交
3143 3144
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetQuerySegmentInfo")
	defer sp.End()
3145 3146 3147

	log := log.Ctx(ctx)

D
dragondriver 已提交
3148
	log.Debug("GetQuerySegmentInfo",
3149
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3150 3151 3152
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3153
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3154
		Status: &commonpb.Status{
3155
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3156 3157
		},
	}
3158 3159 3160 3161
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3162

3163 3164
	method := "GetQuerySegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3165
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3166 3167
		metrics.TotalLabel).Inc()

3168 3169
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
E
Enwei Jiao 已提交
3170
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3171 3172 3173
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3174
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
3175 3176 3177
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3178
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3179
		),
3180
		CollectionID: collID,
Z
zhenshan.cao 已提交
3181 3182
	})
	if err != nil {
E
Enwei Jiao 已提交
3183
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3184 3185
		log.Error("Failed to get segment info from QueryCoord",
			zap.Error(err))
Z
zhenshan.cao 已提交
3186 3187 3188
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3189 3190 3191
	log.Debug("GetQuerySegmentInfo",
		zap.Any("infos", infoResp.Infos),
		zap.Any("status", infoResp.Status))
3192
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3193
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3194 3195
		log.Error("Failed to get segment info from QueryCoord",
			zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
		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 已提交
3209
			State:        info.SegmentState,
3210
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3211 3212
		}
	}
3213

E
Enwei Jiao 已提交
3214 3215
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3216
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3217 3218 3219 3220
	resp.Infos = queryInfos
	return resp, nil
}

J
jingkl 已提交
3221
// Dummy handles dummy request
C
Cai Yudong 已提交
3222
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3223 3224 3225 3226 3227 3228
	failedResponse := &milvuspb.DummyResponse{
		Response: `{"status": "fail"}`,
	}

	// TODO(wxyu): change name RequestType to Request
	drt, err := parseDummyRequestType(req.RequestType)
3229

E
Enwei Jiao 已提交
3230 3231
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Dummy")
	defer sp.End()
3232 3233 3234

	log := log.Ctx(ctx)

3235
	if err != nil {
3236 3237
		log.Warn("Failed to parse dummy request type",
			zap.Error(err))
3238 3239 3240
		return failedResponse, nil
	}

3241 3242
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3243
		if err != nil {
3244 3245
			log.Warn("Failed to parse dummy query request",
				zap.Error(err))
3246 3247 3248
			return failedResponse, nil
		}

3249
		request := &milvuspb.QueryRequest{
3250 3251 3252
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3253
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3254 3255
		}

3256
		_, err = node.Query(ctx, request)
3257
		if err != nil {
3258 3259
			log.Warn("Failed to execute dummy query",
				zap.Error(err))
3260 3261
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3262 3263 3264 3265 3266 3267

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

3268 3269
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3270 3271
}

J
jingkl 已提交
3272
// RegisterLink registers a link
C
Cai Yudong 已提交
3273
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
3274
	code := node.stateCode.Load().(commonpb.StateCode)
3275

E
Enwei Jiao 已提交
3276 3277
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RegisterLink")
	defer sp.End()
3278 3279

	log := log.Ctx(ctx).With(
3280
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3281
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3282

3283 3284
	log.Debug("RegisterLink")

3285
	if code != commonpb.StateCode_Healthy {
3286 3287 3288
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3289
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3290
				Reason:    "proxy not healthy",
3291 3292 3293
			},
		}, nil
	}
E
Enwei Jiao 已提交
3294
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Inc()
3295 3296 3297
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3298
			ErrorCode: commonpb.ErrorCode_Success,
3299
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3300 3301 3302
		},
	}, nil
}
3303

3304
// GetMetrics gets the metrics of proxy
3305 3306
// 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) {
E
Enwei Jiao 已提交
3307 3308
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetMetrics")
	defer sp.End()
3309 3310 3311

	log := log.Ctx(ctx)

3312 3313
	log.RatedDebug(60, "Proxy.GetMetrics",
		zap.Int64("nodeID", paramtable.GetNodeID()),
3314 3315 3316
		zap.String("req", req.Request))

	if !node.checkHealthy() {
S
smellthemoon 已提交
3317
		err := merr.WrapErrServiceNotReady(fmt.Sprintf("proxy %d is unhealthy", paramtable.GetNodeID()))
3318
		log.Warn("Proxy.GetMetrics failed",
3319
			zap.Int64("nodeID", paramtable.GetNodeID()),
3320
			zap.String("req", req.Request),
S
smellthemoon 已提交
3321
			zap.Error(err))
3322 3323

		return &milvuspb.GetMetricsResponse{
S
smellthemoon 已提交
3324
			Status:   merr.Status(err),
3325 3326 3327 3328 3329 3330 3331
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
3332
			zap.Int64("nodeID", paramtable.GetNodeID()),
3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
			zap.String("req", req.Request),
			zap.Error(err))

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

3345 3346 3347
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3348
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3349
	)
3350
	if metricType == metricsinfo.SystemInfoMetrics {
3351 3352 3353
		metrics, err := node.metricsCacheManager.GetSystemInfoMetrics()
		if err != nil {
			metrics, err = getSystemInfoMetrics(ctx, req, node)
3354
		}
3355

3356 3357
		log.RatedDebug(60, "Proxy.GetMetrics",
			zap.Int64("nodeID", paramtable.GetNodeID()),
3358
			zap.String("req", req.Request),
3359
			zap.String("metricType", metricType),
3360 3361 3362
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3363 3364
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3365
		return metrics, nil
3366 3367
	}

3368 3369
	log.RatedWarn(60, "Proxy.GetMetrics failed, request metric type is not implemented yet",
		zap.Int64("nodeID", paramtable.GetNodeID()),
3370
		zap.String("req", req.Request),
3371
		zap.String("metricType", metricType))
3372 3373 3374 3375 3376 3377 3378 3379 3380 3381

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

3382 3383 3384
// 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) {
E
Enwei Jiao 已提交
3385 3386
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetProxyMetrics")
	defer sp.End()
3387 3388

	log := log.Ctx(ctx).With(
3389
		zap.Int64("nodeID", paramtable.GetNodeID()),
3390 3391
		zap.String("req", req.Request))

3392
	if !node.checkHealthy() {
S
smellthemoon 已提交
3393
		err := merr.WrapErrServiceNotReady(fmt.Sprintf("proxy %d is unhealthy", paramtable.GetNodeID()))
3394
		log.Warn("Proxy.GetProxyMetrics failed",
S
smellthemoon 已提交
3395
			zap.Error(err))
3396 3397

		return &milvuspb.GetMetricsResponse{
S
smellthemoon 已提交
3398
			Status: merr.Status(err),
3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetProxyMetrics failed to parse metric type",
			zap.Error(err))

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

3415 3416 3417
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3418
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3419
	)
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434

	if metricType == metricsinfo.SystemInfoMetrics {
		proxyMetrics, err := getProxyMetrics(ctx, req, node)
		if err != nil {
			log.Warn("Proxy.GetProxyMetrics failed to getProxyMetrics",
				zap.Error(err))

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

3435 3436
		//log.Debug("Proxy.GetProxyMetrics",
		//	zap.String("metricType", metricType))
3437 3438 3439 3440

		return proxyMetrics, nil
	}

J
Jiquan Long 已提交
3441
	log.Warn("Proxy.GetProxyMetrics failed, request metric type is not implemented yet",
3442
		zap.String("metricType", metricType))
3443 3444 3445 3446 3447 3448 3449 3450 3451

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

B
bigsheeper 已提交
3452 3453
// LoadBalance would do a load balancing operation between query nodes
func (node *Proxy) LoadBalance(ctx context.Context, req *milvuspb.LoadBalanceRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3454 3455
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-LoadBalance")
	defer sp.End()
3456 3457 3458

	log := log.Ctx(ctx)

B
bigsheeper 已提交
3459
	log.Debug("Proxy.LoadBalance",
E
Enwei Jiao 已提交
3460
		zap.Int64("proxy_id", paramtable.GetNodeID()),
B
bigsheeper 已提交
3461 3462 3463 3464 3465 3466 3467 3468 3469
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3470 3471 3472

	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	if err != nil {
J
Jiquan Long 已提交
3473
		log.Warn("failed to get collection id",
3474 3475
			zap.String("collection name", req.GetCollectionName()),
			zap.Error(err))
3476 3477 3478
		status.Reason = err.Error()
		return status, nil
	}
B
bigsheeper 已提交
3479
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
3480 3481 3482
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_LoadBalanceSegments),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3483
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3484
		),
B
bigsheeper 已提交
3485 3486
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3487
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3488
		SealedSegmentIDs: req.SealedSegmentIDs,
3489
		CollectionID:     collectionID,
B
bigsheeper 已提交
3490 3491
	})
	if err != nil {
J
Jiquan Long 已提交
3492
		log.Warn("Failed to LoadBalance from Query Coordinator",
3493 3494
			zap.Any("req", req),
			zap.Error(err))
B
bigsheeper 已提交
3495 3496 3497 3498
		status.Reason = err.Error()
		return status, nil
	}
	if infoResp.ErrorCode != commonpb.ErrorCode_Success {
J
Jiquan Long 已提交
3499
		log.Warn("Failed to LoadBalance from Query Coordinator",
3500
			zap.String("errMsg", infoResp.Reason))
B
bigsheeper 已提交
3501 3502 3503
		status.Reason = infoResp.Reason
		return status, nil
	}
3504 3505 3506
	log.Debug("LoadBalance Done",
		zap.Any("req", req),
		zap.Any("status", infoResp))
B
bigsheeper 已提交
3507 3508 3509 3510
	status.ErrorCode = commonpb.ErrorCode_Success
	return status, nil
}

3511 3512
// GetReplicas gets replica info
func (node *Proxy) GetReplicas(ctx context.Context, req *milvuspb.GetReplicasRequest) (*milvuspb.GetReplicasResponse, error) {
E
Enwei Jiao 已提交
3513 3514
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetReplicas")
	defer sp.End()
3515 3516 3517 3518 3519 3520

	log := log.Ctx(ctx)

	log.Debug("received get replicas request",
		zap.Int64("collection", req.GetCollectionID()),
		zap.Bool("with shard nodes", req.GetWithShardNodes()))
3521 3522 3523 3524 3525 3526
	resp := &milvuspb.GetReplicasResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

S
smellthemoon 已提交
3527 3528
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_GetReplicas),
E
Enwei Jiao 已提交
3529
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
S
smellthemoon 已提交
3530
	)
3531

W
wei liu 已提交
3532 3533 3534 3535
	if req.GetCollectionName() != "" {
		req.CollectionID, _ = globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	}

3536 3537
	resp, err := node.queryCoord.GetReplicas(ctx, req)
	if err != nil {
3538 3539
		log.Error("Failed to get replicas from Query Coordinator",
			zap.Error(err))
3540 3541 3542 3543
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3544 3545 3546
	log.Debug("received get replicas response",
		zap.Any("resp", resp),
		zap.Error(err))
3547 3548 3549
	return resp, nil
}

3550
// GetCompactionState gets the compaction state of multiple segments
3551
func (node *Proxy) GetCompactionState(ctx context.Context, req *milvuspb.GetCompactionStateRequest) (*milvuspb.GetCompactionStateResponse, error) {
E
Enwei Jiao 已提交
3552 3553
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetCompactionState")
	defer sp.End()
3554 3555 3556 3557 3558

	log := log.Ctx(ctx).With(
		zap.Int64("compactionID", req.GetCompactionID()))

	log.Debug("received GetCompactionState request")
3559 3560 3561 3562 3563 3564 3565
	resp := &milvuspb.GetCompactionStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionState(ctx, req)
3566 3567 3568
	log.Debug("received GetCompactionState response",
		zap.Any("resp", resp),
		zap.Error(err))
3569 3570 3571
	return resp, err
}

3572
// ManualCompaction invokes compaction on specified collection
3573
func (node *Proxy) ManualCompaction(ctx context.Context, req *milvuspb.ManualCompactionRequest) (*milvuspb.ManualCompactionResponse, error) {
E
Enwei Jiao 已提交
3574 3575
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ManualCompaction")
	defer sp.End()
3576 3577 3578 3579 3580

	log := log.Ctx(ctx).With(
		zap.Int64("collectionID", req.GetCollectionID()))

	log.Info("received ManualCompaction request")
3581 3582 3583 3584 3585 3586 3587
	resp := &milvuspb.ManualCompactionResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.ManualCompaction(ctx, req)
3588 3589 3590
	log.Info("received ManualCompaction response",
		zap.Any("resp", resp),
		zap.Error(err))
3591 3592 3593
	return resp, err
}

3594
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3595
func (node *Proxy) GetCompactionStateWithPlans(ctx context.Context, req *milvuspb.GetCompactionPlansRequest) (*milvuspb.GetCompactionPlansResponse, error) {
E
Enwei Jiao 已提交
3596 3597
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetCompactionStateWithPlans")
	defer sp.End()
3598 3599 3600 3601 3602

	log := log.Ctx(ctx).With(
		zap.Int64("compactionID", req.GetCompactionID()))

	log.Debug("received GetCompactionStateWithPlans request")
3603 3604 3605 3606 3607 3608 3609
	resp := &milvuspb.GetCompactionPlansResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionStateWithPlans(ctx, req)
3610 3611 3612
	log.Debug("received GetCompactionStateWithPlans response",
		zap.Any("resp", resp),
		zap.Error(err))
3613 3614 3615
	return resp, err
}

B
Bingyi Sun 已提交
3616 3617
// GetFlushState gets the flush state of multiple segments
func (node *Proxy) GetFlushState(ctx context.Context, req *milvuspb.GetFlushStateRequest) (*milvuspb.GetFlushStateResponse, error) {
E
Enwei Jiao 已提交
3618 3619
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetFlushState")
	defer sp.End()
3620 3621 3622 3623 3624

	log := log.Ctx(ctx)

	log.Debug("received get flush state request",
		zap.Any("request", req))
3625
	var err error
B
Bingyi Sun 已提交
3626 3627 3628
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
J
Jiquan Long 已提交
3629
		log.Warn("unable to get flush state because of closed server")
B
Bingyi Sun 已提交
3630 3631 3632
		return resp, nil
	}

3633
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3634
	if err != nil {
3635 3636
		log.Warn("failed to get flush state response",
			zap.Error(err))
X
Xiaofan 已提交
3637 3638
		return nil, err
	}
3639 3640
	log.Debug("received get flush state response",
		zap.Any("response", resp))
B
Bingyi Sun 已提交
3641 3642 3643
	return resp, err
}

Y
yihao.dai 已提交
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672
// GetFlushAllState checks if all DML messages before `FlushAllTs` have been flushed.
func (node *Proxy) GetFlushAllState(ctx context.Context, req *milvuspb.GetFlushAllStateRequest) (*milvuspb.GetFlushAllStateResponse, error) {
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetFlushAllState")
	defer sp.End()
	log := log.Ctx(ctx).With(zap.Uint64("FlushAllTs", req.GetFlushAllTs()),
		zap.Time("FlushAllTime", tsoutil.PhysicalTime(req.GetFlushAllTs())))
	log.Debug("receive GetFlushAllState request")

	var err error
	resp := &milvuspb.GetFlushAllStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Warn("GetFlushAllState failed, closed server")
		return resp, nil
	}

	resp, err = node.dataCoord.GetFlushAllState(ctx, req)
	if err != nil {
		resp.Status = &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}
		log.Warn("GetFlushAllState failed", zap.String("err", err.Error()))
		return resp, nil
	}
	log.Debug("GetFlushAllState done", zap.Bool("flushed", resp.GetFlushed()))
	return resp, err
}

C
Cai Yudong 已提交
3673 3674
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3675 3676
	code := node.stateCode.Load().(commonpb.StateCode)
	return code == commonpb.StateCode_Healthy
3677 3678
}

3679 3680 3681
func (node *Proxy) checkHealthyAndReturnCode() (commonpb.StateCode, bool) {
	code := node.stateCode.Load().(commonpb.StateCode)
	return code, code == commonpb.StateCode_Healthy
3682 3683
}

3684
// unhealthyStatus returns the proxy not healthy status
3685 3686 3687
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3688
		Reason:    "proxy not healthy",
3689 3690
	}
}
G
groot 已提交
3691 3692 3693

// 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) {
E
Enwei Jiao 已提交
3694 3695
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Import")
	defer sp.End()
3696 3697 3698

	log := log.Ctx(ctx)

3699 3700
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
G
groot 已提交
3701 3702
		zap.String("partition name", req.GetPartitionName()),
		zap.Strings("files", req.GetFiles()))
3703 3704 3705 3706 3707 3708
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3709 3710 3711 3712
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3713

3714 3715
	err := importutil.ValidateOptions(req.GetOptions())
	if err != nil {
3716 3717
		log.Error("failed to execute import request",
			zap.Error(err))
3718 3719 3720 3721 3722
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = "request options is not illegal    \n" + err.Error() + "    \nIllegal option format    \n" + importutil.OptionFormat
		return resp, nil
	}

3723 3724
	method := "Import"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3725
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3726 3727
		metrics.TotalLabel).Inc()

3728
	// Call rootCoord to finish import.
3729 3730
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
E
Enwei Jiao 已提交
3731
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3732 3733
		log.Error("failed to execute bulk insert request",
			zap.Error(err))
3734 3735 3736 3737
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3738

E
Enwei Jiao 已提交
3739 3740
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3741
	return respFromRC, nil
G
groot 已提交
3742 3743
}

3744
// GetImportState checks import task state from RootCoord.
G
groot 已提交
3745
func (node *Proxy) GetImportState(ctx context.Context, req *milvuspb.GetImportStateRequest) (*milvuspb.GetImportStateResponse, error) {
E
Enwei Jiao 已提交
3746 3747
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetImportState")
	defer sp.End()
3748 3749 3750 3751 3752

	log := log.Ctx(ctx)

	log.Debug("received get import state request",
		zap.Int64("taskID", req.GetTask()))
G
groot 已提交
3753 3754 3755 3756 3757
	resp := &milvuspb.GetImportStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3758 3759
	method := "GetImportState"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3760
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3761
		metrics.TotalLabel).Inc()
G
groot 已提交
3762 3763

	resp, err := node.rootCoord.GetImportState(ctx, req)
3764
	if err != nil {
E
Enwei Jiao 已提交
3765
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3766 3767
		log.Error("failed to execute get import state",
			zap.Error(err))
3768 3769 3770 3771 3772
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}

3773 3774 3775
	log.Debug("successfully received get import state response",
		zap.Int64("taskID", req.GetTask()),
		zap.Any("resp", resp), zap.Error(err))
E
Enwei Jiao 已提交
3776 3777
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3778
	return resp, nil
G
groot 已提交
3779 3780 3781 3782
}

// ListImportTasks get id array of all import tasks from rootcoord
func (node *Proxy) ListImportTasks(ctx context.Context, req *milvuspb.ListImportTasksRequest) (*milvuspb.ListImportTasksResponse, error) {
E
Enwei Jiao 已提交
3783 3784
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ListImportTasks")
	defer sp.End()
3785 3786 3787

	log := log.Ctx(ctx)

J
Jiquan Long 已提交
3788
	log.Debug("received list import tasks request")
G
groot 已提交
3789 3790 3791 3792 3793
	resp := &milvuspb.ListImportTasksResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3794 3795
	method := "ListImportTasks"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3796
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3797
		metrics.TotalLabel).Inc()
G
groot 已提交
3798
	resp, err := node.rootCoord.ListImportTasks(ctx, req)
3799
	if err != nil {
E
Enwei Jiao 已提交
3800
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3801 3802
		log.Error("failed to execute list import tasks",
			zap.Error(err))
3803 3804
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
X
XuanYang-cn 已提交
3805 3806 3807
		return resp, nil
	}

3808 3809 3810
	log.Debug("successfully received list import tasks response",
		zap.String("collection", req.CollectionName),
		zap.Any("tasks", resp.Tasks))
E
Enwei Jiao 已提交
3811 3812
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
X
XuanYang-cn 已提交
3813 3814 3815
	return resp, err
}

3816 3817
// InvalidateCredentialCache invalidate the credential cache of specified username.
func (node *Proxy) InvalidateCredentialCache(ctx context.Context, request *proxypb.InvalidateCredCacheRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3818 3819
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-InvalidateCredentialCache")
	defer sp.End()
3820 3821

	log := log.Ctx(ctx).With(
3822 3823
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
3824 3825

	log.Debug("received request to invalidate credential cache")
3826
	if !node.checkHealthy() {
3827
		return unhealthyStatus(), nil
3828
	}
3829 3830 3831 3832 3833

	username := request.Username
	if globalMetaCache != nil {
		globalMetaCache.RemoveCredential(username) // no need to return error, though credential may be not cached
	}
3834
	log.Debug("complete to invalidate credential cache")
3835 3836 3837 3838 3839 3840 3841 3842 3843

	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) {
E
Enwei Jiao 已提交
3844 3845
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-UpdateCredentialCache")
	defer sp.End()
3846 3847

	log := log.Ctx(ctx).With(
3848 3849
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
3850 3851

	log.Debug("received request to update credential cache")
3852
	if !node.checkHealthy() {
3853
		return unhealthyStatus(), nil
3854
	}
3855 3856

	credInfo := &internalpb.CredentialInfo{
3857 3858
		Username:       request.Username,
		Sha256Password: request.Password,
3859 3860 3861 3862
	}
	if globalMetaCache != nil {
		globalMetaCache.UpdateCredential(credInfo) // no need to return error, though credential may be not cached
	}
3863
	log.Debug("complete to update credential cache")
3864 3865 3866 3867 3868 3869 3870 3871

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

func (node *Proxy) CreateCredential(ctx context.Context, req *milvuspb.CreateCredentialRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3872 3873
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateCredential")
	defer sp.End()
3874 3875 3876 3877 3878 3879

	log := log.Ctx(ctx).With(
		zap.String("username", req.Username))

	log.Debug("CreateCredential",
		zap.String("role", typeutil.ProxyRole))
3880
	if !node.checkHealthy() {
3881
		return unhealthyStatus(), nil
3882
	}
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892
	// 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 {
3893 3894
		log.Error("decode password fail",
			zap.Error(err))
3895 3896 3897 3898 3899 3900
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "decode password fail key:" + req.Username,
		}, nil
	}
	if err = ValidatePassword(rawPassword); err != nil {
3901 3902
		log.Error("illegal password",
			zap.Error(err))
3903 3904 3905 3906 3907 3908 3909
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
	encryptedPassword, err := crypto.PasswordEncrypt(rawPassword)
	if err != nil {
3910 3911
		log.Error("encrypt password fail",
			zap.Error(err))
3912 3913 3914 3915 3916
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "encrypt password fail key:" + req.Username,
		}, nil
	}
3917

3918 3919 3920
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
3921
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
3922 3923 3924
	}
	result, err := node.rootCoord.CreateCredential(ctx, credInfo)
	if err != nil { // for error like conntext timeout etc.
3925 3926
		log.Error("create credential fail",
			zap.Error(err))
3927 3928 3929 3930 3931 3932 3933 3934
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}
	return result, err
}

C
codeman 已提交
3935
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3936 3937
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-UpdateCredential")
	defer sp.End()
3938 3939 3940 3941 3942 3943

	log := log.Ctx(ctx).With(
		zap.String("username", req.Username))

	log.Debug("UpdateCredential",
		zap.String("role", typeutil.ProxyRole))
3944
	if !node.checkHealthy() {
3945
		return unhealthyStatus(), nil
3946
	}
C
codeman 已提交
3947 3948
	rawOldPassword, err := crypto.Base64Decode(req.OldPassword)
	if err != nil {
3949 3950
		log.Error("decode old password fail",
			zap.Error(err))
C
codeman 已提交
3951 3952 3953 3954 3955 3956
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode old password fail when updating:" + req.Username,
		}, nil
	}
	rawNewPassword, err := crypto.Base64Decode(req.NewPassword)
3957
	if err != nil {
3958 3959
		log.Error("decode password fail",
			zap.Error(err))
3960 3961 3962 3963 3964
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
3965 3966
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
3967 3968
		log.Error("illegal password",
			zap.Error(err))
3969 3970 3971 3972 3973
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
3974 3975

	if !passwordVerify(ctx, req.Username, rawOldPassword, globalMetaCache) {
C
codeman 已提交
3976 3977 3978 3979 3980 3981 3982
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
3983
	if err != nil {
3984 3985
		log.Error("encrypt password fail",
			zap.Error(err))
3986 3987 3988 3989 3990
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "encrypt password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
3991
	updateCredReq := &internalpb.CredentialInfo{
3992
		Username:          req.Username,
3993
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
3994 3995
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
3996
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
3997
	if err != nil { // for error like conntext timeout etc.
3998 3999
		log.Error("update credential fail",
			zap.Error(err))
4000 4001 4002 4003 4004 4005 4006 4007 4008
		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) {
E
Enwei Jiao 已提交
4009 4010
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DeleteCredential")
	defer sp.End()
4011 4012 4013 4014 4015 4016

	log := log.Ctx(ctx).With(
		zap.String("username", req.Username))

	log.Debug("DeleteCredential",
		zap.String("role", typeutil.ProxyRole))
4017
	if !node.checkHealthy() {
4018
		return unhealthyStatus(), nil
4019 4020
	}

4021 4022 4023 4024 4025 4026
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
4027 4028
	result, err := node.rootCoord.DeleteCredential(ctx, req)
	if err != nil { // for error like conntext timeout etc.
4029 4030
		log.Error("delete credential fail",
			zap.Error(err))
4031 4032 4033 4034 4035 4036 4037 4038 4039
		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) {
E
Enwei Jiao 已提交
4040 4041
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ListCredUsers")
	defer sp.End()
4042 4043 4044 4045 4046

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole))

	log.Debug("ListCredUsers")
4047
	if !node.checkHealthy() {
4048
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
4049
	}
4050
	rootCoordReq := &milvuspb.ListCredUsersRequest{
4051 4052 4053
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_ListCredUsernames),
		),
4054 4055
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067
	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,
		},
4068
		Usernames: resp.Usernames,
4069 4070
	}, nil
}
4071

4072
func (node *Proxy) CreateRole(ctx context.Context, req *milvuspb.CreateRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4073 4074
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateRole")
	defer sp.End()
4075 4076 4077 4078 4079

	log := log.Ctx(ctx)

	log.Debug("CreateRole",
		zap.Any("req", req))
4080
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4081
		return errorutil.UnhealthyStatus(code), nil
4082 4083 4084 4085 4086 4087 4088 4089 4090 4091
	}

	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(),
4092
		}, nil
4093 4094 4095 4096
	}

	result, err := node.rootCoord.CreateRole(ctx, req)
	if err != nil {
4097 4098
		log.Error("fail to create role",
			zap.Error(err))
4099 4100 4101
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4102
		}, nil
4103 4104
	}
	return result, nil
4105 4106
}

4107
func (node *Proxy) DropRole(ctx context.Context, req *milvuspb.DropRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4108 4109
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropRole")
	defer sp.End()
4110 4111 4112 4113 4114

	log := log.Ctx(ctx)

	log.Debug("DropRole",
		zap.Any("req", req))
4115
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4116
		return errorutil.UnhealthyStatus(code), nil
4117 4118 4119 4120 4121
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4122
		}, nil
4123
	}
4124 4125 4126 4127 4128
	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,
4129
		}, nil
4130
	}
4131 4132
	result, err := node.rootCoord.DropRole(ctx, req)
	if err != nil {
4133 4134 4135
		log.Error("fail to drop role",
			zap.String("role_name", req.RoleName),
			zap.Error(err))
4136 4137 4138
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4139
		}, nil
4140 4141
	}
	return result, nil
4142 4143
}

4144
func (node *Proxy) OperateUserRole(ctx context.Context, req *milvuspb.OperateUserRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4145 4146
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-OperateUserRole")
	defer sp.End()
4147 4148 4149 4150 4151

	log := log.Ctx(ctx)

	log.Debug("OperateUserRole",
		zap.Any("req", req))
4152
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4153
		return errorutil.UnhealthyStatus(code), nil
4154 4155 4156 4157 4158
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4159
		}, nil
4160 4161 4162 4163 4164
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4165
		}, nil
4166 4167 4168 4169
	}

	result, err := node.rootCoord.OperateUserRole(ctx, req)
	if err != nil {
4170 4171
		logger.Error("fail to operate user role",
			zap.Error(err))
4172 4173 4174
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4175
		}, nil
4176 4177
	}
	return result, nil
4178 4179
}

4180
func (node *Proxy) SelectRole(ctx context.Context, req *milvuspb.SelectRoleRequest) (*milvuspb.SelectRoleResponse, error) {
E
Enwei Jiao 已提交
4181 4182
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectRole")
	defer sp.End()
4183 4184 4185 4186

	log := log.Ctx(ctx)

	log.Debug("SelectRole", zap.Any("req", req))
4187
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4188
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4189 4190 4191 4192 4193 4194 4195 4196 4197
	}

	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(),
				},
4198
			}, nil
4199 4200 4201 4202 4203
		}
	}

	result, err := node.rootCoord.SelectRole(ctx, req)
	if err != nil {
4204 4205
		log.Error("fail to select role",
			zap.Error(err))
4206 4207 4208 4209 4210
		return &milvuspb.SelectRoleResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4211
		}, nil
4212 4213
	}
	return result, nil
4214 4215
}

4216
func (node *Proxy) SelectUser(ctx context.Context, req *milvuspb.SelectUserRequest) (*milvuspb.SelectUserResponse, error) {
E
Enwei Jiao 已提交
4217 4218
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectUser")
	defer sp.End()
4219 4220 4221 4222 4223

	log := log.Ctx(ctx)

	log.Debug("SelectUser",
		zap.Any("req", req))
4224
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4225
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4226 4227 4228 4229 4230 4231 4232 4233 4234
	}

	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(),
				},
4235
			}, nil
4236 4237 4238 4239 4240
		}
	}

	result, err := node.rootCoord.SelectUser(ctx, req)
	if err != nil {
4241 4242
		log.Error("fail to select user",
			zap.Error(err))
4243 4244 4245 4246 4247
		return &milvuspb.SelectUserResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4248
		}, nil
4249 4250
	}
	return result, nil
4251 4252
}

4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282
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
4283 4284
}

4285
func (node *Proxy) OperatePrivilege(ctx context.Context, req *milvuspb.OperatePrivilegeRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4286 4287
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-OperatePrivilege")
	defer sp.End()
4288 4289 4290 4291 4292

	log := log.Ctx(ctx)

	log.Debug("OperatePrivilege",
		zap.Any("req", req))
4293
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4294
		return errorutil.UnhealthyStatus(code), nil
4295 4296 4297 4298 4299
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4300
		}, nil
4301 4302 4303 4304 4305 4306
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4307
		}, nil
4308 4309 4310 4311
	}
	req.Entity.Grantor.User = &milvuspb.UserEntity{Name: curUser}
	result, err := node.rootCoord.OperatePrivilege(ctx, req)
	if err != nil {
4312 4313
		log.Error("fail to operate privilege",
			zap.Error(err))
4314 4315 4316
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4317
		}, nil
4318 4319
	}
	return result, nil
4320 4321
}

4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348
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) {
E
Enwei Jiao 已提交
4349 4350
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectGrant")
	defer sp.End()
4351 4352 4353 4354 4355

	log := log.Ctx(ctx)

	log.Debug("SelectGrant",
		zap.Any("req", req))
4356
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4357
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4358 4359 4360 4361 4362 4363 4364 4365
	}

	if err := node.validGrantParams(req); err != nil {
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_IllegalArgument,
				Reason:    err.Error(),
			},
4366
		}, nil
4367 4368 4369 4370
	}

	result, err := node.rootCoord.SelectGrant(ctx, req)
	if err != nil {
4371 4372
		log.Error("fail to select grant",
			zap.Error(err))
4373 4374 4375 4376 4377
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4378
		}, nil
4379 4380 4381 4382 4383
	}
	return result, nil
}

func (node *Proxy) RefreshPolicyInfoCache(ctx context.Context, req *proxypb.RefreshPolicyInfoCacheRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4384 4385
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RefreshPolicyInfoCache")
	defer sp.End()
4386 4387 4388 4389 4390

	log := log.Ctx(ctx)

	log.Debug("RefreshPrivilegeInfoCache",
		zap.Any("req", req))
4391 4392 4393 4394 4395 4396 4397 4398 4399 4400
	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 {
4401 4402
			log.Error("fail to refresh policy info",
				zap.Error(err))
4403 4404 4405 4406 4407 4408
			return &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_RefreshPolicyInfoCacheFailure,
				Reason:    err.Error(),
			}, err
		}
	}
4409
	log.Debug("RefreshPrivilegeInfoCache success")
4410 4411 4412 4413

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
	}, nil
4414
}
4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431

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

	err := node.multiRateLimiter.globalRateLimiter.setRates(request.GetRates())
	// TODO: set multiple rate limiter rates
	if err != nil {
		resp.Reason = err.Error()
		return resp, nil
	}
4432
	node.multiRateLimiter.SetQuotaStates(request.GetStates(), request.GetCodes())
4433 4434 4435 4436 4437 4438 4439
	rateStrs := lo.FilterMap(request.GetRates(), func(r *internalpb.Rate, _ int) (string, bool) {
		return fmt.Sprintf("rateType:%s, rate:%s", r.GetRt().String(), ratelimitutil.Limit(r.GetR()).String()),
			ratelimitutil.Limit(r.GetR()) != ratelimitutil.Inf
	})
	if len(rateStrs) > 0 {
		log.RatedInfo(30, "current rates in proxy", zap.Int64("proxyNodeID", paramtable.GetNodeID()), zap.Strings("rates", rateStrs))
	}
4440 4441
	if len(request.GetStates()) != 0 {
		for i := range request.GetStates() {
4442
			log.Warn("Proxy set quota states", zap.String("state", request.GetStates()[i].String()), zap.String("reason", request.GetCodes()[i].String()))
4443 4444
		}
	}
4445 4446 4447
	resp.ErrorCode = commonpb.ErrorCode_Success
	return resp, nil
}
4448 4449 4450 4451

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")
4452 4453 4454 4455
		return &milvuspb.CheckHealthResponse{
			Status:    unhealthyStatus(),
			IsHealthy: false,
			Reasons:   []string{reason}}, nil
4456 4457 4458 4459 4460 4461 4462 4463 4464 4465
	}

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

E
Enwei Jiao 已提交
4466 4467
		ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RefreshPolicyInfoCache")
		defer sp.End()
4468 4469 4470

		log := log.Ctx(ctx).With(zap.String("role", role))

4471
		if err != nil {
4472 4473
			log.Warn("check health fail",
				zap.Error(err))
4474 4475 4476 4477 4478
			errReasons = append(errReasons, fmt.Sprintf("check health fail for %s", role))
			return err
		}

		if !resp.IsHealthy {
4479
			log.Warn("check health fail")
4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502
			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)
	})

	err := group.Wait()
	if err != nil || len(errReasons) != 0 {
		return &milvuspb.CheckHealthResponse{
4503 4504 4505
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_Success,
			},
4506 4507 4508 4509 4510
			IsHealthy: false,
			Reasons:   errReasons,
		}, nil
	}

4511
	states, reasons := node.multiRateLimiter.GetQuotaStates()
4512 4513 4514 4515 4516
	return &milvuspb.CheckHealthResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
4517 4518 4519
		QuotaStates: states,
		Reasons:     reasons,
		IsHealthy:   true,
4520
	}, nil
4521
}
W
wei liu 已提交
4522

J
jaime 已提交
4523
func (node *Proxy) RenameCollection(ctx context.Context, req *milvuspb.RenameCollectionRequest) (*commonpb.Status, error) {
4524
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RenameCollection")
J
jaime 已提交
4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
	defer sp.End()

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
		zap.String("oldName", req.GetOldName()),
		zap.String("newName", req.GetNewName()))

	log.Info("received rename collection request")
	var err error

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

	if err := validateCollectionName(req.GetNewName()); err != nil {
		log.Warn("validate new collection name fail", zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalCollectionName,
			Reason:    err.Error(),
J
jaime 已提交
4544
		}, nil
J
jaime 已提交
4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
	}

	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_RenameCollection),
		commonpbutil.WithMsgID(0),
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
	)
	resp, err := node.rootCoord.RenameCollection(ctx, req)
	if err != nil {
		log.Warn("failed to rename collection", zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, err
	}

	return resp, nil
}

W
wei liu 已提交
4564
func (node *Proxy) CreateResourceGroup(ctx context.Context, request *milvuspb.CreateResourceGroupRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4565 4566 4567 4568
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

W
wei liu 已提交
4569 4570 4571 4572 4573 4574 4575 4576
	method := "CreateResourceGroup"
	if err := ValidateResourceGroupName(request.GetResourceGroup()); err != nil {
		log.Warn("CreateResourceGroup failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

W
wei liu 已提交
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateResourceGroup")
	defer sp.End()
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &CreateResourceGroupTask{
		ctx:                        ctx,
		Condition:                  NewTaskCondition(ctx),
		CreateResourceGroupRequest: request,
		queryCoord:                 node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("CreateResourceGroup received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("CreateResourceGroup failed to enqueue",
			zap.Error(err))
W
wei liu 已提交
4598
		return getErrResponse(err, method), nil
W
wei liu 已提交
4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609
	}

	log.Debug("CreateResourceGroup enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("CreateResourceGroup failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
W
wei liu 已提交
4610
		return getErrResponse(err, method), nil
W
wei liu 已提交
4611 4612 4613 4614 4615 4616 4617 4618 4619 4620
	}

	log.Debug("CreateResourceGroup done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4621 4622
}

W
wei liu 已提交
4623 4624 4625 4626
func getErrResponse(err error, method string) *commonpb.Status {
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()

	return &commonpb.Status{
W
wei liu 已提交
4627
		ErrorCode: commonpb.ErrorCode_IllegalArgument,
W
wei liu 已提交
4628 4629 4630 4631
		Reason:    err.Error(),
	}
}

W
wei liu 已提交
4632
func (node *Proxy) DropResourceGroup(ctx context.Context, request *milvuspb.DropResourceGroupRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4633 4634 4635 4636
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

W
wei liu 已提交
4637
	method := "DropResourceGroup"
W
wei liu 已提交
4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropResourceGroup")
	defer sp.End()
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &DropResourceGroupTask{
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		DropResourceGroupRequest: request,
		queryCoord:               node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("DropResourceGroup received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("DropResourceGroup failed to enqueue",
			zap.Error(err))

W
wei liu 已提交
4660
		return getErrResponse(err, method), nil
W
wei liu 已提交
4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671
	}

	log.Debug("DropResourceGroup enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("DropResourceGroup failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
W
wei liu 已提交
4672
		return getErrResponse(err, method), nil
W
wei liu 已提交
4673 4674 4675 4676 4677 4678 4679 4680 4681 4682
	}

	log.Debug("DropResourceGroup done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4683 4684 4685
}

func (node *Proxy) TransferNode(ctx context.Context, request *milvuspb.TransferNodeRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4686 4687 4688 4689
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

W
wei liu 已提交
4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704
	method := "TransferNode"
	if err := ValidateResourceGroupName(request.GetSourceResourceGroup()); err != nil {
		log.Warn("TransferNode failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

	if err := ValidateResourceGroupName(request.GetTargetResourceGroup()); err != nil {
		log.Warn("TransferNode failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

W
wei liu 已提交
4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-TransferNode")
	defer sp.End()
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &TransferNodeTask{
		ctx:                 ctx,
		Condition:           NewTaskCondition(ctx),
		TransferNodeRequest: request,
		queryCoord:          node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("TransferNode received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("TransferNode failed to enqueue",
			zap.Error(err))

W
wei liu 已提交
4727
		return getErrResponse(err, method), nil
W
wei liu 已提交
4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
	}

	log.Debug("TransferNode enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("TransferNode failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
W
wei liu 已提交
4739
		return getErrResponse(err, method), nil
W
wei liu 已提交
4740 4741 4742 4743 4744 4745 4746 4747 4748 4749
	}

	log.Debug("TransferNode done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4750 4751 4752
}

func (node *Proxy) TransferReplica(ctx context.Context, request *milvuspb.TransferReplicaRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4753 4754 4755
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
W
wei liu 已提交
4756

W
wei liu 已提交
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771
	method := "TransferReplica"
	if err := ValidateResourceGroupName(request.GetSourceResourceGroup()); err != nil {
		log.Warn("TransferReplica failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

	if err := ValidateResourceGroupName(request.GetTargetResourceGroup()); err != nil {
		log.Warn("TransferReplica failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

W
wei liu 已提交
4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-TransferReplica")
	defer sp.End()
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &TransferReplicaTask{
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		TransferReplicaRequest: request,
		queryCoord:             node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("TransferReplica received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("TransferReplica failed to enqueue",
			zap.Error(err))

W
wei liu 已提交
4794
		return getErrResponse(err, method), nil
W
wei liu 已提交
4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805
	}

	log.Debug("TransferReplica enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("TransferReplica failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
W
wei liu 已提交
4806
		return getErrResponse(err, method), nil
W
wei liu 已提交
4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
	}

	log.Debug("TransferReplica done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4817 4818
}

W
wei liu 已提交
4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885
func (node *Proxy) ListResourceGroups(ctx context.Context, request *milvuspb.ListResourceGroupsRequest) (*milvuspb.ListResourceGroupsResponse, error) {
	if !node.checkHealthy() {
		return &milvuspb.ListResourceGroupsResponse{
			Status: unhealthyStatus(),
		}, nil
	}

	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ListResourceGroups")
	defer sp.End()
	method := "ListResourceGroups"
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &ListResourceGroupsTask{
		ctx:                       ctx,
		Condition:                 NewTaskCondition(ctx),
		ListResourceGroupsRequest: request,
		queryCoord:                node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("ListResourceGroups received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("ListResourceGroups failed to enqueue",
			zap.Error(err))

		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
		return &milvuspb.ListResourceGroupsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

	log.Debug("ListResourceGroups enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("ListResourceGroups failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
		return &milvuspb.ListResourceGroupsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

	log.Debug("ListResourceGroups done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4886 4887 4888
}

func (node *Proxy) DescribeResourceGroup(ctx context.Context, request *milvuspb.DescribeResourceGroupRequest) (*milvuspb.DescribeResourceGroupResponse, error) {
W
wei liu 已提交
4889 4890 4891 4892 4893 4894
	if !node.checkHealthy() {
		return &milvuspb.DescribeResourceGroupResponse{
			Status: unhealthyStatus(),
		}, nil
	}

W
wei liu 已提交
4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906
	method := "DescribeResourceGroup"
	GetErrResponse := func(err error) *milvuspb.DescribeResourceGroupResponse {
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()

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

W
wei liu 已提交
4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DescribeResourceGroup")
	defer sp.End()
	tr := timerecord.NewTimeRecorder(method)
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
	t := &DescribeResourceGroupTask{
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		DescribeResourceGroupRequest: request,
		queryCoord:                   node.queryCoord,
	}

	log := log.Ctx(ctx).With(
		zap.String("role", typeutil.ProxyRole),
	)

	log.Debug("DescribeResourceGroup received")

	if err := node.sched.ddQueue.Enqueue(t); err != nil {
		log.Warn("DescribeResourceGroup failed to enqueue",
			zap.Error(err))

W
wei liu 已提交
4929
		return GetErrResponse(err), nil
W
wei liu 已提交
4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940
	}

	log.Debug("DescribeResourceGroup enqueued",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	if err := t.WaitToFinish(); err != nil {
		log.Warn("DescribeResourceGroup failed to WaitToFinish",
			zap.Error(err),
			zap.Uint64("BeginTS", t.BeginTs()),
			zap.Uint64("EndTS", t.EndTs()))
W
wei liu 已提交
4941
		return GetErrResponse(err), nil
W
wei liu 已提交
4942 4943 4944 4945 4946 4947 4948 4949 4950 4951
	}

	log.Debug("DescribeResourceGroup done",
		zap.Uint64("BeginTS", t.BeginTs()),
		zap.Uint64("EndTS", t.EndTs()))

	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return t.result, nil
W
wei liu 已提交
4952
}
Y
yihao.dai 已提交
4953 4954 4955 4956 4957 4958 4959 4960

func (node *Proxy) ListIndexedSegment(ctx context.Context, request *federpb.ListIndexedSegmentRequest) (*federpb.ListIndexedSegmentResponse, error) {
	panic("TODO: implement me")
}

func (node *Proxy) DescribeSegmentIndexData(ctx context.Context, request *federpb.DescribeSegmentIndexDataRequest) (*federpb.DescribeSegmentIndexDataResponse, error) {
	panic("TODO: implement me")
}