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

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

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

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

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

52 53
const moduleName = "Proxy"

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

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

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

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

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

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

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

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

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

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

157 158 159
	// avoid data race
	lenOfSchema := len(request.Schema)

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

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

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

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

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

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

225 226
	log.Debug(
		rpcDone(method),
227
		zap.String("traceID", traceID),
228
		zap.String("role", typeutil.ProxyRole),
229 230 231 232 233 234
		zap.Int64("MsgID", cct.ID()),
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Int("len(schema)", lenOfSchema),
235 236
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
237

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

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

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

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

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

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

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

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

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

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

313 314
	log.Debug("DropCollection done",
		zap.String("traceID", traceID),
315
		zap.String("role", typeutil.ProxyRole),
316 317 318 319 320 321
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

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

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

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

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

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

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

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

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

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

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

404 405
	log.Debug("HasCollection done",
		zap.String("traceID", traceID),
406
		zap.String("role", typeutil.ProxyRole),
407 408 409 410 411 412
		zap.Int64("MsgID", hct.ID()),
		zap.Uint64("BeginTS", hct.BeginTs()),
		zap.Uint64("EndTS", hct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

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

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

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

431
	lct := &loadCollectionTask{
S
sunby 已提交
432
		ctx:                   ctx,
433 434
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
435
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
436
		indexCoord:            node.indexCoord,
437 438
	}

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

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

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

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

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

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

491 492
	log.Debug("LoadCollection done",
		zap.String("traceID", traceID),
493
		zap.String("role", typeutil.ProxyRole),
494 495 496 497 498 499
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

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

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

514
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleaseCollection")
515 516
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
517 518
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
519

520
	rct := &releaseCollectionTask{
S
sunby 已提交
521
		ctx:                      ctx,
522 523
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
524
		queryCoord:               node.queryCoord,
525
		chMgr:                    node.chMgr,
526 527
	}

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

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

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

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

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

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

584 585
	log.Debug(
		rpcDone(method),
586
		zap.String("traceID", traceID),
587
		zap.String("role", typeutil.ProxyRole),
588 589 590 591 592 593
		zap.Int64("MsgID", rct.ID()),
		zap.Uint64("BeginTS", rct.BeginTs()),
		zap.Uint64("EndTS", rct.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

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

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

610
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeCollection")
611 612
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
613 614
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
615

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

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

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

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

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

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

X
Xiaofan 已提交
667
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
668
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
669
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
670
			metrics.FailLabel).Inc()
671

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

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

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

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
// GetStatistics get the statistics, such as `num_rows`.
// WARNING: It is an experimental API
func (node *Proxy) GetStatistics(ctx context.Context, request *milvuspb.GetStatisticsRequest) (*milvuspb.GetStatisticsResponse, error) {
	if !node.checkHealthy() {
		return &milvuspb.GetStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}

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

	g := &getStatisticsTask{
		request:   request,
		Condition: NewTaskCondition(ctx),
		ctx:       ctx,
		tr:        tr,
		dc:        node.dataCoord,
		qc:        node.queryCoord,
		shardMgr:  node.shardMgr,
	}

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

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

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

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

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

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

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

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

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

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

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

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

820
	g := &getCollectionStatisticsTask{
G
godchen 已提交
821 822 823
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
824
		dataCoord:                      node.dataCoord,
825 826
	}

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

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

X
Xiaofan 已提交
843
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
844
			metrics.AbandonLabel).Inc()
845

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

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

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

X
Xiaofan 已提交
876
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
877
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
878
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
879
			metrics.FailLabel).Inc()
880

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

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

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

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

918
	sct := &showCollectionsTask{
G
godchen 已提交
919 920 921
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
922
		queryCoord:             node.queryCoord,
923
		rootCoord:              node.rootCoord,
924 925
	}

926
	log.Debug("ShowCollections received",
927
		zap.String("role", typeutil.ProxyRole),
928 929 930 931 932 933
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
		zap.Any("CollectionNames", request.CollectionNames),
	)

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

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

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

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

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

G
godchen 已提交
977
		return &milvuspb.ShowCollectionsResponse{
978
			Status: &commonpb.Status{
979
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
980 981 982 983 984
				Reason:    err.Error(),
			},
		}, nil
	}

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

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

J
jaime 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
func (node *Proxy) AlterCollection(ctx context.Context, request *milvuspb.AlterCollectionRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

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

	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()

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

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

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

		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

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

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

		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

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

	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return act.result, nil
}

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

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

1100
	cpt := &createPartitionTask{
S
sunby 已提交
1101
		ctx:                    ctx,
1102 1103
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
1104
		rootCoord:              node.rootCoord,
1105 1106 1107
		result:                 nil,
	}

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

	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
			zap.Error(err),
			zap.String("traceID", traceID),
1121
			zap.String("role", typeutil.ProxyRole),
1122 1123 1124 1125
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

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

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

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

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

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

1160
		return &commonpb.Status{
1161
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1162 1163 1164
			Reason:    err.Error(),
		}, nil
	}
1165 1166 1167 1168

	log.Debug(
		rpcDone("CreatePartition"),
		zap.String("traceID", traceID),
1169
		zap.String("role", typeutil.ProxyRole),
1170 1171 1172 1173 1174 1175 1176
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

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

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

1188
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropPartition")
1189 1190
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1191 1192
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
1193
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1194

1195
	dpt := &dropPartitionTask{
S
sunby 已提交
1196
		ctx:                  ctx,
1197 1198
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
1199
		rootCoord:            node.rootCoord,
1200 1201 1202
		result:               nil,
	}

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

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

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

1223
		return &commonpb.Status{
1224
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1225 1226 1227
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1228

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

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

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

1255
		return &commonpb.Status{
1256
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1257 1258 1259
			Reason:    err.Error(),
		}, nil
	}
1260 1261 1262 1263

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

X
Xiaofan 已提交
1272 1273
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1274 1275 1276
	return dpt.result, nil
}

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

D
dragondriver 已提交
1285
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasPartition")
D
dragondriver 已提交
1286 1287
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1288 1289 1290
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1291
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1292
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1293

1294
	hpt := &hasPartitionTask{
S
sunby 已提交
1295
		ctx:                 ctx,
1296 1297
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1298
		rootCoord:           node.rootCoord,
1299 1300 1301
		result:              nil,
	}

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

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

X
Xiaofan 已提交
1320
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1321
			metrics.AbandonLabel).Inc()
1322

1323 1324
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1325
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1326 1327 1328 1329 1330
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1331

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

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

X
Xiaofan 已提交
1356
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1357
			metrics.FailLabel).Inc()
1358

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

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

X
Xiaofan 已提交
1379
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1380
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1381
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1382 1383 1384
	return hpt.result, nil
}

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

D
dragondriver 已提交
1391
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadPartitions")
1392 1393
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1394 1395
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
1396

1397
	lpt := &loadPartitionsTask{
G
godchen 已提交
1398 1399 1400
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1401
		queryCoord:            node.queryCoord,
C
cai.zhang 已提交
1402
		indexCoord:            node.indexCoord,
1403 1404
	}

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

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

X
Xiaofan 已提交
1423
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1424
			metrics.AbandonLabel).Inc()
1425

1426
		return &commonpb.Status{
1427
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1428 1429 1430 1431
			Reason:    err.Error(),
		}, nil
	}

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

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

X
Xiaofan 已提交
1456
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1457
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1458
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1459
			metrics.FailLabel).Inc()
1460

1461
		return &commonpb.Status{
1462
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1463 1464 1465 1466
			Reason:    err.Error(),
		}, nil
	}

1467 1468 1469
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1470
		zap.String("role", typeutil.ProxyRole),
1471 1472 1473 1474 1475 1476 1477
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1478
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1479
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1480
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1481
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1482
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1483
	return lpt.result, nil
1484 1485
}

1486
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1487
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1488 1489 1490
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1491 1492 1493 1494 1495

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

