impl.go 154.8 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"
E
Enwei Jiao 已提交
28
	"go.opentelemetry.io/otel"
J
jaime 已提交
29
	"go.uber.org/zap"
30
	"golang.org/x/sync/errgroup"
31

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

56 57
const moduleName = "Proxy"

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

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

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

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

	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-InvalidateCollectionMetaCache")
	defer sp.End()
113
	log := log.Ctx(ctx).With(
114
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
115
		zap.String("db", request.DbName),
116 117
		zap.String("collectionName", request.CollectionName),
		zap.Int64("collectionID", request.CollectionID))
D
dragondriver 已提交
118

119 120
	log.Info("received request to invalidate collection meta cache")

121
	collectionName := request.CollectionName
122
	collectionID := request.CollectionID
X
Xiaofan 已提交
123 124

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

144
	return &commonpb.Status{
145
		ErrorCode: commonpb.ErrorCode_Success,
146 147
		Reason:    "",
	}, nil
148 149
}

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

E
Enwei Jiao 已提交
157 158
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateCollection")
	defer sp.End()
159 160 161
	method := "CreateCollection"
	tr := timerecord.NewTimeRecorder(method)

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

164
	cct := &createCollectionTask{
S
sunby 已提交
165
		ctx:                     ctx,
166 167
		Condition:               NewTaskCondition(ctx),
		CreateCollectionRequest: request,
168
		rootCoord:               node.rootCoord,
169 170
	}

171 172 173
	// avoid data race
	lenOfSchema := len(request.Schema)

174
	log := log.Ctx(ctx).With(
175
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
176 177
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
178
		zap.Int("len(schema)", lenOfSchema),
179 180
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
181

182 183
	log.Debug(rpcReceived(method))

184 185 186
	if err := node.sched.ddQueue.Enqueue(cct); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
187
			zap.Error(err))
188

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

196 197
	log.Debug(
		rpcEnqueued(method),
198 199
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
200
		zap.Uint64("timestamp", request.Base.Timestamp))
201

202 203 204
	if err := cct.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
205
			zap.Error(err),
206
			zap.Uint64("BeginTs", cct.BeginTs()),
207
			zap.Uint64("EndTs", cct.EndTs()))
D
dragondriver 已提交
208

E
Enwei Jiao 已提交
209
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
210
		return &commonpb.Status{
211
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
212 213 214 215
			Reason:    err.Error(),
		}, nil
	}

216 217
	log.Debug(
		rpcDone(method),
218
		zap.Uint64("BeginTs", cct.BeginTs()),
219
		zap.Uint64("EndTs", cct.EndTs()))
220

E
Enwei Jiao 已提交
221 222
	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()))
223 224 225
	return cct.result, nil
}

226
// DropCollection drop a collection.
C
Cai Yudong 已提交
227
func (node *Proxy) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
228 229 230
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
231

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

238
	dct := &dropCollectionTask{
S
sunby 已提交
239
		ctx:                   ctx,
240 241
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
242
		rootCoord:             node.rootCoord,
243
		chMgr:                 node.chMgr,
S
sunby 已提交
244
		chTicker:              node.chTicker,
245 246
	}

247
	log := log.Ctx(ctx).With(
248
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
249 250
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
251

252 253
	log.Debug("DropCollection received")

254 255
	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DropCollection failed to enqueue",
256
			zap.Error(err))
257

E
Enwei Jiao 已提交
258
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
259
		return &commonpb.Status{
260
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
261 262 263 264
			Reason:    err.Error(),
		}, nil
	}

265 266
	log.Debug("DropCollection enqueued",
		zap.Uint64("BeginTs", dct.BeginTs()),
267
		zap.Uint64("EndTs", dct.EndTs()))
268 269 270

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DropCollection failed to WaitToFinish",
D
dragondriver 已提交
271
			zap.Error(err),
272
			zap.Uint64("BeginTs", dct.BeginTs()),
273
			zap.Uint64("EndTs", dct.EndTs()))
D
dragondriver 已提交
274

E
Enwei Jiao 已提交
275
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
276
		return &commonpb.Status{
277
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
278 279 280 281
			Reason:    err.Error(),
		}, nil
	}

282 283
	log.Debug("DropCollection done",
		zap.Uint64("BeginTs", dct.BeginTs()),
284
		zap.Uint64("EndTs", dct.EndTs()))
285

E
Enwei Jiao 已提交
286 287
	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()))
288 289 290
	return dct.result, nil
}

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

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

306
	log := log.Ctx(ctx).With(
307
		zap.String("role", typeutil.ProxyRole),
308 309 310
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

311 312
	log.Debug("HasCollection received")

313
	hct := &hasCollectionTask{
S
sunby 已提交
314
		ctx:                  ctx,
315 316
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
317
		rootCoord:            node.rootCoord,
318 319
	}

320 321
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
322
			zap.Error(err))
323

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

334 335
	log.Debug("HasCollection enqueued",
		zap.Uint64("BeginTS", hct.BeginTs()),
336
		zap.Uint64("EndTS", hct.EndTs()))
337 338 339

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

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

354 355
	log.Debug("HasCollection done",
		zap.Uint64("BeginTS", hct.BeginTs()),
356
		zap.Uint64("EndTS", hct.EndTs()))
357

E
Enwei Jiao 已提交
358
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
359
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
360
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
361 362 363
	return hct.result, nil
}

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

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

384
	log := log.Ctx(ctx).With(
385
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
386
		zap.String("db", request.DbName),
387 388
		zap.String("collection", request.CollectionName),
		zap.Bool("refreshMode", request.Refresh))
389

390 391
	log.Debug("LoadCollection received")

392 393
	if err := node.sched.ddQueue.Enqueue(lct); err != nil {
		log.Warn("LoadCollection failed to enqueue",
394
			zap.Error(err))
395

E
Enwei Jiao 已提交
396
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
397
			metrics.AbandonLabel).Inc()
398
		return &commonpb.Status{
399
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
400 401 402
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
403

404 405
	log.Debug("LoadCollection enqueued",
		zap.Uint64("BeginTS", lct.BeginTs()),
406
		zap.Uint64("EndTS", lct.EndTs()))
407 408 409

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

421 422
	log.Debug("LoadCollection done",
		zap.Uint64("BeginTS", lct.BeginTs()),
423
		zap.Uint64("EndTS", lct.EndTs()))
424

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

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

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

451
	log := log.Ctx(ctx).With(
452
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
453 454
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
455

456 457
	log.Debug(rpcReceived(method))

458
	if err := node.sched.ddQueue.Enqueue(rct); err != nil {
459 460
		log.Warn(
			rpcFailedToEnqueue(method),
461
			zap.Error(err))
462

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

471 472
	log.Debug(
		rpcEnqueued(method),
473
		zap.Uint64("BeginTS", rct.BeginTs()),
474
		zap.Uint64("EndTS", rct.EndTs()))
475 476

	if err := rct.WaitToFinish(); err != nil {
477 478
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
479
			zap.Error(err),
480
			zap.Uint64("BeginTS", rct.BeginTs()),
481
			zap.Uint64("EndTS", rct.EndTs()))
D
dragondriver 已提交
482

E
Enwei Jiao 已提交
483
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
484
			metrics.FailLabel).Inc()
485
		return &commonpb.Status{
486
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
487 488 489 490
			Reason:    err.Error(),
		}, nil
	}

491 492
	log.Debug(
		rpcDone(method),
493
		zap.Uint64("BeginTS", rct.BeginTs()),
494
		zap.Uint64("EndTS", rct.EndTs()))
495

E
Enwei Jiao 已提交
496
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
497
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
498
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
499
	return rct.result, nil
500 501
}

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

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

517
	dct := &describeCollectionTask{
S
sunby 已提交
518
		ctx:                       ctx,
519 520
		Condition:                 NewTaskCondition(ctx),
		DescribeCollectionRequest: request,
521
		rootCoord:                 node.rootCoord,
522 523
	}

524
	log := log.Ctx(ctx).With(
525
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
526 527
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
528

529 530
	log.Debug("DescribeCollection received")

531 532
	if err := node.sched.ddQueue.Enqueue(dct); err != nil {
		log.Warn("DescribeCollection failed to enqueue",
533
			zap.Error(err))
534

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

545 546
	log.Debug("DescribeCollection enqueued",
		zap.Uint64("BeginTS", dct.BeginTs()),
547
		zap.Uint64("EndTS", dct.EndTs()))
548 549 550

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

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

558 559
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
560
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
561 562 563 564 565
				Reason:    err.Error(),
			},
		}, nil
	}

566 567
	log.Debug("DescribeCollection done",
		zap.Uint64("BeginTS", dct.BeginTs()),
568
		zap.Uint64("EndTS", dct.EndTs()))