1496
	rpt := &releasePartitionsTask{
G
godchen 已提交
1497 1498 1499
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1500
		queryCoord:               node.queryCoord,
1501 1502
	}

1503
	method := "ReleasePartitions"
1504
	tr := timerecord.NewTimeRecorder(method)
1505 1506 1507 1508

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1509
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1510 1511 1512
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1513 1514 1515 1516 1517 1518

	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1519
			zap.String("role", typeutil.ProxyRole),
1520 1521 1522 1523
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1524
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1525
			metrics.AbandonLabel).Inc()
1526

1527
		return &commonpb.Status{
1528
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1529 1530 1531 1532
			Reason:    err.Error(),
		}, nil
	}

1533 1534 1535
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1536
		zap.String("role", typeutil.ProxyRole),
1537 1538 1539
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1540 1541 1542
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1543 1544 1545 1546

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

X
Xiaofan 已提交
1557
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1558
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1559
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1560
			metrics.FailLabel).Inc()
1561

1562
		return &commonpb.Status{
1563
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1564 1565 1566 1567
			Reason:    err.Error(),
		}, nil
	}

1568 1569 1570
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1571
		zap.String("role", typeutil.ProxyRole),
1572 1573 1574 1575 1576 1577 1578
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1579
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1580
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1581
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1582
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1583
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1584
	return rpt.result, nil
1585 1586
}

1587
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1588
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1589 1590 1591 1592 1593
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1594 1595 1596 1597

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

1601
	g := &getPartitionStatisticsTask{
1602 1603 1604
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1605
		dataCoord:                     node.dataCoord,
1606 1607
	}

1608 1609 1610
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1611
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1612 1613 1614
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1615 1616 1617 1618 1619 1620

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1621
			zap.String("role", typeutil.ProxyRole),
1622 1623 1624 1625
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1626
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1627
			metrics.AbandonLabel).Inc()
1628

1629 1630 1631 1632 1633 1634 1635 1636
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1637 1638 1639
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1640
		zap.String("role", typeutil.ProxyRole),
1641 1642 1643
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
1644 1645 1646
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1647 1648 1649 1650

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1651
			zap.Error(err),
1652
			zap.String("traceID", traceID),
1653
			zap.String("role", typeutil.ProxyRole),
1654 1655 1656
			zap.Int64("msgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
1657 1658 1659 1660
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1661
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1662
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1663
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1664
			metrics.FailLabel).Inc()
1665

1666 1667 1668 1669 1670 1671 1672 1673
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1674 1675 1676
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1677
		zap.String("role", typeutil.ProxyRole),
1678 1679 1680 1681 1682 1683 1684
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1685
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1686
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1687
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1688
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1689
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1690
	return g.result, nil
1691 1692
}

1693
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1694
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1695 1696 1697 1698 1699
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1700 1701 1702 1703 1704

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

1705
	spt := &showPartitionsTask{
G
godchen 已提交
1706 1707 1708
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1709
		rootCoord:             node.rootCoord,
1710
		queryCoord:            node.queryCoord,
G
godchen 已提交
1711
		result:                nil,
1712 1713
	}

1714
	method := "ShowPartitions"
1715 1716
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1717
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1718
		metrics.TotalLabel).Inc()
1719 1720 1721 1722

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1723
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1724
		zap.Any("request", request))
1725 1726 1727 1728 1729 1730

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

X
Xiaofan 已提交
1734
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1735
			metrics.AbandonLabel).Inc()
1736

G
godchen 已提交
1737
		return &milvuspb.ShowPartitionsResponse{
1738
			Status: &commonpb.Status{
1739
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1740 1741 1742 1743 1744
				Reason:    err.Error(),
			},
		}, nil
	}

1745 1746 1747
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1748
		zap.String("role", typeutil.ProxyRole),
1749 1750 1751
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1752 1753
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1754 1755 1756 1757 1758
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1759
			zap.Error(err),
1760
			zap.String("traceID", traceID),
1761
			zap.String("role", typeutil.ProxyRole),
1762 1763 1764 1765 1766 1767
			zap.Int64("msgID", spt.ID()),
			zap.Uint64("BeginTS", spt.BeginTs()),
			zap.Uint64("EndTS", spt.EndTs()),
			zap.String("db", spt.ShowPartitionsRequest.DbName),
			zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
			zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))
D
dragondriver 已提交
1768

X
Xiaofan 已提交
1769
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1770
			metrics.FailLabel).Inc()
1771

G
godchen 已提交
1772
		return &milvuspb.ShowPartitionsResponse{
1773
			Status: &commonpb.Status{
1774
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1775 1776 1777 1778
				Reason:    err.Error(),
			},
		}, nil
	}
1779 1780 1781 1782

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1783
		zap.String("role", typeutil.ProxyRole),
1784 1785 1786 1787 1788 1789 1790
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

X
Xiaofan 已提交
1791
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1792
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1793
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1794 1795 1796
	return spt.result, nil
}

S
SimFG 已提交
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
func (node *Proxy) getCollectionProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest, collectionID int64) (int64, error) {
	resp, err := node.queryCoord.ShowCollections(ctx, &querypb.ShowCollectionsRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowCollections,
			MsgID:     request.Base.MsgID,
			Timestamp: request.Base.Timestamp,
			SourceID:  request.Base.SourceID,
		},
		CollectionIDs: []int64{collectionID},
	})
	if err != nil {
		return 0, err
	}
	if len(resp.InMemoryPercentages) == 0 {
		return 0, errors.New("fail to show collections from the querycoord, no data")
	}
	return resp.InMemoryPercentages[0], nil
}

func (node *Proxy) getPartitionProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest, collectionID int64) (int64, error) {
	IDs2Names := make(map[int64]string)
	partitionIDs := make([]int64, 0)
	for _, partitionName := range request.PartitionNames {
		partitionID, err := globalMetaCache.GetPartitionID(ctx, request.CollectionName, partitionName)
		if err != nil {
			return 0, err
		}
		IDs2Names[partitionID] = partitionName
		partitionIDs = append(partitionIDs, partitionID)
	}
	resp, err := node.queryCoord.ShowPartitions(ctx, &querypb.ShowPartitionsRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_ShowPartitions,
			MsgID:     request.Base.MsgID,
			Timestamp: request.Base.Timestamp,
			SourceID:  request.Base.SourceID,
		},
		CollectionID: collectionID,
		PartitionIDs: partitionIDs,
	})
	if err != nil {
		return 0, err
	}
	if len(resp.InMemoryPercentages) != len(partitionIDs) {
		return 0, errors.New("fail to show partitions from the querycoord, invalid data num")
	}
	var progress int64
	for _, p := range resp.InMemoryPercentages {
		progress += p
	}
	progress /= int64(len(partitionIDs))
	return progress, nil
}

func (node *Proxy) GetLoadingProgress(ctx context.Context, request *milvuspb.GetLoadingProgressRequest) (*milvuspb.GetLoadingProgressResponse, error) {
	if !node.checkHealthy() {
		return &milvuspb.GetLoadingProgressResponse{Status: unhealthyStatus()}, nil
	}
	method := "GetLoadingProgress"
	tr := timerecord.NewTimeRecorder(method)
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ShowPartitions")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

	logger.Info(
		rpcReceived(method),
		zap.String("traceID", traceID),
		zap.Any("request", request))

	getErrResponse := func(err error) *milvuspb.GetLoadingProgressResponse {
		logger.Error("fail to get loading progress", zap.String("collection_name", request.CollectionName),
			zap.Strings("partition_name", request.PartitionNames), zap.Error(err))
		return &milvuspb.GetLoadingProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}
	}
	if err := validateCollectionName(request.CollectionName); err != nil {
		return getErrResponse(err), nil
	}
	collectionID, err := globalMetaCache.GetCollectionID(ctx, request.CollectionName)
	if err != nil {
		return getErrResponse(err), nil
	}
1883 1884 1885 1886 1887
	msgBase := &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     0,
		Timestamp: 0,
		SourceID:  Params.ProxyCfg.GetNodeID(),
S
SimFG 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
	}
	if request.Base == nil {
		request.Base = msgBase
	} else {
		request.Base.MsgID = msgBase.MsgID
		request.Base.Timestamp = msgBase.Timestamp
		request.Base.SourceID = msgBase.SourceID
	}

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

	logger.Info(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.Any("request", request))
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
	return &milvuspb.GetLoadingProgressResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
		},
		Progress: progress,
	}, nil
}

1923
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1924
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1925 1926 1927
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1928 1929 1930 1931 1932

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

1933
	cit := &createIndexTask{
Z
zhenshan.cao 已提交
1934 1935 1936 1937 1938
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		req:        request,
		rootCoord:  node.rootCoord,
		indexCoord: node.indexCoord,
1939 1940
	}

D
dragondriver 已提交
1941
	method := "CreateIndex"
1942
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
1943 1944 1945 1946

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1947
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1948 1949 1950 1951
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1952 1953 1954 1955 1956 1957

	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1958
			zap.String("role", typeutil.ProxyRole),
Z
zhenshan.cao 已提交
1959 1960 1961 1962
			zap.String("db", request.GetDbName()),
			zap.String("collection", request.GetCollectionName()),
			zap.String("field", request.GetFieldName()),
			zap.Any("extra_params", request.GetExtraParams()))
D
dragondriver 已提交
1963

X
Xiaofan 已提交
1964
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1965
			metrics.AbandonLabel).Inc()
1966

1967
		return &commonpb.Status{
1968
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1969 1970 1971 1972
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1973 1974 1975
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1976
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1977 1978 1979
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1980 1981 1982 1983
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1984 1985 1986 1987

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1988
			zap.Error(err),
D
dragondriver 已提交
1989
			zap.String("traceID", traceID),
1990
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1991 1992 1993
			zap.Int64("MsgID", cit.ID()),
			zap.Uint64("BeginTs", cit.BeginTs()),
			zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1994 1995 1996 1997 1998
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

X
Xiaofan 已提交
1999
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2000
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2001
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2002
			metrics.FailLabel).Inc()
2003

2004
		return &commonpb.Status{
2005
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
2006 2007 2008 2009
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2010 2011 2012
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2013
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2014 2015 2016 2017 2018 2019 2020 2021
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))

X
Xiaofan 已提交
2022
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2023
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2024
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2025
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2026
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2027 2028 2029
	return cit.result, nil
}

2030
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
2031
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
2032 2033 2034 2035 2036
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2037 2038 2039 2040 2041

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

2042
	dit := &describeIndexTask{
S
sunby 已提交
2043
		ctx:                  ctx,
2044 2045
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
2046
		indexCoord:           node.indexCoord,
2047 2048
	}

2049 2050 2051
	method := "DescribeIndex"
	// avoid data race
	indexName := request.IndexName
2052
	tr := timerecord.NewTimeRecorder(method)
2053 2054 2055 2056

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2057
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2058 2059 2060
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2061 2062 2063 2064 2065 2066 2067
		zap.String("index name", indexName))

	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2068
			zap.String("role", typeutil.ProxyRole),
2069 2070 2071 2072 2073
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", indexName))

X
Xiaofan 已提交
2074
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2075
			metrics.AbandonLabel).Inc()
2076

2077 2078
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
2079
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2080 2081 2082 2083 2084
				Reason:    err.Error(),
			},
		}, nil
	}

2085 2086 2087
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2088
		zap.String("role", typeutil.ProxyRole),
2089 2090 2091
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2092 2093 2094
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
2095 2096 2097 2098 2099
		zap.String("index name", indexName))

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2100
			zap.Error(err),
2101
			zap.String("traceID", traceID),
2102
			zap.String("role", typeutil.ProxyRole),
2103 2104 2105
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2106 2107 2108
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
2109
			zap.String("index name", indexName))
D
dragondriver 已提交
2110

Z
zhenshan.cao 已提交
2111 2112 2113 2114
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
X
Xiaofan 已提交
2115
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2116
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2117
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2118
			metrics.FailLabel).Inc()
2119

2120 2121
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
2122
				ErrorCode: errCode,
2123 2124 2125 2126 2127
				Reason:    err.Error(),
			},
		}, nil
	}

2128 2129 2130
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2131
		zap.String("role", typeutil.ProxyRole),
2132 2133 2134 2135 2136 2137 2138 2139
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", indexName))

X
Xiaofan 已提交
2140
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2141
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2142
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2143
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2144
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2145 2146 2147
	return dit.result, nil
}

2148
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
2149
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
2150 2151 2152
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2153 2154 2155 2156 2157

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

2158
	dit := &dropIndexTask{
S
sunby 已提交
2159
		ctx:              ctx,
B
BossZou 已提交
2160 2161
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
2162
		indexCoord:       node.indexCoord,
B
BossZou 已提交
2163
	}
G
godchen 已提交
2164

D
dragondriver 已提交
2165
	method := "DropIndex"
2166
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
2167 2168 2169 2170

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2171
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2172 2173 2174 2175 2176
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

D
dragondriver 已提交
2177 2178 2179 2180 2181
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2182
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2183 2184 2185 2186
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2187
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2188
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
2189

B
BossZou 已提交
2190
		return &commonpb.Status{
2191
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2192 2193 2194
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2195

D
dragondriver 已提交
2196 2197 2198
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2199
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2200 2201 2202
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2203 2204 2205 2206
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
D
dragondriver 已提交
2207 2208 2209 2210

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2211
			zap.Error(err),
D
dragondriver 已提交
2212
			zap.String("traceID", traceID),
2213
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2214 2215 2216
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2217 2218 2219 2220 2221
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2222
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2223
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2224
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2225
			metrics.FailLabel).Inc()
2226

B
BossZou 已提交
2227
		return &commonpb.Status{
2228
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2229 2230 2231
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2232 2233 2234 2235

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2236
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2237 2238 2239 2240 2241 2242 2243 2244
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2245
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2246
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2247
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2248
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2249
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
2250 2251 2252
	return dit.result, nil
}

2253 2254
// 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.
2255
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2256
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
2257 2258 2259 2260 2261
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2262 2263 2264 2265 2266

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

2267
	gibpt := &getIndexBuildProgressTask{
2268 2269 2270
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
2271 2272
		indexCoord:                   node.indexCoord,
		rootCoord:                    node.rootCoord,
2273
		dataCoord:                    node.dataCoord,
2274 2275
	}

2276
	method := "GetIndexBuildProgress"
2277
	tr := timerecord.NewTimeRecorder(method)
2278 2279 2280 2281

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2282
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2283 2284 2285 2286
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2287 2288 2289 2290 2291 2292

	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2293
			zap.String("role", typeutil.ProxyRole),
2294 2295 2296 2297
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2298
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2299
			metrics.AbandonLabel).Inc()
2300

2301 2302 2303 2304 2305 2306 2307 2308
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2309 2310 2311
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2312
		zap.String("role", typeutil.ProxyRole),
2313 2314 2315
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
2316 2317 2318 2319
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2320 2321 2322 2323

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
2324
			zap.Error(err),
2325
			zap.String("traceID", traceID),
2326
			zap.String("role", typeutil.ProxyRole),
2327 2328 2329
			zap.Int64("MsgID", gibpt.ID()),
			zap.Uint64("BeginTs", gibpt.BeginTs()),
			zap.Uint64("EndTs", gibpt.EndTs()),
2330 2331 2332 2333
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2334
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2335
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2336
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2337
			metrics.FailLabel).Inc()
2338 2339 2340 2341 2342 2343 2344 2345

		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2346 2347 2348 2349

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2350
		zap.String("role", typeutil.ProxyRole),