569

E
Enwei Jiao 已提交
570
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
571
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
572
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
573 574 575
	return dct.result, nil
}

576 577 578 579 580 581 582 583 584
// 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 已提交
585 586
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetStatistics")
	defer sp.End()
587 588
	method := "GetStatistics"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
589
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
590
		metrics.TotalLabel).Inc()
591 592 593 594 595 596 597 598 599 600
	g := &getStatisticsTask{
		request:   request,
		Condition: NewTaskCondition(ctx),
		ctx:       ctx,
		tr:        tr,
		dc:        node.dataCoord,
		qc:        node.queryCoord,
		shardMgr:  node.shardMgr,
	}

601
	log := log.Ctx(ctx).With(
602 603
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
604 605 606 607
		zap.String("collection", request.CollectionName))

	log.Debug(
		rpcReceived(method),
608 609 610 611 612 613 614 615
		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 已提交
616
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
			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 已提交
641
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
642 643 644 645 646 647 648 649 650 651 652 653 654
			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()),
655
		zap.Uint64("EndTS", g.EndTs()))
656

E
Enwei Jiao 已提交
657
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
658
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
659
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
660 661 662
	return g.result, nil
}

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

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

684
	log := log.Ctx(ctx).With(
685
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
686 687
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
688

689 690
	log.Debug(rpcReceived(method))

691
	if err := node.sched.ddQueue.Enqueue(g); err != nil {
692 693
		log.Warn(
			rpcFailedToEnqueue(method),
694
			zap.Error(err))
695

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

G
godchen 已提交
699
		return &milvuspb.GetCollectionStatisticsResponse{
700
			Status: &commonpb.Status{
701
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
702 703 704 705 706
				Reason:    err.Error(),
			},
		}, nil
	}

707 708
	log.Debug(
		rpcEnqueued(method),
709
		zap.Uint64("BeginTS", g.BeginTs()),
710
		zap.Uint64("EndTS", g.EndTs()))
711 712

	if err := g.WaitToFinish(); err != nil {
713 714
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
715
			zap.Error(err),
716
			zap.Uint64("BeginTS", g.BeginTs()),
717
			zap.Uint64("EndTS", g.EndTs()))
D
dragondriver 已提交
718

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

G
godchen 已提交
722
		return &milvuspb.GetCollectionStatisticsResponse{
723
			Status: &commonpb.Status{
724
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
725 726 727 728 729
				Reason:    err.Error(),
			},
		}, nil
	}

730 731
	log.Debug(
		rpcDone(method),
732
		zap.Uint64("BeginTS", g.BeginTs()),
733
		zap.Uint64("EndTS", g.EndTs()))
734

E
Enwei Jiao 已提交
735
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
736
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
737
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
738
	return g.result, nil
739 740
}

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

754
	sct := &showCollectionsTask{
G
godchen 已提交
755 756 757
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
758
		queryCoord:             node.queryCoord,
759
		rootCoord:              node.rootCoord,
760 761
	}

762
	log := log.Ctx(ctx).With(
763
		zap.String("role", typeutil.ProxyRole),
764 765
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
766 767 768 769
		zap.String("ShowType", request.Type.String()))

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

771
	err := node.sched.ddQueue.Enqueue(sct)
772
	if err != nil {
773 774
		log.Warn("ShowCollections failed to enqueue",
			zap.Error(err),
775
			zap.Any("CollectionNames", request.CollectionNames))
776

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

786
	log.Debug("ShowCollections enqueued",
787
		zap.Any("CollectionNames", request.CollectionNames))
D
dragondriver 已提交
788

789 790
	err = sct.WaitToFinish()
	if err != nil {
791 792
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
793
			zap.Any("CollectionNames", request.CollectionNames))
794

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

G
godchen 已提交
797
		return &milvuspb.ShowCollectionsResponse{
798
			Status: &commonpb.Status{
799
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
800 801 802 803 804
				Reason:    err.Error(),
			},
		}, nil
	}

805
	log.Debug("ShowCollections Done",
806 807
		zap.Int("len(CollectionNames)", len(request.CollectionNames)),
		zap.Int("num_collections", len(sct.result.CollectionNames)))
808

E
Enwei Jiao 已提交
809 810
	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()))
811 812 813
	return sct.result, nil
}

J
jaime 已提交
814 815 816 817 818
func (node *Proxy) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

E
Enwei Jiao 已提交
819 820
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-AlterCollection")
	defer sp.End()
J
jaime 已提交
821 822 823
	method := "AlterCollection"
	tr := timerecord.NewTimeRecorder(method)

E
Enwei Jiao 已提交
824
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
J
jaime 已提交
825 826 827 828 829 830 831 832

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

833
	log := log.Ctx(ctx).With(
J
jaime 已提交
834 835 836 837
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

838 839 840
	log.Debug(
		rpcReceived(method))

J
jaime 已提交
841 842 843
	if err := node.sched.ddQueue.Enqueue(act); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
844
			zap.Error(err))
J
jaime 已提交
845

E
Enwei Jiao 已提交
846
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
J
jaime 已提交
847 848 849 850 851 852 853 854 855 856
		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()),
857
		zap.Uint64("timestamp", request.Base.Timestamp))
J
jaime 已提交
858 859 860 861 862 863

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

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

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

E
Enwei Jiao 已提交
878 879
	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 已提交
880 881 882
	return act.result, nil
}

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

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

895
	cpt := &createPartitionTask{
S
sunby 已提交
896
		ctx:                    ctx,
897 898
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
899
		rootCoord:              node.rootCoord,
900 901 902
		result:                 nil,
	}

903
	log := log.Ctx(ctx).With(
904
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
905 906 907
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
908

909 910
	log.Debug(rpcReceived("CreatePartition"))

911 912 913
	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
914
			zap.Error(err))
915

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

918
		return &commonpb.Status{
919
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
920 921 922
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
923

924 925 926
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.Uint64("BeginTS", cpt.BeginTs()),
927
		zap.Uint64("EndTS", cpt.EndTs()))
928 929 930 931

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
932
			zap.Error(err),
933
			zap.Uint64("BeginTS", cpt.BeginTs()),
934
			zap.Uint64("EndTS", cpt.EndTs()))
D
dragondriver 已提交
935

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

938
		return &commonpb.Status{
939
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
940 941 942
			Reason:    err.Error(),
		}, nil
	}
943 944 945 946

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

E
Enwei Jiao 已提交
949 950
	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()))
951 952 953
	return cpt.result, nil
}

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

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

966
	dpt := &dropPartitionTask{
S
sunby 已提交
967
		ctx:                  ctx,
968 969
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
970
		rootCoord:            node.rootCoord,
C
cai.zhang 已提交
971
		queryCoord:           node.queryCoord,
972 973 974
		result:               nil,
	}

975
	log := log.Ctx(ctx).With(
976
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
977 978 979
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
980

981 982
	log.Debug(rpcReceived(method))

983 984 985
	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
986
			zap.Error(err))
987

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

990
		return &commonpb.Status{
991
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
992 993 994
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
995

996 997 998
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", dpt.BeginTs()),
999
		zap.Uint64("EndTS", dpt.EndTs()))
1000 1001 1002 1003

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1004
			zap.Error(err),
1005
			zap.Uint64("BeginTS", dpt.BeginTs()),
1006
			zap.Uint64("EndTS", dpt.EndTs()))
D
dragondriver 已提交
1007

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

1010
		return &commonpb.Status{
1011
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1012 1013 1014
			Reason:    err.Error(),
		}, nil
	}
1015 1016 1017 1018

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

E
Enwei Jiao 已提交
1021 1022
	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()))
1023 1024 1025
	return dpt.result, nil
}

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

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

1042
	hpt := &hasPartitionTask{
S
sunby 已提交
1043
		ctx:                 ctx,
1044 1045
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1046
		rootCoord:           node.rootCoord,
1047 1048 1049
		result:              nil,
	}

1050
	log := log.Ctx(ctx).With(
1051
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1052 1053 1054
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1055

1056 1057
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
1058 1059 1060
	if err := node.sched.ddQueue.Enqueue(hpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1061
			zap.Error(err))
D
dragondriver 已提交
1062

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

1066 1067
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1068
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1069 1070 1071 1072 1073
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1074

D
dragondriver 已提交
1075 1076 1077
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", hpt.BeginTs()),
1078
		zap.Uint64("EndTS", hpt.EndTs()))
D
dragondriver 已提交
1079 1080 1081 1082

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1083
			zap.Error(err),
D
dragondriver 已提交
1084
			zap.Uint64("BeginTS", hpt.BeginTs()),
1085
			zap.Uint64("EndTS", hpt.EndTs()))
D
dragondriver 已提交
1086

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