2351 2352 2353 2354 2355 2356 2357 2358
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName),
		zap.Any("result", gibpt.result))
2359

X
Xiaofan 已提交
2360
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2361
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2362
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2363
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2364
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2365
	return gibpt.result, nil
2366 2367
}

2368
// GetIndexState get the build-state of index.
2369
// Deprecated: use DescribeIndex instead
C
Cai Yudong 已提交
2370
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
2371 2372 2373 2374 2375
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2376 2377 2378 2379 2380

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

2381
	dipt := &getIndexStateTask{
G
godchen 已提交
2382 2383 2384
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
2385 2386
		indexCoord:           node.indexCoord,
		rootCoord:            node.rootCoord,
2387 2388
	}

2389
	method := "GetIndexState"
2390
	tr := timerecord.NewTimeRecorder(method)
2391 2392 2393 2394

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2395
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2396 2397 2398 2399
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2400 2401 2402 2403 2404 2405

	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2406
			zap.String("role", typeutil.ProxyRole),
2407 2408 2409 2410 2411
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2412
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2413
			metrics.AbandonLabel).Inc()
2414

G
godchen 已提交
2415
		return &milvuspb.GetIndexStateResponse{
2416
			Status: &commonpb.Status{
2417
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2418 2419 2420 2421 2422
				Reason:    err.Error(),
			},
		}, nil
	}

2423 2424 2425
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2426
		zap.String("role", typeutil.ProxyRole),
2427 2428 2429
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2430 2431 2432 2433
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2434 2435 2436 2437

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2438
			zap.Error(err),
2439
			zap.String("traceID", traceID),
2440
			zap.String("role", typeutil.ProxyRole),
2441 2442 2443
			zap.Int64("MsgID", dipt.ID()),
			zap.Uint64("BeginTs", dipt.BeginTs()),
			zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2444 2445 2446 2447 2448
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2449
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2450
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2451
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2452
			metrics.FailLabel).Inc()
2453

G
godchen 已提交
2454
		return &milvuspb.GetIndexStateResponse{
2455
			Status: &commonpb.Status{
2456
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2457 2458 2459 2460 2461
				Reason:    err.Error(),
			},
		}, nil
	}

2462 2463 2464
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2465
		zap.String("role", typeutil.ProxyRole),
2466 2467 2468 2469 2470 2471 2472 2473
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2474
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2475
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2476
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2477
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2478
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2479 2480 2481
	return dipt.result, nil
}

2482
// Insert insert records into collection.
C
Cai Yudong 已提交
2483
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
X
Xiangyu Wang 已提交
2484 2485 2486 2487 2488 2489
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Insert")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
	log.Info("Start processing insert request in Proxy", zap.String("traceID", traceID))
	defer log.Info("Finish processing insert request in Proxy", zap.String("traceID", traceID))

2490 2491 2492 2493 2494
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2495 2496
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
2497
	receiveSize := proto.Size(request)
2498 2499
	rateCol.Add(internalpb.RateType_DMLInsert.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Add(float64(receiveSize))
D
dragondriver 已提交
2500

2501 2502 2503 2504 2505
	defer func() {
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.TotalLabel).Inc()
	}()

2506
	it := &insertTask{
2507 2508
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2509
		// req:       request,
2510 2511 2512 2513
		BaseInsertTask: BaseInsertTask{
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2514
			InsertRequest: internalpb.InsertRequest{
2515
				Base: &commonpb.MsgBase{
X
xige-16 已提交
2516 2517
					MsgType:  commonpb.MsgType_Insert,
					MsgID:    0,
X
Xiaofan 已提交
2518
					SourceID: Params.ProxyCfg.GetNodeID(),
2519 2520 2521
				},
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2522 2523 2524
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
				Version:        internalpb.InsertDataVersion_ColumnBased,
2525
				// RowData: transfer column based request to this
2526 2527
			},
		},
2528
		idAllocator:   node.rowIDAllocator,
2529 2530 2531
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2532
	}
2533 2534

	if len(it.PartitionName) <= 0 {
2535
		it.PartitionName = Params.CommonCfg.DefaultPartitionName
2536 2537
	}

X
Xiangyu Wang 已提交
2538
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2539
		numRows := request.NumRows
2540 2541 2542 2543
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2544

X
Xiangyu Wang 已提交
2545 2546 2547 2548 2549 2550 2551
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2552 2553
	}

X
Xiangyu Wang 已提交
2554
	log.Debug("Enqueue insert request in Proxy",
2555
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2556 2557 2558 2559 2560
		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)),
2561 2562
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))
D
dragondriver 已提交
2563

X
Xiangyu Wang 已提交
2564 2565
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Debug("Failed to enqueue insert task: " + err.Error())
2566 2567
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2568
		return constructFailedResponse(err), nil
2569
	}
D
dragondriver 已提交
2570

X
Xiangyu Wang 已提交
2571
	log.Debug("Detail of insert request in Proxy",
2572
		zap.String("role", typeutil.ProxyRole),
X
Xiangyu Wang 已提交
2573
		zap.Int64("msgID", it.Base.MsgID),
D
dragondriver 已提交
2574 2575 2576 2577 2578
		zap.Uint64("BeginTS", it.BeginTs()),
		zap.Uint64("EndTS", it.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
X
Xiangyu Wang 已提交
2579 2580 2581 2582 2583
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))

	if err := it.WaitToFinish(); err != nil {
		log.Debug("Failed to execute insert task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
2584
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2585
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2586 2587 2588 2589 2590
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2591
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
			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 已提交
2603
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2604

2605
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2606
		metrics.SuccessLabel).Inc()
2607 2608
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(successCnt))
2609
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2610 2611 2612
	return it.result, nil
}

2613
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2614
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
2615 2616 2617
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Delete")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2618 2619
	log.Info("Start processing delete request in Proxy", zap.String("traceID", traceID))
	defer log.Info("Finish processing delete request in Proxy", zap.String("traceID", traceID))
2620

2621
	receiveSize := proto.Size(request)
2622 2623
	rateCol.Add(internalpb.RateType_DMLDelete.String(), float64(receiveSize))
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Add(float64(receiveSize))
2624

G
groot 已提交
2625 2626 2627 2628 2629 2630
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2631 2632 2633
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

2634 2635
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2636
	dt := &deleteTask{
X
xige-16 已提交
2637 2638 2639
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
G
godchen 已提交
2640
		BaseDeleteTask: BaseDeleteTask{
G
godchen 已提交
2641 2642 2643
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2644 2645 2646 2647 2648
			DeleteRequest: internalpb.DeleteRequest{
				Base: &commonpb.MsgBase{
					MsgType: commonpb.MsgType_Delete,
					MsgID:   0,
				},
X
xige-16 已提交
2649
				DbName:         request.DbName,
G
godchen 已提交
2650 2651 2652
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2653 2654 2655 2656
			},
		},
		chMgr:    node.chMgr,
		chTicker: node.chTicker,
G
groot 已提交
2657 2658
	}

2659
	log.Debug("Enqueue delete request in Proxy",
2660
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2661 2662 2663 2664
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2665 2666 2667 2668

	// MsgID will be set by Enqueue()
	if err := node.sched.dmQueue.Enqueue(dt); err != nil {
		log.Error("Failed to enqueue delete task: "+err.Error(), zap.String("traceID", traceID))
X
Xiaofan 已提交
2669
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2670
			metrics.FailLabel).Inc()
2671

G
groot 已提交
2672 2673 2674 2675 2676 2677 2678 2679
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2680
	log.Debug("Detail of delete request in Proxy",
2681
		zap.String("role", typeutil.ProxyRole),
G
groot 已提交
2682 2683 2684 2685 2686
		zap.Int64("msgID", dt.Base.MsgID),
		zap.Uint64("timestamp", dt.Base.Timestamp),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
2687 2688
		zap.String("expr", request.Expr),
		zap.String("traceID", traceID))
G
groot 已提交
2689

2690 2691
	if err := dt.WaitToFinish(); err != nil {
		log.Error("Failed to execute delete task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
X
Xiaofan 已提交
2692
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2693
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2694
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2695
			metrics.FailLabel).Inc()
G
groot 已提交
2696 2697 2698 2699 2700 2701 2702 2703
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

X
Xiaofan 已提交
2704
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2705
		metrics.SuccessLabel).Inc()
2706
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2707 2708 2709
	return dt.result, nil
}