1090 1091
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1092
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1093 1094 1095 1096 1097
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1098 1099 1100 1101

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

E
Enwei Jiao 已提交
1104
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1105
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1106
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1107 1108 1109
	return hpt.result, nil
}

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

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

1130
	log := log.Ctx(ctx).With(
1131
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1132 1133
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
1134 1135
		zap.Strings("partitions", request.PartitionNames),
		zap.Bool("refreshMode", request.Refresh))
1136

1137 1138
	log.Debug(rpcReceived(method))

1139 1140 1141
	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1142
			zap.Error(err))
1143

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

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

1153 1154 1155
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", lpt.BeginTs()),
1156
		zap.Uint64("EndTS", lpt.EndTs()))
1157 1158 1159 1160

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1161
			zap.Error(err),
1162
			zap.Uint64("BeginTS", lpt.BeginTs()),
1163
			zap.Uint64("EndTS", lpt.EndTs()))
D
dragondriver 已提交
1164

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

1168
		return &commonpb.Status{
1169
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1170 1171 1172 1173
			Reason:    err.Error(),
		}, nil
	}

1174 1175 1176
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", lpt.BeginTs()),
1177
		zap.Uint64("EndTS", lpt.EndTs()))
1178

E
Enwei Jiao 已提交
1179
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1180
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1181
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1182
	return lpt.result, nil
1183 1184
}

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

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

1194
	rpt := &releasePartitionsTask{
G
godchen 已提交
1195 1196 1197
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1198
		queryCoord:               node.queryCoord,
1199 1200
	}

1201
	method := "ReleasePartitions"
1202
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1203
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1204
		metrics.TotalLabel).Inc()
1205 1206

	log := log.Ctx(ctx).With(
1207
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1208 1209 1210
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1211

1212 1213
	log.Debug(rpcReceived(method))

1214 1215 1216
	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1217
			zap.Error(err))
1218

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

1222
		return &commonpb.Status{
1223
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1224 1225 1226 1227
			Reason:    err.Error(),
		}, nil
	}

1228 1229 1230
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", rpt.BeginTs()),
1231
		zap.Uint64("EndTS", rpt.EndTs()))
1232 1233 1234 1235

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1236
			zap.Error(err),
1237
			zap.Uint64("BeginTS", rpt.BeginTs()),
1238
			zap.Uint64("EndTS", rpt.EndTs()))
D
dragondriver 已提交
1239

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

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

1249 1250 1251
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", rpt.BeginTs()),
1252
		zap.Uint64("EndTS", rpt.EndTs()))
1253

E
Enwei Jiao 已提交
1254
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1255
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1256
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1257
	return rpt.result, nil
1258 1259
}

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

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

1275
	g := &getPartitionStatisticsTask{
1276 1277 1278
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1279
		dataCoord:                     node.dataCoord,
1280 1281
	}

1282
	log := log.Ctx(ctx).With(
1283
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1284 1285 1286
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1287

1288 1289
	log.Debug(rpcReceived(method))

1290 1291 1292
	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
1293
			zap.Error(err))
1294

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

1298 1299 1300 1301 1302 1303 1304 1305
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1306 1307 1308
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", g.BeginTs()),
1309
		zap.Uint64("EndTS", g.EndTs()))
1310 1311 1312 1313

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1314
			zap.Error(err),
1315
			zap.Uint64("BeginTS", g.BeginTs()),
1316
			zap.Uint64("EndTS", g.EndTs()))
1317

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

1321 1322 1323 1324 1325 1326 1327 1328
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1329 1330 1331
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTS", g.BeginTs()),
1332
		zap.Uint64("EndTS", g.EndTs()))
1333

E
Enwei Jiao 已提交
1334
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1335
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1336
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1337
	return g.result, nil
1338 1339
}

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

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

1351
	spt := &showPartitionsTask{
G
godchen 已提交
1352 1353 1354
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1355
		rootCoord:             node.rootCoord,
1356
		queryCoord:            node.queryCoord,
G
godchen 已提交
1357
		result:                nil,
1358 1359
	}

1360
	method := "ShowPartitions"
1361 1362
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
E
Enwei Jiao 已提交
1363
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1364
		metrics.TotalLabel).Inc()
1365

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

1368 1369
	log.Debug(
		rpcReceived(method),
G
godchen 已提交
1370
		zap.Any("request", request))
1371 1372 1373 1374 1375 1376 1377

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

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

G
godchen 已提交
1381
		return &milvuspb.ShowPartitionsResponse{
1382
			Status: &commonpb.Status{
1383
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1384 1385 1386 1387 1388
				Reason:    err.Error(),
			},
		}, nil
	}

1389 1390 1391 1392
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1393 1394
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1395 1396 1397 1398 1399
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1400
			zap.Error(err),
1401 1402 1403 1404 1405
			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 已提交
1406

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

G
godchen 已提交
1410
		return &milvuspb.ShowPartitionsResponse{
1411
			Status: &commonpb.Status{
1412
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1413 1414 1415 1416
				Reason:    err.Error(),
			},
		}, nil
	}
1417 1418 1419 1420 1421 1422 1423 1424 1425

	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 已提交
1426
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
1427
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
1428
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1429 1430 1431
	return spt.result, nil
}

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

	log.Debug(
S
SimFG 已提交
1444 1445 1446 1447
		rpcReceived(method),
		zap.Any("request", request))

	getErrResponse := func(err error) *milvuspb.GetLoadingProgressResponse {
J
Jiquan Long 已提交
1448
		log.Warn("fail to get loading progress",
1449
			zap.String("collection_name", request.CollectionName),
S
SimFG 已提交
1450 1451
			zap.Strings("partition_name", request.PartitionNames),
			zap.Error(err))
E
Enwei Jiao 已提交
1452
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
1453 1454 1455 1456 1457
		if errors.Is(err, ErrInsufficientMemory) {
			return &milvuspb.GetLoadingProgressResponse{
				Status: InSufficientMemoryStatus(request.GetCollectionName()),
			}
		}
S
SimFG 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
		return &milvuspb.GetLoadingProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}
	}
	if err := validateCollectionName(request.CollectionName); err != nil {
		return getErrResponse(err), nil
	}
	collectionID, err := globalMetaCache.GetCollectionID(ctx, request.CollectionName)
	if err != nil {
		return getErrResponse(err), nil
	}
S
SimFG 已提交
1472

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

1498
	log.Debug(
S
SimFG 已提交
1499 1500
		rpcDone(method),
		zap.Any("request", request))
E
Enwei Jiao 已提交
1501 1502
	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 已提交
1503 1504 1505 1506 1507 1508 1509 1510
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1511
func (node *Proxy) GetLoadState(ctx context.Context, request *milvuspb.GetLoadStateRequest) (*milvuspb.GetLoadStateResponse, error) {
S
SimFG 已提交
1512 1513 1514 1515 1516
	if !node.checkHealthy() {
		return &milvuspb.GetLoadStateResponse{Status: unhealthyStatus()}, nil
	}
	method := "GetLoadState"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
1517 1518
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetLoadState")
	defer sp.End()
S
SimFG 已提交
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
	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{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}
	}

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

1544 1545
	// 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 已提交
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 1586
	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 {
1587 1588 1589 1590 1591
			if errors.Is(err, ErrInsufficientMemory) {
				return &milvuspb.GetLoadStateResponse{
					Status: InSufficientMemoryStatus(request.GetCollectionName()),
				}, nil
			}
S
SimFG 已提交
1592 1593 1594 1595 1596 1597
			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 {
1598 1599 1600 1601 1602
			if errors.Is(err, ErrInsufficientMemory) {
				return &milvuspb.GetLoadStateResponse{
					Status: InSufficientMemoryStatus(request.GetCollectionName()),
				}, nil
			}
S
SimFG 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
			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
1613 1614
}

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

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

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

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

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

1645 1646
	log.Debug(rpcReceived(method))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1809 1810
	log.Debug(rpcReceived(method))

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

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

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

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

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

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

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

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

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

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

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

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

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

1889 1890
	log.Debug(rpcReceived(method))

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

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

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

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

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

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

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

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

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

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

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

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

1971 1972
	log.Debug(rpcReceived(method))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

E
Enwei Jiao 已提交
2136
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
2137
		metrics.SuccessLabel).Inc()
2138
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
E
Enwei Jiao 已提交
2139 2140 2141
	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()))
2142 2143 2144
	return it.result, nil
}

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

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

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

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

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

2745
// DropAlias alter the alias of collection.
Y
Yusup 已提交
2746 2747 2748 2749
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2750

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

Y
Yusup 已提交
2754 2755 2756 2757 2758 2759 2760
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
2761
	method := "DropAlias"
2762
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2763
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2764