2710
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2711
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2712 2713 2714 2715 2716
	receiveSize := proto.Size(request)
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.SearchLabel).Add(float64(receiveSize))

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

2717 2718 2719 2720 2721
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2722 2723
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
2724 2725
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2726

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

2730
	qt := &searchTask{
S
sunby 已提交
2731
		ctx:       ctx,
2732
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2733
		SearchRequest: &internalpb.SearchRequest{
2734
			Base: &commonpb.MsgBase{
2735
				MsgType:  commonpb.MsgType_Search,
X
Xiaofan 已提交
2736
				SourceID: Params.ProxyCfg.GetNodeID(),
2737
			},
2738
			ReqID: Params.ProxyCfg.GetNodeID(),
2739
		},
2740 2741 2742 2743
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2744 2745
	}

2746 2747 2748
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

Z
Zach 已提交
2749
	log.Ctx(ctx).Info(
2750
		rpcReceived(method),
2751
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2752 2753 2754 2755 2756
		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)),
2757 2758 2759 2760
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2761

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

2777 2778
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
2779

2780 2781
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2782
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2783 2784 2785 2786
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
2787
	tr.CtxRecord(ctx, "search request enqueue")
2788

Z
Zach 已提交
2789
	log.Ctx(ctx).Debug(
2790
		rpcEnqueued(method),
2791
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2792
		zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2793 2794 2795 2796 2797
		zap.Uint64("timestamp", qt.Base.Timestamp),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames),
		zap.Any("dsl", request.Dsl),
2798
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2799 2800 2801 2802
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2803

2804
	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
2805
		log.Ctx(ctx).Warn(
2806
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2807
			zap.Error(err),
2808
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2809
			zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2810 2811 2812 2813
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
2814
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2815 2816 2817 2818
			zap.Any("OutputFields", request.OutputFields),
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
2819

2820 2821
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
2822

2823 2824
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2825
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2826 2827 2828 2829 2830
				Reason:    err.Error(),
			},
		}, nil
	}

Z
Zach 已提交
2831
	span := tr.CtxRecord(ctx, "wait search result")
2832 2833
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
Z
Zach 已提交
2834
	log.Ctx(ctx).Debug(
2835
		rpcDone(method),
2836
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2837 2838 2839 2840 2841 2842
		zap.Int64("msgID", qt.ID()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames),
		zap.Any("dsl", request.Dsl),
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2843 2844 2845 2846
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2847

2848 2849 2850
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()
	metrics.ProxySearchVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(qt.result.GetResults().GetNumQueries()))
C
cai.zhang 已提交
2851
	searchDur := tr.ElapseSpan().Milliseconds()
X
Xiaofan 已提交
2852
	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2853
		metrics.SearchLabel).Observe(float64(searchDur))
2854 2855 2856 2857

	if qt.result != nil {
		sentSize := proto.Size(qt.result)
		metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
2858
		rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
2859
	}
2860 2861 2862
	return qt.result, nil
}

2863
// Flush notify data nodes to persist the data of collection.
2864 2865 2866 2867 2868 2869 2870
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2871
	if !node.checkHealthy() {
2872 2873
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2874
	}
D
dragondriver 已提交
2875 2876 2877 2878 2879

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

2880
	ft := &flushTask{
T
ThreadDao 已提交
2881 2882 2883
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2884
		dataCoord:    node.dataCoord,
2885 2886
	}

D
dragondriver 已提交
2887
	method := "Flush"
2888
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
2889
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2890 2891 2892 2893

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2894
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2895 2896
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2897 2898 2899 2900 2901 2902

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

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

2909 2910
		resp.Status.Reason = err.Error()
		return resp, nil
2911 2912
	}

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

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2926
			zap.Error(err),
D
dragondriver 已提交
2927
			zap.String("traceID", traceID),
2928
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2929 2930 2931
			zap.Int64("MsgID", ft.ID()),
			zap.Uint64("BeginTs", ft.BeginTs()),
			zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2932 2933 2934
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

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

D
dragondriver 已提交
2937
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2938 2939
		resp.Status.Reason = err.Error()
		return resp, nil
2940 2941
	}

D
dragondriver 已提交
2942 2943 2944
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2945
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2946 2947 2948 2949 2950 2951
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))

X
Xiaofan 已提交
2952 2953
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2954
	return ft.result, nil
2955 2956
}

2957
// Query get the records by primary keys.
C
Cai Yudong 已提交
2958
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2959 2960 2961 2962 2963
	receiveSize := proto.Size(request)
	metrics.ProxyReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.QueryLabel).Add(float64(receiveSize))

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

2964 2965 2966 2967 2968
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2969

D
dragondriver 已提交
2970 2971
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Query")
	defer sp.Finish()
2972
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2973

2974
	qt := &queryTask{
2975 2976 2977 2978 2979
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
			Base: &commonpb.MsgBase{
				MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
2980
				SourceID: Params.ProxyCfg.GetNodeID(),
2981
			},
2982
			ReqID: Params.ProxyCfg.GetNodeID(),
2983
		},
2984 2985
		request:          request,
		qc:               node.queryCoord,
2986
		queryShardPolicy: mergeRoundRobinPolicy,
2987
		shardMgr:         node.shardMgr,
2988 2989
	}

D
dragondriver 已提交
2990 2991
	method := "Query"

2992 2993 2994
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()

Z
Zach 已提交
2995
	log.Ctx(ctx).Info(
D
dragondriver 已提交
2996
		rpcReceived(method),
2997
		zap.String("role", typeutil.ProxyRole),
2998 2999
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
3000 3001 3002 3003 3004
		zap.Strings("partitions", request.PartitionNames),
		zap.String("expr", request.Expr),
		zap.Strings("OutputFields", request.OutputFields),
		zap.Uint64("travel_timestamp", request.TravelTimestamp),
		zap.Uint64("guarantee_timestamp", request.GuaranteeTimestamp))
G
godchen 已提交
3005

D
dragondriver 已提交
3006
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
Z
Zach 已提交
3007
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
3008 3009 3010
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("role", typeutil.ProxyRole),
3011 3012 3013
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
3014

3015 3016 3017
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()

3018 3019 3020 3021 3022 3023
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
3024
	}
Z
Zach 已提交
3025
	tr.CtxRecord(ctx, "query request enqueue")
3026

Z
Zach 已提交
3027
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
3028
		rpcEnqueued(method),
3029
		zap.String("role", typeutil.ProxyRole),
3030
		zap.Int64("msgID", qt.ID()),
3031 3032
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
3033
		zap.Strings("partitions", request.PartitionNames))
D
dragondriver 已提交
3034 3035

	if err := qt.WaitToFinish(); err != nil {
Z
Zach 已提交
3036
		log.Ctx(ctx).Warn(
D
dragondriver 已提交
3037 3038
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
3039
			zap.String("role", typeutil.ProxyRole),
3040
			zap.Int64("msgID", qt.ID()),
3041 3042 3043
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
3044

3045 3046
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.FailLabel).Inc()
3047

3048 3049 3050 3051 3052 3053 3054
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
Z
Zach 已提交
3055
	span := tr.CtxRecord(ctx, "wait query result")
3056 3057
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
Z
Zach 已提交
3058
	log.Ctx(ctx).Debug(
D
dragondriver 已提交
3059 3060
		rpcDone(method),
		zap.String("role", typeutil.ProxyRole),
3061
		zap.Int64("msgID", qt.ID()),
3062 3063 3064
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
3065

3066 3067 3068 3069
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()

	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
3070
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
3071 3072

	ret := &milvuspb.QueryResults{
3073 3074
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
3075 3076
	}
	sentSize := proto.Size(qt.result)
3077
	rateCol.Add(metricsinfo.ReadResultThroughput, float64(sentSize))
3078 3079
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
	return ret, nil
3080
}
3081

3082
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
3083 3084 3085 3086
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3087 3088 3089 3090 3091

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

Y
Yusup 已提交
3092 3093 3094 3095 3096 3097 3098
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
3099
	method := "CreateAlias"
3100
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3101
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120

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

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

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

Y
Yusup 已提交
3123 3124 3125 3126 3127 3128
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3129 3130 3131
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3132
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3133 3134 3135 3136
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3137 3138
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3139 3140 3141 3142

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3143
			zap.Error(err),
D
dragondriver 已提交
3144
			zap.String("traceID", traceID),
3145
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3146 3147 3148 3149
			zap.Int64("MsgID", cat.ID()),
			zap.Uint64("BeginTs", cat.BeginTs()),
			zap.Uint64("EndTs", cat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3150 3151
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
X
Xiaofan 已提交
3152
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
3153 3154 3155 3156 3157 3158 3159

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

D
dragondriver 已提交
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
3171 3172
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3173 3174 3175
	return cat.result, nil
}

3176
// DropAlias alter the alias of collection.
Y
Yusup 已提交
3177 3178 3179 3180
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3181 3182 3183 3184 3185

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

Y
Yusup 已提交
3186 3187 3188 3189 3190 3191 3192
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
3193
	method := "DropAlias"
3194
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3195
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211

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

	if err := node.sched.ddQueue.Enqueue(dat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("alias", request.Alias))
X
Xiaofan 已提交
3212
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3213

Y
Yusup 已提交
3214 3215 3216 3217 3218 3219
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3220 3221 3222
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3223
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3224 3225 3226 3227
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3228
		zap.String("alias", request.Alias))
D
dragondriver 已提交
3229 3230 3231 3232

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3233
			zap.Error(err),
D
dragondriver 已提交
3234
			zap.String("traceID", traceID),
3235
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3236 3237 3238 3239
			zap.Int64("MsgID", dat.ID()),
			zap.Uint64("BeginTs", dat.BeginTs()),
			zap.Uint64("EndTs", dat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3240 3241
			zap.String("alias", request.Alias))

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

Y
Yusup 已提交
3244 3245 3246 3247 3248 3249
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias))

X
Xiaofan 已提交
3260 3261
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3262 3263 3264
	return dat.result, nil
}

3265
// AlterAlias alter alias of collection.
Y
Yusup 已提交
3266 3267 3268 3269
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3270 3271 3272 3273 3274

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

Y
Yusup 已提交
3275 3276 3277 3278 3279 3280 3281
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
3282
	method := "AlterAlias"
3283
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3284
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302

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

	if err := node.sched.ddQueue.Enqueue(aat); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
			zap.String("db", request.DbName),
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
X
Xiaofan 已提交
3303
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
D
dragondriver 已提交
3304

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

D
dragondriver 已提交
3311 3312 3313
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3314
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3315 3316 3317 3318
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3319 3320
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3321 3322 3323 3324

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3325
			zap.Error(err),
D
dragondriver 已提交
3326
			zap.String("traceID", traceID),
3327
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3328 3329 3330 3331
			zap.Int64("MsgID", aat.ID()),
			zap.Uint64("BeginTs", aat.BeginTs()),
			zap.Uint64("EndTs", aat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3332 3333 3334
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

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

Y
Yusup 已提交
3337 3338 3339 3340 3341 3342
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
3354 3355
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.SuccessLabel).Inc()
	metrics.ProxyDDLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
Y
Yusup 已提交
3356 3357 3358
	return aat.result, nil
}

3359
// CalcDistance calculates the distances between vectors.
3360
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
3361 3362 3363 3364 3365
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
3366

3367 3368 3369 3370
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CalcDistance")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

3371 3372
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
3373

3374 3375 3376 3377 3378
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
3379 3380
		}

3381
		qt := &queryTask{
3382 3383 3384 3385 3386
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
				Base: &commonpb.MsgBase{
					MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
3387
					SourceID: Params.ProxyCfg.GetNodeID(),
3388
				},
3389
				ReqID: Params.ProxyCfg.GetNodeID(),
3390
			},
3391 3392 3393 3394
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

3395
			queryShardPolicy: mergeRoundRobinPolicy,
3396
			shardMgr:         node.shardMgr,
3397 3398
		}

G
groot 已提交
3399 3400 3401 3402 3403 3404
		items := []zapcore.Field{
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
			zap.Any("OutputFields", queryRequest.OutputFields),
		}

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

3409 3410 3411 3412 3413
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3414
			}, err
3415
		}
3416

G
groot 已提交
3417
		log.Debug("CalcDistance queryTask enqueued", items...)
3418 3419 3420

		err = qt.WaitToFinish()
		if err != nil {
G
groot 已提交
3421
			log.Error("CalcDistance queryTask failed to WaitToFinish", append(items, zap.Error(err))...)
3422 3423 3424 3425 3426 3427

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3428
			}, err
3429
		}
3430

G
groot 已提交
3431
		log.Debug("CalcDistance queryTask Done", items...)
3432 3433

		return &milvuspb.QueryResults{
3434 3435
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
3436 3437 3438
		}, nil
	}

G
groot 已提交
3439 3440 3441 3442
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
		traceID:   traceID,
		queryFunc: query,
3443 3444
	}

G
groot 已提交
3445
	return task.Execute(ctx, request)
3446 3447
}

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

3453
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3454
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
D
dragondriver 已提交
3455
	log.Debug("GetPersistentSegmentInfo",
3456
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3457 3458 3459
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3460
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3461
		Status: &commonpb.Status{
3462
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3463 3464
		},
	}
3465 3466 3467 3468
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3469 3470
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3471
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3472
		metrics.TotalLabel).Inc()
G
godchen 已提交
3473
	segments, err := node.getSegmentsOfCollection(ctx, req.DbName, req.CollectionName)
X
XuanYang-cn 已提交
3474
	if err != nil {
3475
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3476 3477
		return resp, nil
	}
3478
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
X
XuanYang-cn 已提交
3479
		Base: &commonpb.MsgBase{
3480
			MsgType:   commonpb.MsgType_SegmentInfo,
X
XuanYang-cn 已提交
3481 3482
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3483
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3484 3485 3486 3487
		},
		SegmentIDs: segments,
	})
	if err != nil {
3488
		log.Debug("GetPersistentSegmentInfo fail", zap.Error(err))
3489
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3490 3491
		return resp, nil
	}
3492
	log.Debug("GetPersistentSegmentInfo ", zap.Int("len(infos)", len(infoResp.Infos)), zap.Any("status", infoResp.Status))
3493
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3494 3495 3496 3497 3498 3499
		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 已提交
3500
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3501 3502
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3503
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3504 3505 3506
			State:        info.State,
		}
	}
X
Xiaofan 已提交
3507
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3508
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
3509
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3510
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3511 3512 3513 3514
	resp.Infos = persistentInfos
	return resp, nil
}

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

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

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

C
Cai Yudong 已提交
3577
func (node *Proxy) getSegmentsOfCollection(ctx context.Context, dbName string, collectionName string) ([]UniqueID, error) {
3578
	describeCollectionResponse, err := node.rootCoord.DescribeCollection(ctx, &milvuspb.DescribeCollectionRequest{
X
XuanYang-cn 已提交
3579
		Base: &commonpb.MsgBase{
3580
			MsgType:   commonpb.MsgType_DescribeCollection,
X
XuanYang-cn 已提交
3581 3582
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3583
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3584 3585 3586 3587 3588 3589 3590
		},
		DbName:         dbName,
		CollectionName: collectionName,
	})
	if err != nil {
		return nil, err
	}
3591
	if describeCollectionResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3592 3593 3594
		return nil, errors.New(describeCollectionResponse.Status.Reason)
	}
	collectionID := describeCollectionResponse.CollectionID