2765
	log := log.Ctx(ctx).With(
D
dragondriver 已提交
2766 2767 2768 2769
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias))

2770 2771
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2772 2773 2774
	if err := node.sched.ddQueue.Enqueue(dat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2775
			zap.Error(err))
E
Enwei Jiao 已提交
2776
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2777

Y
Yusup 已提交
2778 2779 2780 2781 2782 2783
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2784 2785 2786
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", dat.BeginTs()),
2787
		zap.Uint64("EndTs", dat.EndTs()))
D
dragondriver 已提交
2788 2789 2790 2791

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2792
			zap.Error(err),
D
dragondriver 已提交
2793
			zap.Uint64("BeginTs", dat.BeginTs()),
2794
			zap.Uint64("EndTs", dat.EndTs()))
Y
Yusup 已提交
2795

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

Y
Yusup 已提交
2798 2799 2800 2801 2802 2803
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2804 2805 2806
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", dat.BeginTs()),
2807
		zap.Uint64("EndTs", dat.EndTs()))
D
dragondriver 已提交
2808

E
Enwei Jiao 已提交
2809 2810
	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 已提交
2811 2812 2813
	return dat.result, nil
}

2814
// AlterAlias alter alias of collection.
Y
Yusup 已提交
2815 2816 2817 2818
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2819

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

Y
Yusup 已提交
2823 2824 2825 2826 2827 2828 2829
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
2830
	method := "AlterAlias"
2831
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
2832
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2833

2834
	log := log.Ctx(ctx).With(
D
dragondriver 已提交
2835 2836 2837 2838 2839
		zap.String("role", typeutil.ProxyRole),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

2840 2841
	log.Debug(rpcReceived(method))

D
dragondriver 已提交
2842 2843 2844
	if err := node.sched.ddQueue.Enqueue(aat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
2845
			zap.Error(err))
E
Enwei Jiao 已提交
2846
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2847

Y
Yusup 已提交
2848 2849 2850 2851 2852 2853
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2854 2855 2856
	log.Debug(
		rpcEnqueued(method),
		zap.Uint64("BeginTs", aat.BeginTs()),
2857
		zap.Uint64("EndTs", aat.EndTs()))
D
dragondriver 已提交
2858 2859 2860 2861

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2862
			zap.Error(err),
D
dragondriver 已提交
2863
			zap.Uint64("BeginTs", aat.BeginTs()),
2864
			zap.Uint64("EndTs", aat.EndTs()))
Y
Yusup 已提交
2865

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

Y
Yusup 已提交
2868 2869 2870 2871 2872 2873
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2874 2875 2876
	log.Debug(
		rpcDone(method),
		zap.Uint64("BeginTs", aat.BeginTs()),
2877
		zap.Uint64("EndTs", aat.EndTs()))
D
dragondriver 已提交
2878

E
Enwei Jiao 已提交
2879 2880
	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 已提交
2881 2882 2883
	return aat.result, nil
}

2884
// CalcDistance calculates the distances between vectors.
2885
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
2886 2887 2888 2889 2890
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
2891

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

2895 2896
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
2897

2898 2899 2900 2901 2902
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
2903 2904
		}

2905
		qt := &queryTask{
2906 2907 2908
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
2909 2910
				Base: commonpbutil.NewMsgBase(
					commonpbutil.WithMsgType(commonpb.MsgType_Retrieve),
E
Enwei Jiao 已提交
2911
					commonpbutil.WithSourceID(paramtable.GetNodeID()),
2912
				),
E
Enwei Jiao 已提交
2913
				ReqID: paramtable.GetNodeID(),
2914
			},
2915 2916 2917 2918
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

2919
			queryShardPolicy: mergeRoundRobinPolicy,
2920
			shardMgr:         node.shardMgr,
2921 2922
		}

2923
		log := log.Ctx(ctx).With(
G
groot 已提交
2924 2925
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
2926
			zap.Any("OutputFields", queryRequest.OutputFields))
G
groot 已提交
2927

2928
		err := node.sched.dqQueue.Enqueue(qt)
2929
		if err != nil {
2930 2931
			log.Error("CalcDistance queryTask failed to enqueue",
				zap.Error(err))
2932

2933 2934 2935 2936 2937
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
2938
			}, err
2939
		}
2940

2941
		log.Debug("CalcDistance queryTask enqueued")
2942 2943 2944

		err = qt.WaitToFinish()
		if err != nil {
2945 2946
			log.Error("CalcDistance queryTask failed to WaitToFinish",
				zap.Error(err))
2947 2948 2949 2950 2951 2952

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
2953
			}, err
2954
		}
2955

2956
		log.Debug("CalcDistance queryTask Done")
2957 2958

		return &milvuspb.QueryResults{
2959 2960
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
2961 2962 2963
		}, nil
	}

G
groot 已提交
2964 2965
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
E
Enwei Jiao 已提交
2966
		traceID:   sp.SpanContext().TraceID().String(),
G
groot 已提交
2967
		queryFunc: query,
2968 2969
	}

G
groot 已提交
2970
	return task.Execute(ctx, request)
2971 2972
}

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

2978
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
2979
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
E
Enwei Jiao 已提交
2980 2981
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetPersistentSegmentInfo")
	defer sp.End()
2982 2983 2984

	log := log.Ctx(ctx)

D
dragondriver 已提交
2985
	log.Debug("GetPersistentSegmentInfo",
2986
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2987 2988 2989
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
2990
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
2991
		Status: &commonpb.Status{
2992
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
2993 2994
		},
	}
2995 2996 2997 2998
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
2999 3000
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3001
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3002
		metrics.TotalLabel).Inc()
3003 3004 3005

	// list segments
	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
X
XuanYang-cn 已提交
3006
	if err != nil {
E
Enwei Jiao 已提交
3007
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
		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 已提交
3019
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3020
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3021 3022
		return resp, nil
	}
3023 3024

	// get Segment info
3025
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
3026 3027 3028
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3029
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3030
		),
3031
		SegmentIDs: getSegmentsByStatesResponse.Segments,
X
XuanYang-cn 已提交
3032 3033
	})
	if err != nil {
E
Enwei Jiao 已提交
3034
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3035
			metrics.FailLabel).Inc()
3036 3037
		log.Warn("GetPersistentSegmentInfo fail",
			zap.Error(err))
3038
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3039 3040
		return resp, nil
	}
3041 3042 3043
	log.Debug("GetPersistentSegmentInfo",
		zap.Int("len(infos)", len(infoResp.Infos)),
		zap.Any("status", infoResp.Status))
3044
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3045
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3046
			metrics.FailLabel).Inc()
X
XuanYang-cn 已提交
3047 3048 3049 3050 3051 3052
		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 已提交
3053
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3054 3055
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3056
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3057 3058 3059
			State:        info.State,
		}
	}
E
Enwei Jiao 已提交
3060
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3061
		metrics.SuccessLabel).Inc()
E
Enwei Jiao 已提交
3062
	metrics.ProxyReqLatency.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3063
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3064 3065 3066 3067
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3068
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3069
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
E
Enwei Jiao 已提交
3070 3071
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetQuerySegmentInfo")
	defer sp.End()
3072 3073 3074

	log := log.Ctx(ctx)

D
dragondriver 已提交
3075
	log.Debug("GetQuerySegmentInfo",
3076
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3077 3078 3079
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3080
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3081
		Status: &commonpb.Status{
3082
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3083 3084
		},
	}
3085 3086 3087 3088
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3089

3090 3091
	method := "GetQuerySegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3092
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3093 3094
		metrics.TotalLabel).Inc()

3095 3096
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
E
Enwei Jiao 已提交
3097
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3098 3099 3100
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3101
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
3102 3103 3104
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_SegmentInfo),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3105
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3106
		),
3107
		CollectionID: collID,
Z
zhenshan.cao 已提交
3108 3109
	})
	if err != nil {
E
Enwei Jiao 已提交
3110
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3111 3112
		log.Error("Failed to get segment info from QueryCoord",
			zap.Error(err))
Z
zhenshan.cao 已提交
3113 3114 3115
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3116 3117 3118
	log.Debug("GetQuerySegmentInfo",
		zap.Any("infos", infoResp.Infos),
		zap.Any("status", infoResp.Status))
3119
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
E
Enwei Jiao 已提交
3120
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3121 3122
		log.Error("Failed to get segment info from QueryCoord",
			zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
		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 已提交
3136
			State:        info.SegmentState,
3137
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3138 3139
		}
	}
3140

E
Enwei Jiao 已提交
3141 3142
	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()))
3143
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3144 3145 3146 3147
	resp.Infos = queryInfos
	return resp, nil
}