3595
	showPartitionsResp, err := node.rootCoord.ShowPartitions(ctx, &milvuspb.ShowPartitionsRequest{
X
XuanYang-cn 已提交
3596
		Base: &commonpb.MsgBase{
3597
			MsgType:   commonpb.MsgType_ShowPartitions,
X
XuanYang-cn 已提交
3598 3599
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3600
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3601 3602 3603 3604 3605 3606 3607 3608
		},
		DbName:         dbName,
		CollectionName: collectionName,
		CollectionID:   collectionID,
	})
	if err != nil {
		return nil, err
	}
3609
	if showPartitionsResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3610 3611 3612 3613 3614
		return nil, errors.New(showPartitionsResp.Status.Reason)
	}

	ret := make([]UniqueID, 0)
	for _, partitionID := range showPartitionsResp.PartitionIDs {
3615
		getSegmentsByStatesResponse, err := node.dataCoord.GetSegmentsByStates(ctx, &datapb.GetSegmentsByStatesRequest{
X
XuanYang-cn 已提交
3616 3617
			CollectionID: collectionID,
			PartitionID:  partitionID,
3618
			States:       []commonpb.SegmentState{commonpb.SegmentState_Flushing, commonpb.SegmentState_Flushed, commonpb.SegmentState_Sealed},
X
XuanYang-cn 已提交
3619 3620 3621 3622
		})
		if err != nil {
			return nil, err
		}
3623 3624
		if getSegmentsByStatesResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
			return nil, errors.New(getSegmentsByStatesResponse.Status.Reason)
X
XuanYang-cn 已提交
3625
		}
3626
		ret = append(ret, getSegmentsByStatesResponse.GetSegments()...)
X
XuanYang-cn 已提交
3627 3628 3629
	}
	return ret, nil
}
3630

J
jingkl 已提交
3631
// Dummy handles dummy request
C
Cai Yudong 已提交
3632
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643
	failedResponse := &milvuspb.DummyResponse{
		Response: `{"status": "fail"}`,
	}

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

3644 3645
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3646
		if err != nil {
3647
			log.Debug("Failed to parse dummy query request")
3648 3649 3650
			return failedResponse, nil
		}

3651
		request := &milvuspb.QueryRequest{
3652 3653 3654
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3655
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3656 3657
		}

3658
		_, err = node.Query(ctx, request)
3659
		if err != nil {
3660
			log.Debug("Failed to execute dummy query")
3661 3662
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3663 3664 3665 3666 3667 3668

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

3669 3670
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3671 3672
}

J
jingkl 已提交
3673
// RegisterLink registers a link
C
Cai Yudong 已提交
3674
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
3675
	code := node.stateCode.Load().(commonpb.StateCode)
D
dragondriver 已提交
3676
	log.Debug("RegisterLink",
3677
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3678
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3679

3680
	if code != commonpb.StateCode_Healthy {
3681 3682 3683
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3684
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3685
				Reason:    "proxy not healthy",
3686 3687 3688
			},
		}, nil
	}
X
Xiaofan 已提交
3689
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Inc()
3690 3691 3692
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3693
			ErrorCode: commonpb.ErrorCode_Success,
3694
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3695 3696 3697
		},
	}, nil
}
3698

3699
// GetMetrics gets the metrics of proxy
3700 3701 3702
// TODO(dragondriver): cache the Metrics and set a retention to the cache
func (node *Proxy) GetMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	log.Debug("Proxy.GetMetrics",
X
Xiaofan 已提交
3703
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3704 3705 3706 3707
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
X
Xiaofan 已提交
3708
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3709
			zap.String("req", req.Request),
X
Xiaofan 已提交
3710
			zap.Error(errProxyIsUnhealthy(Params.ProxyCfg.GetNodeID())))
3711 3712 3713 3714

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
Xiaofan 已提交
3715
				Reason:    msgProxyIsUnhealthy(Params.ProxyCfg.GetNodeID()),
3716 3717 3718 3719 3720 3721 3722 3723
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
X
Xiaofan 已提交
3724
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
			zap.String("req", req.Request),
			zap.Error(err))

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

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

D
dragondriver 已提交
3740 3741
	req.Base = &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
3742
		MsgID:     0,
D
dragondriver 已提交
3743
		Timestamp: 0,
X
Xiaofan 已提交
3744
		SourceID:  Params.ProxyCfg.GetNodeID(),
D
dragondriver 已提交
3745 3746
	}

3747
	if metricType == metricsinfo.SystemInfoMetrics {
3748 3749 3750 3751 3752 3753 3754
		ret, err := node.metricsCacheManager.GetSystemInfoMetrics()
		if err == nil && ret != nil {
			return ret, nil
		}
		log.Debug("failed to get system info metrics from cache, recompute instead",
			zap.Error(err))

3755
		metrics, err := getSystemInfoMetrics(ctx, req, node)
3756 3757

		log.Debug("Proxy.GetMetrics",
X
Xiaofan 已提交
3758
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3759 3760 3761 3762 3763
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3764 3765
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3766
		return metrics, nil
3767 3768 3769
	}

	log.Debug("Proxy.GetMetrics failed, request metric type is not implemented yet",
X
Xiaofan 已提交
3770
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782
		zap.String("req", req.Request),
		zap.String("metric_type", metricType))

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

3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
// GetProxyMetrics gets the metrics of proxy, it's an internal interface which is different from GetMetrics interface,
// because it only obtains the metrics of Proxy, not including the topological metrics of Query cluster and Data cluster.
func (node *Proxy) GetProxyMetrics(ctx context.Context, req *milvuspb.GetMetricsRequest) (*milvuspb.GetMetricsResponse, error) {
	log.Debug("Proxy.GetProxyMetrics",
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
		zap.String("req", req.Request))

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

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

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

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

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

	req.Base = &commonpb.MsgBase{
3823 3824 3825 3826
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     0,
		Timestamp: 0,
		SourceID:  Params.ProxyCfg.GetNodeID(),
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
	}

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

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

		log.Debug("Proxy.GetProxyMetrics",
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Error(err))

		return proxyMetrics, nil
	}

	log.Debug("Proxy.GetProxyMetrics failed, request metric type is not implemented yet",
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
		zap.String("req", req.Request),
		zap.String("metric_type", metricType))

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

B
bigsheeper 已提交
3867 3868 3869
// LoadBalance would do a load balancing operation between query nodes
func (node *Proxy) LoadBalance(ctx context.Context, req *milvuspb.LoadBalanceRequest) (*commonpb.Status, error) {
	log.Debug("Proxy.LoadBalance",
X
Xiaofan 已提交
3870
		zap.Int64("proxy_id", Params.ProxyCfg.GetNodeID()),
B
bigsheeper 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3880 3881 3882 3883 3884 3885 3886

	collectionID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	if err != nil {
		log.Error("failed to get collection id", zap.String("collection name", req.GetCollectionName()), zap.Error(err))
		status.Reason = err.Error()
		return status, nil
	}
B
bigsheeper 已提交
3887 3888 3889 3890 3891
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_LoadBalanceSegments,
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3892
			SourceID:  Params.ProxyCfg.GetNodeID(),
B
bigsheeper 已提交
3893 3894 3895
		},
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3896
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3897
		SealedSegmentIDs: req.SealedSegmentIDs,
3898
		CollectionID:     collectionID,
B
bigsheeper 已提交
3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915
	})
	if err != nil {
		log.Error("Failed to LoadBalance from Query Coordinator",
			zap.Any("req", req), zap.Error(err))
		status.Reason = err.Error()
		return status, nil
	}
	if infoResp.ErrorCode != commonpb.ErrorCode_Success {
		log.Error("Failed to LoadBalance from Query Coordinator", zap.String("errMsg", infoResp.Reason))
		status.Reason = infoResp.Reason
		return status, nil
	}
	log.Debug("LoadBalance Done", zap.Any("req", req), zap.Any("status", infoResp))
	status.ErrorCode = commonpb.ErrorCode_Success
	return status, nil
}

J
jingkl 已提交
3916
//GetCompactionState gets the compaction state of multiple segments
3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929
func (node *Proxy) GetCompactionState(ctx context.Context, req *milvuspb.GetCompactionStateRequest) (*milvuspb.GetCompactionStateResponse, error) {
	log.Info("received GetCompactionState request", zap.Int64("compactionID", req.GetCompactionID()))
	resp := &milvuspb.GetCompactionStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

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

3930
// ManualCompaction invokes compaction on specified collection
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
func (node *Proxy) ManualCompaction(ctx context.Context, req *milvuspb.ManualCompactionRequest) (*milvuspb.ManualCompactionResponse, error) {
	log.Info("received ManualCompaction request", zap.Int64("collectionID", req.GetCollectionID()))
	resp := &milvuspb.ManualCompactionResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

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

3944
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
func (node *Proxy) GetCompactionStateWithPlans(ctx context.Context, req *milvuspb.GetCompactionPlansRequest) (*milvuspb.GetCompactionPlansResponse, error) {
	log.Info("received GetCompactionStateWithPlans request", zap.Int64("compactionID", req.GetCompactionID()))
	resp := &milvuspb.GetCompactionPlansResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

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

B
Bingyi Sun 已提交
3958 3959 3960
// GetFlushState gets the flush state of multiple segments
func (node *Proxy) GetFlushState(ctx context.Context, req *milvuspb.GetFlushStateRequest) (*milvuspb.GetFlushStateResponse, error) {
	log.Info("received get flush state request", zap.Any("request", req))
3961
	var err error
B
Bingyi Sun 已提交
3962 3963 3964 3965 3966 3967 3968
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Info("unable to get flush state because of closed server")
		return resp, nil
	}

3969
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3970 3971 3972 3973
	if err != nil {
		log.Info("failed to get flush state response", zap.Error(err))
		return nil, err
	}
B
Bingyi Sun 已提交
3974 3975 3976 3977
	log.Info("received get flush state response", zap.Any("response", resp))
	return resp, err
}

C
Cai Yudong 已提交
3978 3979
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3980 3981
	code := node.stateCode.Load().(commonpb.StateCode)
	return code == commonpb.StateCode_Healthy
3982 3983
}

3984 3985 3986
func (node *Proxy) checkHealthyAndReturnCode() (commonpb.StateCode, bool) {
	code := node.stateCode.Load().(commonpb.StateCode)
	return code, code == commonpb.StateCode_Healthy
3987 3988
}

J
jingkl 已提交
3989
//unhealthyStatus returns the proxy not healthy status
3990 3991 3992
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3993
		Reason:    "proxy not healthy",
3994 3995
	}
}
G
groot 已提交
3996 3997 3998

// 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) {
3999 4000 4001
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
		zap.Bool("row-based", req.GetRowBased()))
4002 4003 4004 4005 4006 4007
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
4008 4009 4010 4011
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
4012
	// Call rootCoord to finish import.
4013 4014 4015 4016 4017 4018 4019 4020
	respFromRC, err := node.rootCoord.Import(ctx, req)
	if err != nil {
		log.Error("failed to execute bulk load request", zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
	}
	return respFromRC, nil
G
groot 已提交
4021 4022
}

4023
// GetImportState checks import task state from RootCoord.
G
groot 已提交
4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
func (node *Proxy) GetImportState(ctx context.Context, req *milvuspb.GetImportStateRequest) (*milvuspb.GetImportStateResponse, error) {
	log.Info("received get import state request", zap.Int64("taskID", req.GetTask()))
	resp := &milvuspb.GetImportStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

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

// ListImportTasks get id array of all import tasks from rootcoord
func (node *Proxy) ListImportTasks(ctx context.Context, req *milvuspb.ListImportTasksRequest) (*milvuspb.ListImportTasksResponse, error) {
	log.Info("received list import tasks request")
	resp := &milvuspb.ListImportTasksResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

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

X
XuanYang-cn 已提交
4051 4052 4053 4054 4055 4056 4057 4058 4059
// GetReplicas gets replica info
func (node *Proxy) GetReplicas(ctx context.Context, req *milvuspb.GetReplicasRequest) (*milvuspb.GetReplicasResponse, error) {
	log.Info("received get replicas request")
	resp := &milvuspb.GetReplicasResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}

4060 4061
	req.Base = &commonpb.MsgBase{
		MsgType:  commonpb.MsgType_GetReplicas,
X
Xiaofan 已提交
4062
		SourceID: Params.ProxyCfg.GetNodeID(),
4063 4064
	}

X
XuanYang-cn 已提交
4065 4066 4067 4068 4069
	resp, err := node.queryCoord.GetReplicas(ctx, req)
	log.Info("received get replicas response", zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

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

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

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

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

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

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

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

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

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

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

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

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

func (node *Proxy) ListCredUsers(ctx context.Context, req *milvuspb.ListCredUsersRequest) (*milvuspb.ListCredUsersResponse, error) {
4259 4260
	log.Debug("ListCredUsers", zap.String("role", typeutil.ProxyRole))
	if !node.checkHealthy() {
4261
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, nil
4262
	}
4263 4264 4265 4266 4267 4268
	rootCoordReq := &milvuspb.ListCredUsersRequest{
		Base: &commonpb.MsgBase{
			MsgType: commonpb.MsgType_ListCredUsernames,
		},
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280
	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,
		},
4281
		Usernames: resp.Usernames,
4282 4283
	}, nil
}
4284

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

	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(),
4299
		}, nil
4300 4301 4302 4303 4304 4305 4306 4307
	}

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

4313 4314 4315
func (node *Proxy) DropRole(ctx context.Context, req *milvuspb.DropRoleRequest) (*commonpb.Status, error) {
	logger.Debug("DropRole", zap.Any("req", req))
	if code, ok := node.checkHealthyAndReturnCode(); !ok {
4316
		return errorutil.UnhealthyStatus(code), nil
4317 4318 4319 4320 4321
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
4322
		}, nil
4323
	}
4324 4325 4326 4327 4328
	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,
4329
		}, nil
4330
	}
4331 4332 4333 4334 4335 4336
	result, err := node.rootCoord.DropRole(ctx, req)
	if err != nil {
		logger.Error("fail to drop role", zap.String("role_name", req.RoleName), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
4337
		}, nil
4338 4339
	}
	return result, nil
4340 4341
}

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

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

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

	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(),
				},
4384
			}, nil
4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395
		}
	}

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

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

	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(),
				},
4414
			}, nil
4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425
		}
	}

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

4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460
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
4461 4462
}

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

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

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

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

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

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

	return nil
}

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

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

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

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

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

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

// SetRates limits the rates of requests.
func (node *Proxy) SetRates(ctx context.Context, request *proxypb.SetRatesRequest) (*commonpb.Status, error) {
	log.Debug("SetRates", zap.String("role", typeutil.ProxyRole), zap.Any("rates", request.GetRates()))
	resp := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
	if !node.checkHealthy() {
		resp = unhealthyStatus()
		return resp, nil
	}

	err := node.multiRateLimiter.globalRateLimiter.setRates(request.GetRates())
	// TODO: set multiple rate limiter rates
	if err != nil {
		resp.Reason = err.Error()
		return resp, nil
	}
	resp.ErrorCode = commonpb.ErrorCode_Success
	return resp, nil
}
4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650

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

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

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

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

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

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

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

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

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

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

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