J
jingkl 已提交
3148
// Dummy handles dummy request
C
Cai Yudong 已提交
3149
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3150 3151 3152 3153 3154 3155
	failedResponse := &milvuspb.DummyResponse{
		Response: `{"status": "fail"}`,
	}

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

E
Enwei Jiao 已提交
3157 3158
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Dummy")
	defer sp.End()
3159 3160 3161

	log := log.Ctx(ctx)

3162
	if err != nil {
3163 3164
		log.Warn("Failed to parse dummy request type",
			zap.Error(err))
3165 3166 3167
		return failedResponse, nil
	}

3168 3169
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3170
		if err != nil {
3171 3172
			log.Warn("Failed to parse dummy query request",
				zap.Error(err))
3173 3174 3175
			return failedResponse, nil
		}

3176
		request := &milvuspb.QueryRequest{
3177 3178 3179
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3180
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3181 3182
		}

3183
		_, err = node.Query(ctx, request)
3184
		if err != nil {
3185 3186
			log.Warn("Failed to execute dummy query",
				zap.Error(err))
3187 3188
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3189 3190 3191 3192 3193 3194

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

3195 3196
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3197 3198
}

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

E
Enwei Jiao 已提交
3203 3204
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RegisterLink")
	defer sp.End()
3205 3206

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

3210 3211
	log.Debug("RegisterLink")

3212
	if code != commonpb.StateCode_Healthy {
3213 3214 3215
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3216
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3217
				Reason:    "proxy not healthy",
3218 3219 3220
			},
		}, nil
	}
E
Enwei Jiao 已提交
3221
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10)).Inc()
3222 3223 3224
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3225
			ErrorCode: commonpb.ErrorCode_Success,
3226
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3227 3228 3229
		},
	}, nil
}
3230

3231
// GetMetrics gets the metrics of proxy
3232 3233
// 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 已提交
3234 3235
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetMetrics")
	defer sp.End()
3236 3237 3238

	log := log.Ctx(ctx)

3239 3240
	log.RatedDebug(60, "Proxy.GetMetrics",
		zap.Int64("nodeID", paramtable.GetNodeID()),
3241 3242 3243 3244
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
3245
			zap.Int64("nodeID", paramtable.GetNodeID()),
3246
			zap.String("req", req.Request),
E
Enwei Jiao 已提交
3247
			zap.Error(errProxyIsUnhealthy(paramtable.GetNodeID())))
3248 3249 3250 3251

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
E
Enwei Jiao 已提交
3252
				Reason:    msgProxyIsUnhealthy(paramtable.GetNodeID()),
3253 3254 3255 3256 3257 3258 3259 3260
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
3261
			zap.Int64("nodeID", paramtable.GetNodeID()),
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
			zap.String("req", req.Request),
			zap.Error(err))

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

3274 3275 3276
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3277
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3278
	)
3279
	if metricType == metricsinfo.SystemInfoMetrics {
3280 3281 3282
		metrics, err := node.metricsCacheManager.GetSystemInfoMetrics()
		if err != nil {
			metrics, err = getSystemInfoMetrics(ctx, req, node)
3283
		}
3284

3285 3286
		log.RatedDebug(60, "Proxy.GetMetrics",
			zap.Int64("nodeID", paramtable.GetNodeID()),
3287
			zap.String("req", req.Request),
3288
			zap.String("metricType", metricType),
3289 3290 3291
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3292 3293
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3294
		return metrics, nil
3295 3296
	}

3297 3298
	log.RatedWarn(60, "Proxy.GetMetrics failed, request metric type is not implemented yet",
		zap.Int64("nodeID", paramtable.GetNodeID()),
3299
		zap.String("req", req.Request),
3300
		zap.String("metricType", metricType))
3301 3302 3303 3304 3305 3306 3307 3308 3309 3310

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

3311 3312 3313
// 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 已提交
3314 3315
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetProxyMetrics")
	defer sp.End()
3316 3317

	log := log.Ctx(ctx).With(
3318
		zap.Int64("nodeID", paramtable.GetNodeID()),
3319 3320
		zap.String("req", req.Request))

3321 3322
	if !node.checkHealthy() {
		log.Warn("Proxy.GetProxyMetrics failed",
E
Enwei Jiao 已提交
3323
			zap.Error(errProxyIsUnhealthy(paramtable.GetNodeID())))
3324 3325 3326 3327

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
E
Enwei Jiao 已提交
3328
				Reason:    msgProxyIsUnhealthy(paramtable.GetNodeID()),
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
			},
		}, 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
	}

3346 3347 3348
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_SystemInfo),
		commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3349
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
3350
	)
3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366

	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
		}

		log.Debug("Proxy.GetProxyMetrics",
3367
			zap.String("metricType", metricType))
3368 3369 3370 3371

		return proxyMetrics, nil
	}

J
Jiquan Long 已提交
3372
	log.Warn("Proxy.GetProxyMetrics failed, request metric type is not implemented yet",
3373
		zap.String("metricType", metricType))
3374 3375 3376 3377 3378 3379 3380 3381 3382

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

B
bigsheeper 已提交
3383 3384
// 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 已提交
3385 3386
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-LoadBalance")
	defer sp.End()
3387 3388 3389

	log := log.Ctx(ctx)

B
bigsheeper 已提交
3390
	log.Debug("Proxy.LoadBalance",
E
Enwei Jiao 已提交
3391
		zap.Int64("proxy_id", paramtable.GetNodeID()),
B
bigsheeper 已提交
3392 3393 3394 3395 3396 3397 3398 3399 3400
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3401 3402 3403

	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	if err != nil {
J
Jiquan Long 已提交
3404
		log.Warn("failed to get collection id",
3405 3406
			zap.String("collection name", req.GetCollectionName()),
			zap.Error(err))
3407 3408 3409
		status.Reason = err.Error()
		return status, nil
	}
B
bigsheeper 已提交
3410
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
3411 3412 3413
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_LoadBalanceSegments),
			commonpbutil.WithMsgID(0),
E
Enwei Jiao 已提交
3414
			commonpbutil.WithSourceID(paramtable.GetNodeID()),
3415
		),
B
bigsheeper 已提交
3416 3417
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3418
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3419
		SealedSegmentIDs: req.SealedSegmentIDs,
3420
		CollectionID:     collectionID,
B
bigsheeper 已提交
3421 3422
	})
	if err != nil {
J
Jiquan Long 已提交
3423
		log.Warn("Failed to LoadBalance from Query Coordinator",
3424 3425
			zap.Any("req", req),
			zap.Error(err))
B
bigsheeper 已提交
3426 3427 3428 3429
		status.Reason = err.Error()
		return status, nil
	}
	if infoResp.ErrorCode != commonpb.ErrorCode_Success {
J
Jiquan Long 已提交
3430
		log.Warn("Failed to LoadBalance from Query Coordinator",
3431
			zap.String("errMsg", infoResp.Reason))
B
bigsheeper 已提交
3432 3433 3434
		status.Reason = infoResp.Reason
		return status, nil
	}
3435 3436 3437
	log.Debug("LoadBalance Done",
		zap.Any("req", req),
		zap.Any("status", infoResp))
B
bigsheeper 已提交
3438 3439 3440 3441
	status.ErrorCode = commonpb.ErrorCode_Success
	return status, nil
}

3442 3443
// GetReplicas gets replica info
func (node *Proxy) GetReplicas(ctx context.Context, req *milvuspb.GetReplicasRequest) (*milvuspb.GetReplicasResponse, error) {
E
Enwei Jiao 已提交
3444 3445
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetReplicas")
	defer sp.End()
3446 3447 3448 3449 3450 3451

	log := log.Ctx(ctx)

	log.Debug("received get replicas request",
		zap.Int64("collection", req.GetCollectionID()),
		zap.Bool("with shard nodes", req.GetWithShardNodes()))
3452 3453 3454 3455 3456 3457
	resp := &milvuspb.GetReplicasResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

S
smellthemoon 已提交
3458 3459
	req.Base = commonpbutil.NewMsgBase(
		commonpbutil.WithMsgType(commonpb.MsgType_GetReplicas),
E
Enwei Jiao 已提交
3460
		commonpbutil.WithSourceID(paramtable.GetNodeID()),
S
smellthemoon 已提交
3461
	)
3462

W
wei liu 已提交
3463 3464 3465 3466
	if req.GetCollectionName() != "" {
		req.CollectionID, _ = globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	}

3467 3468
	resp, err := node.queryCoord.GetReplicas(ctx, req)
	if err != nil {
3469 3470
		log.Error("Failed to get replicas from Query Coordinator",
			zap.Error(err))
3471 3472 3473 3474
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3475 3476 3477
	log.Debug("received get replicas response",
		zap.Any("resp", resp),
		zap.Error(err))
3478 3479 3480
	return resp, nil
}

3481
// GetCompactionState gets the compaction state of multiple segments
3482
func (node *Proxy) GetCompactionState(ctx context.Context, req *milvuspb.GetCompactionStateRequest) (*milvuspb.GetCompactionStateResponse, error) {
E
Enwei Jiao 已提交
3483 3484
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetCompactionState")
	defer sp.End()
3485 3486 3487 3488 3489

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

	log.Debug("received GetCompactionState request")
3490 3491 3492 3493 3494 3495 3496
	resp := &milvuspb.GetCompactionStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionState(ctx, req)
3497 3498 3499
	log.Debug("received GetCompactionState response",
		zap.Any("resp", resp),
		zap.Error(err))
3500 3501 3502
	return resp, err
}

3503
// ManualCompaction invokes compaction on specified collection
3504
func (node *Proxy) ManualCompaction(ctx context.Context, req *milvuspb.ManualCompactionRequest) (*milvuspb.ManualCompactionResponse, error) {
E
Enwei Jiao 已提交
3505 3506
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ManualCompaction")
	defer sp.End()
3507 3508 3509 3510 3511

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

	log.Info("received ManualCompaction request")
3512 3513 3514 3515 3516 3517 3518
	resp := &milvuspb.ManualCompactionResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.ManualCompaction(ctx, req)
3519 3520 3521
	log.Info("received ManualCompaction response",
		zap.Any("resp", resp),
		zap.Error(err))
3522 3523 3524
	return resp, err
}

3525
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3526
func (node *Proxy) GetCompactionStateWithPlans(ctx context.Context, req *milvuspb.GetCompactionPlansRequest) (*milvuspb.GetCompactionPlansResponse, error) {
E
Enwei Jiao 已提交
3527 3528
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetCompactionStateWithPlans")
	defer sp.End()
3529 3530 3531 3532 3533

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

	log.Debug("received GetCompactionStateWithPlans request")
3534 3535 3536 3537 3538 3539 3540
	resp := &milvuspb.GetCompactionPlansResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

	resp, err := node.dataCoord.GetCompactionStateWithPlans(ctx, req)
3541 3542 3543
	log.Debug("received GetCompactionStateWithPlans response",
		zap.Any("resp", resp),
		zap.Error(err))
3544 3545 3546
	return resp, err
}

B
Bingyi Sun 已提交
3547 3548
// GetFlushState gets the flush state of multiple segments
func (node *Proxy) GetFlushState(ctx context.Context, req *milvuspb.GetFlushStateRequest) (*milvuspb.GetFlushStateResponse, error) {
E
Enwei Jiao 已提交
3549 3550
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetFlushState")
	defer sp.End()
3551 3552 3553 3554 3555

	log := log.Ctx(ctx)

	log.Debug("received get flush state request",
		zap.Any("request", req))
3556
	var err error
B
Bingyi Sun 已提交
3557 3558 3559
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
J
Jiquan Long 已提交
3560
		log.Warn("unable to get flush state because of closed server")
B
Bingyi Sun 已提交
3561 3562 3563
		return resp, nil
	}

3564
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3565
	if err != nil {
3566 3567
		log.Warn("failed to get flush state response",
			zap.Error(err))
X
Xiaofan 已提交
3568 3569
		return nil, err
	}
3570 3571
	log.Debug("received get flush state response",
		zap.Any("response", resp))
B
Bingyi Sun 已提交
3572 3573 3574
	return resp, err
}

C
Cai Yudong 已提交
3575 3576
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3577 3578
	code := node.stateCode.Load().(commonpb.StateCode)
	return code == commonpb.StateCode_Healthy
3579 3580
}

3581 3582 3583
func (node *Proxy) checkHealthyAndReturnCode() (commonpb.StateCode, bool) {
	code := node.stateCode.Load().(commonpb.StateCode)
	return code, code == commonpb.StateCode_Healthy
3584 3585
}

3586
// unhealthyStatus returns the proxy not healthy status
3587 3588 3589
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3590
		Reason:    "proxy not healthy",
3591 3592
	}
}
G
groot 已提交
3593 3594 3595

// 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 已提交
3596 3597
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-Import")
	defer sp.End()
3598 3599 3600

	log := log.Ctx(ctx)

3601 3602
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
G
groot 已提交
3603 3604
		zap.String("partition name", req.GetPartitionName()),
		zap.Strings("files", req.GetFiles()))
3605 3606 3607 3608 3609 3610
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3611 3612 3613 3614
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3615

3616 3617
	err := importutil.ValidateOptions(req.GetOptions())
	if err != nil {
3618 3619
		log.Error("failed to execute import request",
			zap.Error(err))
3620 3621 3622 3623 3624
		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
	}

3625 3626
	method := "Import"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3627
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3628 3629
		metrics.TotalLabel).Inc()

3630
	// Call rootCoord to finish import.
3631 3632
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
E
Enwei Jiao 已提交
3633
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3634 3635
		log.Error("failed to execute bulk insert request",
			zap.Error(err))
3636 3637 3638 3639
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3640

E
Enwei Jiao 已提交
3641 3642
	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()))
3643
	return respFromRC, nil
G
groot 已提交
3644 3645
}

3646
// GetImportState checks import task state from RootCoord.
G
groot 已提交
3647
func (node *Proxy) GetImportState(ctx context.Context, req *milvuspb.GetImportStateRequest) (*milvuspb.GetImportStateResponse, error) {
E
Enwei Jiao 已提交
3648 3649
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-GetImportState")
	defer sp.End()
3650 3651 3652 3653 3654

	log := log.Ctx(ctx)

	log.Debug("received get import state request",
		zap.Int64("taskID", req.GetTask()))
G
groot 已提交
3655 3656 3657 3658 3659
	resp := &milvuspb.GetImportStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3660 3661
	method := "GetImportState"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3662
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3663
		metrics.TotalLabel).Inc()
G
groot 已提交
3664 3665

	resp, err := node.rootCoord.GetImportState(ctx, req)
3666
	if err != nil {
E
Enwei Jiao 已提交
3667
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3668 3669
		log.Error("failed to execute get import state",
			zap.Error(err))
3670 3671 3672 3673 3674
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}

3675 3676 3677
	log.Debug("successfully received get import state response",
		zap.Int64("taskID", req.GetTask()),
		zap.Any("resp", resp), zap.Error(err))
E
Enwei Jiao 已提交
3678 3679
	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()))
3680
	return resp, nil
G
groot 已提交
3681 3682 3683 3684
}

// 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 已提交
3685 3686
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ListImportTasks")
	defer sp.End()
3687 3688 3689

	log := log.Ctx(ctx)

J
Jiquan Long 已提交
3690
	log.Debug("received list import tasks request")
G
groot 已提交
3691 3692 3693 3694 3695
	resp := &milvuspb.ListImportTasksResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3696 3697
	method := "ListImportTasks"
	tr := timerecord.NewTimeRecorder(method)
E
Enwei Jiao 已提交
3698
	metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method,
3699
		metrics.TotalLabel).Inc()
G
groot 已提交
3700
	resp, err := node.rootCoord.ListImportTasks(ctx, req)
3701
	if err != nil {
E
Enwei Jiao 已提交
3702
		metrics.ProxyFunctionCall.WithLabelValues(strconv.FormatInt(paramtable.GetNodeID(), 10), method, metrics.FailLabel).Inc()
3703 3704
		log.Error("failed to execute list import tasks",
			zap.Error(err))
3705 3706
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
X
XuanYang-cn 已提交
3707 3708 3709
		return resp, nil
	}

3710 3711 3712
	log.Debug("successfully received list import tasks response",
		zap.String("collection", req.CollectionName),
		zap.Any("tasks", resp.Tasks))
E
Enwei Jiao 已提交
3713 3714
	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 已提交
3715 3716 3717
	return resp, err
}

3718 3719
// InvalidateCredentialCache invalidate the credential cache of specified username.
func (node *Proxy) InvalidateCredentialCache(ctx context.Context, request *proxypb.InvalidateCredCacheRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3720 3721
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-InvalidateCredentialCache")
	defer sp.End()
3722 3723

	log := log.Ctx(ctx).With(
3724 3725
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
3726 3727

	log.Debug("received request to invalidate credential cache")
3728
	if !node.checkHealthy() {
3729
		return unhealthyStatus(), nil
3730
	}
3731 3732 3733 3734 3735

	username := request.Username
	if globalMetaCache != nil {
		globalMetaCache.RemoveCredential(username) // no need to return error, though credential may be not cached
	}
3736
	log.Debug("complete to invalidate credential cache")
3737 3738 3739 3740 3741 3742 3743 3744 3745

	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 已提交
3746 3747
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-UpdateCredentialCache")
	defer sp.End()
3748 3749

	log := log.Ctx(ctx).With(
3750 3751
		zap.String("role", typeutil.ProxyRole),
		zap.String("username", request.Username))
3752 3753

	log.Debug("received request to update credential cache")
3754
	if !node.checkHealthy() {
3755
		return unhealthyStatus(), nil
3756
	}
3757 3758

	credInfo := &internalpb.CredentialInfo{
3759 3760
		Username:       request.Username,
		Sha256Password: request.Password,
3761 3762 3763 3764
	}
	if globalMetaCache != nil {
		globalMetaCache.UpdateCredential(credInfo) // no need to return error, though credential may be not cached
	}
3765
	log.Debug("complete to update credential cache")
3766 3767 3768 3769 3770 3771 3772 3773

	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 已提交
3774 3775
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateCredential")
	defer sp.End()
3776 3777 3778 3779 3780 3781

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

	log.Debug("CreateCredential",
		zap.String("role", typeutil.ProxyRole))
3782
	if !node.checkHealthy() {
3783
		return unhealthyStatus(), nil
3784
	}
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
	// 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 {
3795 3796
		log.Error("decode password fail",
			zap.Error(err))
3797 3798 3799 3800 3801 3802
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "decode password fail key:" + req.Username,
		}, nil
	}
	if err = ValidatePassword(rawPassword); err != nil {
3803 3804
		log.Error("illegal password",
			zap.Error(err))
3805 3806 3807 3808 3809 3810 3811
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
	encryptedPassword, err := crypto.PasswordEncrypt(rawPassword)
	if err != nil {
3812 3813
		log.Error("encrypt password fail",
			zap.Error(err))
3814 3815 3816 3817 3818
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_CreateCredentialFailure,
			Reason:    "encrypt password fail key:" + req.Username,
		}, nil
	}
3819

3820 3821 3822
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
3823
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
3824 3825 3826
	}
	result, err := node.rootCoord.CreateCredential(ctx, credInfo)
	if err != nil { // for error like conntext timeout etc.
3827 3828
		log.Error("create credential fail",
			zap.Error(err))
3829 3830 3831 3832 3833 3834 3835 3836
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}
	return result, err
}

C
codeman 已提交
3837
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3838 3839
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-UpdateCredential")
	defer sp.End()
3840 3841 3842 3843 3844 3845

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

	log.Debug("UpdateCredential",
		zap.String("role", typeutil.ProxyRole))
3846
	if !node.checkHealthy() {
3847
		return unhealthyStatus(), nil
3848
	}
C
codeman 已提交
3849 3850
	rawOldPassword, err := crypto.Base64Decode(req.OldPassword)
	if err != nil {
3851 3852
		log.Error("decode old password fail",
			zap.Error(err))
C
codeman 已提交
3853 3854 3855 3856 3857 3858
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode old password fail when updating:" + req.Username,
		}, nil
	}
	rawNewPassword, err := crypto.Base64Decode(req.NewPassword)
3859
	if err != nil {
3860 3861
		log.Error("decode password fail",
			zap.Error(err))
3862 3863 3864 3865 3866
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "decode password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
3867 3868
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
3869 3870
		log.Error("illegal password",
			zap.Error(err))
3871 3872 3873 3874 3875
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
3876 3877

	if !passwordVerify(ctx, req.Username, rawOldPassword, globalMetaCache) {
C
codeman 已提交
3878 3879 3880 3881 3882 3883 3884
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
3885
	if err != nil {
3886 3887
		log.Error("encrypt password fail",
			zap.Error(err))
3888 3889 3890 3891 3892
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "encrypt password fail when updating:" + req.Username,
		}, nil
	}
C
codeman 已提交
3893
	updateCredReq := &internalpb.CredentialInfo{
3894
		Username:          req.Username,
3895
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
3896 3897
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
3898
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
3899
	if err != nil { // for error like conntext timeout etc.
3900 3901
		log.Error("update credential fail",
			zap.Error(err))
3902 3903 3904 3905 3906 3907 3908 3909 3910
		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 已提交
3911 3912
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DeleteCredential")
	defer sp.End()
3913 3914 3915 3916 3917 3918

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

	log.Debug("DeleteCredential",
		zap.String("role", typeutil.ProxyRole))
3919
	if !node.checkHealthy() {
3920
		return unhealthyStatus(), nil
3921 3922
	}

3923 3924 3925 3926 3927 3928
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
3929 3930
	result, err := node.rootCoord.DeleteCredential(ctx, req)
	if err != nil { // for error like conntext timeout etc.
3931 3932
		log.Error("delete credential fail",
			zap.Error(err))
3933 3934 3935 3936 3937 3938 3939 3940 3941
		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 已提交
3942 3943
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-ListCredUsers")
	defer sp.End()
3944 3945 3946 3947 3948

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

	log.Debug("ListCredUsers")
3949
	if !node.checkHealthy() {
3950
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
3951
	}
3952
	rootCoordReq := &milvuspb.ListCredUsersRequest{
3953 3954 3955
		Base: commonpbutil.NewMsgBase(
			commonpbutil.WithMsgType(commonpb.MsgType_ListCredUsernames),
		),
3956 3957
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
	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,
		},
3970
		Usernames: resp.Usernames,
3971 3972
	}, nil
}
3973

3974
func (node *Proxy) CreateRole(ctx context.Context, req *milvuspb.CreateRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
3975 3976
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-CreateRole")
	defer sp.End()
3977 3978 3979 3980 3981

	log := log.Ctx(ctx)

	log.Debug("CreateRole",
		zap.Any("req", req))
3982
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
3983
		return errorutil.UnhealthyStatus(code), nil
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993
	}

	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(),
3994
		}, nil
3995 3996 3997 3998
	}

	result, err := node.rootCoord.CreateRole(ctx, req)
	if err != nil {
3999 4000
		log.Error("fail to create role",
			zap.Error(err))
4001 4002 4003
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4004
		}, nil
4005 4006
	}
	return result, nil
4007 4008
}

4009
func (node *Proxy) DropRole(ctx context.Context, req *milvuspb.DropRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4010 4011
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-DropRole")
	defer sp.End()
4012 4013 4014 4015 4016

	log := log.Ctx(ctx)

	log.Debug("DropRole",
		zap.Any("req", req))
4017
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4018
		return errorutil.UnhealthyStatus(code), nil
4019 4020 4021 4022 4023
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4024
		}, nil
4025
	}
4026 4027 4028 4029 4030
	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,
4031
		}, nil
4032
	}
4033 4034
	result, err := node.rootCoord.DropRole(ctx, req)
	if err != nil {
4035 4036 4037
		log.Error("fail to drop role",
			zap.String("role_name", req.RoleName),
			zap.Error(err))
4038 4039 4040
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4041
		}, nil
4042 4043
	}
	return result, nil
4044 4045
}

4046
func (node *Proxy) OperateUserRole(ctx context.Context, req *milvuspb.OperateUserRoleRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4047 4048
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-OperateUserRole")
	defer sp.End()
4049 4050 4051 4052 4053

	log := log.Ctx(ctx)

	log.Debug("OperateUserRole",
		zap.Any("req", req))
4054
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4055
		return errorutil.UnhealthyStatus(code), nil
4056 4057 4058 4059 4060
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4061
		}, nil
4062 4063 4064 4065 4066
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4067
		}, nil
4068 4069 4070 4071
	}

	result, err := node.rootCoord.OperateUserRole(ctx, req)
	if err != nil {
4072 4073
		logger.Error("fail to operate user role",
			zap.Error(err))
4074 4075 4076
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4077
		}, nil
4078 4079
	}
	return result, nil
4080 4081
}

4082
func (node *Proxy) SelectRole(ctx context.Context, req *milvuspb.SelectRoleRequest) (*milvuspb.SelectRoleResponse, error) {
E
Enwei Jiao 已提交
4083 4084
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectRole")
	defer sp.End()
4085 4086 4087 4088

	log := log.Ctx(ctx)

	log.Debug("SelectRole", zap.Any("req", req))
4089
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4090
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4091 4092 4093 4094 4095 4096 4097 4098 4099
	}

	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(),
				},
4100
			}, nil
4101 4102 4103 4104 4105
		}
	}

	result, err := node.rootCoord.SelectRole(ctx, req)
	if err != nil {
4106 4107
		log.Error("fail to select role",
			zap.Error(err))
4108 4109 4110 4111 4112
		return &milvuspb.SelectRoleResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4113
		}, nil
4114 4115
	}
	return result, nil
4116 4117
}

4118
func (node *Proxy) SelectUser(ctx context.Context, req *milvuspb.SelectUserRequest) (*milvuspb.SelectUserResponse, error) {
E
Enwei Jiao 已提交
4119 4120
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectUser")
	defer sp.End()
4121 4122 4123 4124 4125

	log := log.Ctx(ctx)

	log.Debug("SelectUser",
		zap.Any("req", req))
4126
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4127
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4128 4129 4130 4131 4132 4133 4134 4135 4136
	}

	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(),
				},
4137
			}, nil
4138 4139 4140 4141 4142
		}
	}

	result, err := node.rootCoord.SelectUser(ctx, req)
	if err != nil {
4143 4144
		log.Error("fail to select user",
			zap.Error(err))
4145 4146 4147 4148 4149
		return &milvuspb.SelectUserResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4150
		}, nil
4151 4152
	}
	return result, nil
4153 4154
}

4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184
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
4185 4186
}

4187
func (node *Proxy) OperatePrivilege(ctx context.Context, req *milvuspb.OperatePrivilegeRequest) (*commonpb.Status, error) {
E
Enwei Jiao 已提交
4188 4189
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-OperatePrivilege")
	defer sp.End()
4190 4191 4192 4193 4194

	log := log.Ctx(ctx)

	log.Debug("OperatePrivilege",
		zap.Any("req", req))
4195
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4196
		return errorutil.UnhealthyStatus(code), nil
4197 4198 4199 4200 4201
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4202
		}, nil
4203 4204 4205 4206 4207 4208
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4209
		}, nil
4210 4211 4212 4213
	}
	req.Entity.Grantor.User = &milvuspb.UserEntity{Name: curUser}
	result, err := node.rootCoord.OperatePrivilege(ctx, req)
	if err != nil {
4214 4215
		log.Error("fail to operate privilege",
			zap.Error(err))
4216 4217 4218
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4219
		}, nil
4220 4221
	}
	return result, nil
4222 4223
}

4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
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 已提交
4251 4252
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-SelectGrant")
	defer sp.End()
4253 4254 4255 4256 4257

	log := log.Ctx(ctx)

	log.Debug("SelectGrant",
		zap.Any("req", req))
4258
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4259
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, nil
4260 4261 4262 4263 4264 4265 4266 4267
	}

	if err := node.validGrantParams(req); err != nil {
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_IllegalArgument,
				Reason:    err.Error(),
			},
4268
		}, nil
4269 4270 4271 4272
	}

	result, err := node.rootCoord.SelectGrant(ctx, req)
	if err != nil {
4273 4274
		log.Error("fail to select grant",
			zap.Error(err))
4275 4276 4277 4278 4279
		return &milvuspb.SelectGrantResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
4280
		}, nil
4281 4282 4283 4284 4285
	}
	return result, nil
}

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

	log := log.Ctx(ctx)

	log.Debug("RefreshPrivilegeInfoCache",
		zap.Any("req", req))
4293 4294 4295 4296 4297 4298 4299 4300 4301 4302
	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 {
4303 4304
			log.Error("fail to refresh policy info",
				zap.Error(err))
4305 4306 4307 4308 4309 4310
			return &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_RefreshPolicyInfoCacheFailure,
				Reason:    err.Error(),
			}, err
		}
	}
4311
	log.Debug("RefreshPrivilegeInfoCache success")
4312 4313 4314 4315

	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_Success,
	}, nil
4316
}
4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333

// 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
	}
4334
	node.multiRateLimiter.SetQuotaStates(request.GetStates(), request.GetCodes())
4335 4336 4337
	log.Info("current rates in proxy", zap.Int64("proxyNodeID", paramtable.GetNodeID()), zap.Any("rates", request.GetRates()))
	if len(request.GetStates()) != 0 {
		for i := range request.GetStates() {
4338
			log.Warn("Proxy set quota states", zap.String("state", request.GetStates()[i].String()), zap.String("reason", request.GetCodes()[i].String()))
4339 4340
		}
	}
4341 4342 4343
	resp.ErrorCode = commonpb.ErrorCode_Success
	return resp, nil
}
4344 4345 4346 4347

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")
4348 4349 4350 4351
		return &milvuspb.CheckHealthResponse{
			Status:    unhealthyStatus(),
			IsHealthy: false,
			Reasons:   []string{reason}}, nil
4352 4353 4354 4355 4356 4357 4358 4359 4360 4361
	}

	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 已提交
4362 4363
		ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RefreshPolicyInfoCache")
		defer sp.End()
4364 4365 4366

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

4367
		if err != nil {
4368 4369
			log.Warn("check health fail",
				zap.Error(err))
4370 4371 4372 4373 4374
			errReasons = append(errReasons, fmt.Sprintf("check health fail for %s", role))
			return err
		}

		if !resp.IsHealthy {
4375
			log.Warn("check health fail")
4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
			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{
4399 4400 4401
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_Success,
			},
4402 4403 4404 4405 4406
			IsHealthy: false,
			Reasons:   errReasons,
		}, nil
	}

4407
	states, reasons := node.multiRateLimiter.GetQuotaStates()
4408 4409 4410 4411 4412
	return &milvuspb.CheckHealthResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
4413 4414 4415
		QuotaStates: states,
		Reasons:     reasons,
		IsHealthy:   true,
4416
	}, nil
4417
}
W
wei liu 已提交
4418

J
jaime 已提交
4419
func (node *Proxy) RenameCollection(ctx context.Context, req *milvuspb.RenameCollectionRequest) (*commonpb.Status, error) {
4420
	ctx, sp := otel.Tracer(typeutil.ProxyRole).Start(ctx, "Proxy-RenameCollection")
J
jaime 已提交
4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439
	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 已提交
4440
		}, nil
J
jaime 已提交
4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459
	}

	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 已提交
4460
func (node *Proxy) CreateResourceGroup(ctx context.Context, request *milvuspb.CreateResourceGroupRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4461 4462 4463 4464
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

W
wei liu 已提交
4465 4466 4467 4468 4469 4470 4471 4472
	method := "CreateResourceGroup"
	if err := ValidateResourceGroupName(request.GetResourceGroup()); err != nil {
		log.Warn("CreateResourceGroup failed",
			zap.Error(err),
		)
		return getErrResponse(err, method), nil
	}

W
wei liu 已提交
4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493
	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 已提交
4494
		return getErrResponse(err, method), nil
W
wei liu 已提交
4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505
	}

	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 已提交
4506
		return getErrResponse(err, method), nil
W
wei liu 已提交
4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
	}

	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 已提交
4517 4518
}

W
wei liu 已提交
4519 4520 4521 4522
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 已提交
4523
		ErrorCode: commonpb.ErrorCode_IllegalArgument,
W
wei liu 已提交
4524 4525 4526 4527
		Reason:    err.Error(),
	}
}

W
wei liu 已提交
4528
func (node *Proxy) DropResourceGroup(ctx context.Context, request *milvuspb.DropResourceGroupRequest) (*commonpb.Status, error) {
W
wei liu 已提交
4529 4530 4531 4532
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

W
wei liu 已提交
4533
	method := "DropResourceGroup"
W
wei liu 已提交
4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555
	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 已提交
4556
		return getErrResponse(err, method), nil
W
wei liu 已提交
4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567
	}

	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 已提交
4568
		return getErrResponse(err, method), nil
W
wei liu 已提交
4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
	}

	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 已提交
4579 4580 4581
}

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

W
wei liu 已提交
4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600
	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 已提交
4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622
	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 已提交
4623
		return getErrResponse(err, method), nil
W
wei liu 已提交
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
	}

	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 已提交
4635
		return getErrResponse(err, method), nil
W
wei liu 已提交
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645
	}

	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 已提交
4646 4647 4648
}

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

W
wei liu 已提交
4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667
	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 已提交
4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689
	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 已提交
4690
		return getErrResponse(err, method), nil
W
wei liu 已提交
4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701
	}

	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 已提交
4702
		return getErrResponse(err, method), nil
W
wei liu 已提交
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712
	}

	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 已提交
4713 4714
}

W
wei liu 已提交
4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781
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 已提交
4782 4783 4784
}

func (node *Proxy) DescribeResourceGroup(ctx context.Context, request *milvuspb.DescribeResourceGroupRequest) (*milvuspb.DescribeResourceGroupResponse, error) {
W
wei liu 已提交
4785 4786 4787 4788 4789 4790
	if !node.checkHealthy() {
		return &milvuspb.DescribeResourceGroupResponse{
			Status: unhealthyStatus(),
		}, nil
	}

W
wei liu 已提交
4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
	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 已提交
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824
	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 已提交
4825
		return GetErrResponse(err), nil
W
wei liu 已提交
4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836
	}

	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 已提交
4837
		return GetErrResponse(err), nil
W
wei liu 已提交
4838 4839 4840 4841 4842 4843 4844 4845 4846 4847
	}

	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 已提交
4848
}