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

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

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

26 27
	"github.com/milvus-io/milvus/internal/util/errorutil"

28 29
	"github.com/milvus-io/milvus/internal/util"

30
	"go.uber.org/zap"
G
groot 已提交
31
	"go.uber.org/zap/zapcore"
S
sunby 已提交
32

33
	"github.com/milvus-io/milvus/internal/common"
X
Xiangyu Wang 已提交
34
	"github.com/milvus-io/milvus/internal/log"
35
	"github.com/milvus-io/milvus/internal/metrics"
J
jaime 已提交
36
	"github.com/milvus-io/milvus/internal/mq/msgstream"
37

38
	"github.com/golang/protobuf/proto"
X
Xiangyu Wang 已提交
39 40 41 42 43 44
	"github.com/milvus-io/milvus/internal/proto/commonpb"
	"github.com/milvus-io/milvus/internal/proto/datapb"
	"github.com/milvus-io/milvus/internal/proto/internalpb"
	"github.com/milvus-io/milvus/internal/proto/milvuspb"
	"github.com/milvus-io/milvus/internal/proto/proxypb"
	"github.com/milvus-io/milvus/internal/proto/querypb"
45
	"github.com/milvus-io/milvus/internal/util/crypto"
46 47
	"github.com/milvus-io/milvus/internal/util/logutil"
	"github.com/milvus-io/milvus/internal/util/metricsinfo"
48
	"github.com/milvus-io/milvus/internal/util/timerecord"
49
	"github.com/milvus-io/milvus/internal/util/trace"
X
Xiangyu Wang 已提交
50
	"github.com/milvus-io/milvus/internal/util/typeutil"
51 52
)

53 54
const moduleName = "Proxy"

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

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

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

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

110
	collectionName := request.CollectionName
111
	collectionID := request.CollectionID
N
neza2017 已提交
112
	if globalMetaCache != nil {
113 114 115 116 117 118
		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 已提交
119
	}
120
	logutil.Logger(ctx).Info("complete to invalidate collection meta cache",
121
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
122
		zap.String("db", request.DbName),
123 124
		zap.String("collection", collectionName),
		zap.Int64("collectionID", collectionID))
D
dragondriver 已提交
125

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

132
// ReleaseDQLMessageStream release the query message stream of specific collection.
C
Cai Yudong 已提交
133
func (node *Proxy) ReleaseDQLMessageStream(ctx context.Context, request *proxypb.ReleaseDQLMessageStreamRequest) (*commonpb.Status, error) {
134 135
	ctx = logutil.WithModule(ctx, moduleName)
	logutil.Logger(ctx).Debug("received request to release DQL message strem",
136
		zap.Any("role", typeutil.ProxyRole),
137 138 139
		zap.Any("db", request.DbID),
		zap.Any("collection", request.CollectionID))

140 141 142 143
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}

144
	logutil.Logger(ctx).Debug("complete to release DQL message stream",
145
		zap.Any("role", typeutil.ProxyRole),
146 147 148 149 150 151 152 153 154
		zap.Any("db", request.DbID),
		zap.Any("collection", request.CollectionID))

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

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

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

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

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

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

180 181
	log.Debug(
		rpcReceived(method),
182
		zap.String("traceID", traceID),
183
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
184 185
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
186
		zap.Int("len(schema)", lenOfSchema),
187 188
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
189

190 191 192
	if err := node.sched.ddQueue.Enqueue(cct); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
193 194
			zap.Error(err),
			zap.String("traceID", traceID),
195
			zap.String("role", typeutil.ProxyRole),
196 197 198
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Int("len(schema)", lenOfSchema),
199 200
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
201

X
Xiaofan 已提交
202
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
203
		return &commonpb.Status{
204
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
205 206 207 208
			Reason:    err.Error(),
		}, nil
	}

209 210
	log.Debug(
		rpcEnqueued(method),
211
		zap.String("traceID", traceID),
212
		zap.String("role", typeutil.ProxyRole),
213 214 215
		zap.Int64("MsgID", cct.ID()),
		zap.Uint64("BeginTs", cct.BeginTs()),
		zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
216 217
		zap.Uint64("timestamp", request.Base.Timestamp),
		zap.String("db", request.DbName),
218 219
		zap.String("collection", request.CollectionName),
		zap.Int("len(schema)", lenOfSchema),
220 221
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
222

223 224 225
	if err := cct.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
226
			zap.Error(err),
227
			zap.String("traceID", traceID),
228
			zap.String("role", typeutil.ProxyRole),
229 230 231
			zap.Int64("MsgID", cct.ID()),
			zap.Uint64("BeginTs", cct.BeginTs()),
			zap.Uint64("EndTs", cct.EndTs()),
D
dragondriver 已提交
232 233
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
234
			zap.Int("len(schema)", lenOfSchema),
235 236
			zap.Int32("shards_num", request.ShardsNum),
			zap.String("consistency_level", request.ConsistencyLevel.String()))
D
dragondriver 已提交
237

X
Xiaofan 已提交
238
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
239
		return &commonpb.Status{
240
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
241 242 243 244
			Reason:    err.Error(),
		}, nil
	}

245 246
	log.Debug(
		rpcDone(method),
247
		zap.String("traceID", traceID),
248
		zap.String("role", typeutil.ProxyRole),
249 250 251 252 253 254
		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),
255 256
		zap.Int32("shards_num", request.ShardsNum),
		zap.String("consistency_level", request.ConsistencyLevel.String()))
257

X
Xiaofan 已提交
258 259
	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()))
260 261 262
	return cct.result, nil
}

263
// DropCollection drop a collection.
C
Cai Yudong 已提交
264
func (node *Proxy) DropCollection(ctx context.Context, request *milvuspb.DropCollectionRequest) (*commonpb.Status, error) {
265 266 267
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
268 269 270 271

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

276
	dct := &dropCollectionTask{
S
sunby 已提交
277
		ctx:                   ctx,
278 279
		Condition:             NewTaskCondition(ctx),
		DropCollectionRequest: request,
280
		rootCoord:             node.rootCoord,
281
		chMgr:                 node.chMgr,
S
sunby 已提交
282
		chTicker:              node.chTicker,
283 284
	}

285 286
	log.Debug("DropCollection received",
		zap.String("traceID", traceID),
287
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
288 289
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
290 291 292 293 294

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

X
Xiaofan 已提交
299
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
300
		return &commonpb.Status{
301
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
302 303 304 305
			Reason:    err.Error(),
		}, nil
	}

306 307
	log.Debug("DropCollection enqueued",
		zap.String("traceID", traceID),
308
		zap.String("role", typeutil.ProxyRole),
309 310 311
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTs", dct.BeginTs()),
		zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
312 313
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
314 315 316

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DropCollection failed to WaitToFinish",
D
dragondriver 已提交
317
			zap.Error(err),
318
			zap.String("traceID", traceID),
319
			zap.String("role", typeutil.ProxyRole),
320 321 322
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTs", dct.BeginTs()),
			zap.Uint64("EndTs", dct.EndTs()),
D
dragondriver 已提交
323 324 325
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
326
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
327
		return &commonpb.Status{
328
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
329 330 331 332
			Reason:    err.Error(),
		}, nil
	}

333 334
	log.Debug("DropCollection done",
		zap.String("traceID", traceID),
335
		zap.String("role", typeutil.ProxyRole),
336 337 338 339 340 341
		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 已提交
342 343
	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()))
344 345 346
	return dct.result, nil
}

347
// HasCollection check if the specific collection exists in Milvus.
C
Cai Yudong 已提交
348
func (node *Proxy) HasCollection(ctx context.Context, request *milvuspb.HasCollectionRequest) (*milvuspb.BoolResponse, error) {
349 350 351 352 353
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
354 355 356 357

	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasCollection")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
358 359
	method := "HasCollection"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
360
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
361
		metrics.TotalLabel).Inc()
362 363 364

	log.Debug("HasCollection received",
		zap.String("traceID", traceID),
365
		zap.String("role", typeutil.ProxyRole),
366 367 368
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

369
	hct := &hasCollectionTask{
S
sunby 已提交
370
		ctx:                  ctx,
371 372
		Condition:            NewTaskCondition(ctx),
		HasCollectionRequest: request,
373
		rootCoord:            node.rootCoord,
374 375
	}

376 377 378 379
	if err := node.sched.ddQueue.Enqueue(hct); err != nil {
		log.Warn("HasCollection failed to enqueue",
			zap.Error(err),
			zap.String("traceID", traceID),
380
			zap.String("role", typeutil.ProxyRole),
381 382 383
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
384
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
385
			metrics.AbandonLabel).Inc()
386 387
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
388
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
389 390 391 392 393
				Reason:    err.Error(),
			},
		}, nil
	}

394 395
	log.Debug("HasCollection enqueued",
		zap.String("traceID", traceID),
396
		zap.String("role", typeutil.ProxyRole),
397 398 399
		zap.Int64("MsgID", hct.ID()),
		zap.Uint64("BeginTS", hct.BeginTs()),
		zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
400 401
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
402 403 404

	if err := hct.WaitToFinish(); err != nil {
		log.Warn("HasCollection failed to WaitToFinish",
D
dragondriver 已提交
405
			zap.Error(err),
406
			zap.String("traceID", traceID),
407
			zap.String("role", typeutil.ProxyRole),
408 409 410
			zap.Int64("MsgID", hct.ID()),
			zap.Uint64("BeginTS", hct.BeginTs()),
			zap.Uint64("EndTS", hct.EndTs()),
D
dragondriver 已提交
411 412 413
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
414
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
415
			metrics.FailLabel).Inc()
416 417
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
418
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
419 420 421 422 423
				Reason:    err.Error(),
			},
		}, nil
	}

424 425
	log.Debug("HasCollection done",
		zap.String("traceID", traceID),
426
		zap.String("role", typeutil.ProxyRole),
427 428 429 430 431 432
		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 已提交
433
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
434
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
435
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
436 437 438
	return hct.result, nil
}

439
// LoadCollection load a collection into query nodes.
C
Cai Yudong 已提交
440
func (node *Proxy) LoadCollection(ctx context.Context, request *milvuspb.LoadCollectionRequest) (*commonpb.Status, error) {
441 442 443
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
444 445 446 447

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

451
	lct := &loadCollectionTask{
S
sunby 已提交
452
		ctx:                   ctx,
453 454
		Condition:             NewTaskCondition(ctx),
		LoadCollectionRequest: request,
455
		queryCoord:            node.queryCoord,
456 457
	}

458 459
	log.Debug("LoadCollection received",
		zap.String("traceID", traceID),
460
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
461 462
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
463 464 465 466 467

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

X
Xiaofan 已提交
472
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
473
			metrics.AbandonLabel).Inc()
474
		return &commonpb.Status{
475
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
476 477 478
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
479

480 481
	log.Debug("LoadCollection enqueued",
		zap.String("traceID", traceID),
482
		zap.String("role", typeutil.ProxyRole),
483 484 485
		zap.Int64("MsgID", lct.ID()),
		zap.Uint64("BeginTS", lct.BeginTs()),
		zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
486 487
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
488 489 490

	if err := lct.WaitToFinish(); err != nil {
		log.Warn("LoadCollection failed to WaitToFinish",
D
dragondriver 已提交
491
			zap.Error(err),
492
			zap.String("traceID", traceID),
493
			zap.String("role", typeutil.ProxyRole),
494 495 496
			zap.Int64("MsgID", lct.ID()),
			zap.Uint64("BeginTS", lct.BeginTs()),
			zap.Uint64("EndTS", lct.EndTs()),
D
dragondriver 已提交
497 498 499
			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.FailLabel).Inc()
504
		return &commonpb.Status{
505
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
506 507 508 509
			Reason:    err.Error(),
		}, nil
	}

510 511
	log.Debug("LoadCollection done",
		zap.String("traceID", traceID),
512
		zap.String("role", typeutil.ProxyRole),
513 514 515 516 517 518
		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 已提交
519
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
520
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
521
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
522
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
523
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
524
	return lct.result, nil
525 526
}

527
// ReleaseCollection remove the loaded collection from query nodes.
C
Cai Yudong 已提交
528
func (node *Proxy) ReleaseCollection(ctx context.Context, request *milvuspb.ReleaseCollectionRequest) (*commonpb.Status, error) {
529 530 531
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
532

533
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-ReleaseCollection")
534 535
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
536 537
	method := "ReleaseCollection"
	tr := timerecord.NewTimeRecorder(method)
538

539
	rct := &releaseCollectionTask{
S
sunby 已提交
540
		ctx:                      ctx,
541 542
		Condition:                NewTaskCondition(ctx),
		ReleaseCollectionRequest: request,
543
		queryCoord:               node.queryCoord,
544
		chMgr:                    node.chMgr,
545 546
	}

547 548
	log.Debug(
		rpcReceived(method),
549
		zap.String("traceID", traceID),
550
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
551 552
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
553 554

	if err := node.sched.ddQueue.Enqueue(rct); err != nil {
555 556
		log.Warn(
			rpcFailedToEnqueue(method),
557 558
			zap.Error(err),
			zap.String("traceID", traceID),
559
			zap.String("role", typeutil.ProxyRole),
560 561 562
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
563
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
564
			metrics.AbandonLabel).Inc()
565
		return &commonpb.Status{
566
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
567 568 569 570
			Reason:    err.Error(),
		}, nil
	}

571 572
	log.Debug(
		rpcEnqueued(method),
573
		zap.String("traceID", traceID),
574
		zap.String("role", typeutil.ProxyRole),
575 576 577
		zap.Int64("MsgID", rct.ID()),
		zap.Uint64("BeginTS", rct.BeginTs()),
		zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
578 579
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
580 581

	if err := rct.WaitToFinish(); err != nil {
582 583
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
584
			zap.Error(err),
585
			zap.String("traceID", traceID),
586
			zap.String("role", typeutil.ProxyRole),
587 588 589
			zap.Int64("MsgID", rct.ID()),
			zap.Uint64("BeginTS", rct.BeginTs()),
			zap.Uint64("EndTS", rct.EndTs()),
D
dragondriver 已提交
590 591 592
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
593
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
594
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
595
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
596
			metrics.FailLabel).Inc()
597
		return &commonpb.Status{
598
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
599 600 601 602
			Reason:    err.Error(),
		}, nil
	}

603 604
	log.Debug(
		rpcDone(method),
605
		zap.String("traceID", traceID),
606
		zap.String("role", typeutil.ProxyRole),
607 608 609 610 611 612
		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 已提交
613
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
614
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
615
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
616
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
617
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
618
	return rct.result, nil
619 620
}

621
// DescribeCollection get the meta information of specific collection, such as schema, created timestamp and etc.
C
Cai Yudong 已提交
622
func (node *Proxy) DescribeCollection(ctx context.Context, request *milvuspb.DescribeCollectionRequest) (*milvuspb.DescribeCollectionResponse, error) {
623 624 625 626 627
	if !node.checkHealthy() {
		return &milvuspb.DescribeCollectionResponse{
			Status: unhealthyStatus(),
		}, nil
	}
628

629
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DescribeCollection")
630 631
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
632 633
	method := "DescribeCollection"
	tr := timerecord.NewTimeRecorder(method)
634

635
	dct := &describeCollectionTask{
S
sunby 已提交
636
		ctx:                       ctx,
637 638
		Condition:                 NewTaskCondition(ctx),
		DescribeCollectionRequest: request,
639
		rootCoord:                 node.rootCoord,
640 641
	}

642 643
	log.Debug("DescribeCollection received",
		zap.String("traceID", traceID),
644
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
645 646
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
647 648 649 650 651

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

X
Xiaofan 已提交
656
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
657
			metrics.AbandonLabel).Inc()
658 659
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
660
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
661 662 663 664 665
				Reason:    err.Error(),
			},
		}, nil
	}

666 667
	log.Debug("DescribeCollection enqueued",
		zap.String("traceID", traceID),
668
		zap.String("role", typeutil.ProxyRole),
669 670 671
		zap.Int64("MsgID", dct.ID()),
		zap.Uint64("BeginTS", dct.BeginTs()),
		zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
672 673
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
674 675 676

	if err := dct.WaitToFinish(); err != nil {
		log.Warn("DescribeCollection failed to WaitToFinish",
D
dragondriver 已提交
677
			zap.Error(err),
678
			zap.String("traceID", traceID),
679
			zap.String("role", typeutil.ProxyRole),
680 681 682
			zap.Int64("MsgID", dct.ID()),
			zap.Uint64("BeginTS", dct.BeginTs()),
			zap.Uint64("EndTS", dct.EndTs()),
D
dragondriver 已提交
683 684 685
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
686
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
687
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
688
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
689
			metrics.FailLabel).Inc()
690

691 692
		return &milvuspb.DescribeCollectionResponse{
			Status: &commonpb.Status{
693
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
694 695 696 697 698
				Reason:    err.Error(),
			},
		}, nil
	}

699 700
	log.Debug("DescribeCollection done",
		zap.String("traceID", traceID),
701
		zap.String("role", typeutil.ProxyRole),
702 703 704 705 706 707
		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 已提交
708
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
709
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
710
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
711
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
712
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
713 714 715
	return dct.result, nil
}

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 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
// 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
}

825
// GetCollectionStatistics get the collection statistics, such as `num_rows`.
C
Cai Yudong 已提交
826
func (node *Proxy) GetCollectionStatistics(ctx context.Context, request *milvuspb.GetCollectionStatisticsRequest) (*milvuspb.GetCollectionStatisticsResponse, error) {
827 828 829 830 831
	if !node.checkHealthy() {
		return &milvuspb.GetCollectionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
832 833 834 835

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

839
	g := &getCollectionStatisticsTask{
G
godchen 已提交
840 841 842
		ctx:                            ctx,
		Condition:                      NewTaskCondition(ctx),
		GetCollectionStatisticsRequest: request,
843
		dataCoord:                      node.dataCoord,
844 845
	}

846 847
	log.Debug(
		rpcReceived(method),
848
		zap.String("traceID", traceID),
849
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
850 851
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
852 853

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
854 855
		log.Warn(
			rpcFailedToEnqueue(method),
856 857
			zap.Error(err),
			zap.String("traceID", traceID),
858
			zap.String("role", typeutil.ProxyRole),
859 860 861
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
862
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
863
			metrics.AbandonLabel).Inc()
864

G
godchen 已提交
865
		return &milvuspb.GetCollectionStatisticsResponse{
866
			Status: &commonpb.Status{
867
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
868 869 870 871 872
				Reason:    err.Error(),
			},
		}, nil
	}

873 874
	log.Debug(
		rpcEnqueued(method),
875
		zap.String("traceID", traceID),
876
		zap.String("role", typeutil.ProxyRole),
877
		zap.Int64("msgID", g.ID()),
878 879
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
D
dragondriver 已提交
880 881
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))
882 883

	if err := g.WaitToFinish(); err != nil {
884 885
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
886
			zap.Error(err),
887
			zap.String("traceID", traceID),
888
			zap.String("role", typeutil.ProxyRole),
889 890 891
			zap.Int64("MsgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
D
dragondriver 已提交
892 893 894
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
895
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
896
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
897
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
898
			metrics.FailLabel).Inc()
899

G
godchen 已提交
900
		return &milvuspb.GetCollectionStatisticsResponse{
901
			Status: &commonpb.Status{
902
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
903 904 905 906 907
				Reason:    err.Error(),
			},
		}, nil
	}

908 909
	log.Debug(
		rpcDone(method),
910
		zap.String("traceID", traceID),
911
		zap.String("role", typeutil.ProxyRole),
912
		zap.Int64("msgID", g.ID()),
913 914 915 916 917
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName))

X
Xiaofan 已提交
918
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
919
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
920
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
921
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
922
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
923
	return g.result, nil
924 925
}

926
// ShowCollections list all collections in Milvus.
C
Cai Yudong 已提交
927
func (node *Proxy) ShowCollections(ctx context.Context, request *milvuspb.ShowCollectionsRequest) (*milvuspb.ShowCollectionsResponse, error) {
928 929 930 931 932
	if !node.checkHealthy() {
		return &milvuspb.ShowCollectionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
933 934
	method := "ShowCollections"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
935
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
936

937
	sct := &showCollectionsTask{
G
godchen 已提交
938 939 940
		ctx:                    ctx,
		Condition:              NewTaskCondition(ctx),
		ShowCollectionsRequest: request,
941
		queryCoord:             node.queryCoord,
942
		rootCoord:              node.rootCoord,
943 944
	}

945
	log.Debug("ShowCollections received",
946
		zap.String("role", typeutil.ProxyRole),
947 948 949 950 951 952
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
		zap.Any("CollectionNames", request.CollectionNames),
	)

953
	err := node.sched.ddQueue.Enqueue(sct)
954
	if err != nil {
955 956
		log.Warn("ShowCollections failed to enqueue",
			zap.Error(err),
957
			zap.String("role", typeutil.ProxyRole),
958 959 960 961 962 963
			zap.String("DbName", request.DbName),
			zap.Uint64("TimeStamp", request.TimeStamp),
			zap.String("ShowType", request.Type.String()),
			zap.Any("CollectionNames", request.CollectionNames),
		)

X
Xiaofan 已提交
964
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
G
godchen 已提交
965
		return &milvuspb.ShowCollectionsResponse{
966
			Status: &commonpb.Status{
967
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
968 969 970 971 972
				Reason:    err.Error(),
			},
		}, nil
	}

973
	log.Debug("ShowCollections enqueued",
974
		zap.String("role", typeutil.ProxyRole),
975
		zap.Int64("MsgID", sct.ID()),
976
		zap.String("DbName", sct.ShowCollectionsRequest.DbName),
977
		zap.Uint64("TimeStamp", request.TimeStamp),
978 979 980
		zap.String("ShowType", sct.ShowCollectionsRequest.Type.String()),
		zap.Any("CollectionNames", sct.ShowCollectionsRequest.CollectionNames),
	)
D
dragondriver 已提交
981

982 983
	err = sct.WaitToFinish()
	if err != nil {
984 985
		log.Warn("ShowCollections failed to WaitToFinish",
			zap.Error(err),
986
			zap.String("role", typeutil.ProxyRole),
987 988 989 990 991 992 993
			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 已提交
994
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
995

G
godchen 已提交
996
		return &milvuspb.ShowCollectionsResponse{
997
			Status: &commonpb.Status{
998
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
999 1000 1001 1002 1003
				Reason:    err.Error(),
			},
		}, nil
	}

1004
	log.Debug("ShowCollections Done",
1005
		zap.String("role", typeutil.ProxyRole),
1006 1007 1008 1009
		zap.Int64("MsgID", sct.ID()),
		zap.String("DbName", request.DbName),
		zap.Uint64("TimeStamp", request.TimeStamp),
		zap.String("ShowType", request.Type.String()),
1010 1011
		zap.Int("len(CollectionNames)", len(request.CollectionNames)),
		zap.Int("num_collections", len(sct.result.CollectionNames)))
1012

X
Xiaofan 已提交
1013 1014
	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()))
1015 1016 1017
	return sct.result, nil
}

1018
// CreatePartition create a partition in specific collection.
C
Cai Yudong 已提交
1019
func (node *Proxy) CreatePartition(ctx context.Context, request *milvuspb.CreatePartitionRequest) (*commonpb.Status, error) {
1020 1021 1022
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1023

1024
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CreatePartition")
1025 1026
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1027 1028
	method := "CreatePartition"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
1029
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1030

1031
	cpt := &createPartitionTask{
S
sunby 已提交
1032
		ctx:                    ctx,
1033 1034
		Condition:              NewTaskCondition(ctx),
		CreatePartitionRequest: request,
1035
		rootCoord:              node.rootCoord,
1036 1037 1038
		result:                 nil,
	}

1039 1040 1041
	log.Debug(
		rpcReceived("CreatePartition"),
		zap.String("traceID", traceID),
1042
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1043 1044 1045
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1046 1047 1048 1049 1050 1051

	if err := node.sched.ddQueue.Enqueue(cpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue("CreatePartition"),
			zap.Error(err),
			zap.String("traceID", traceID),
1052
			zap.String("role", typeutil.ProxyRole),
1053 1054 1055 1056
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

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

1059
		return &commonpb.Status{
1060
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1061 1062 1063
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1064

1065 1066 1067
	log.Debug(
		rpcEnqueued("CreatePartition"),
		zap.String("traceID", traceID),
1068
		zap.String("role", typeutil.ProxyRole),
1069 1070 1071
		zap.Int64("MsgID", cpt.ID()),
		zap.Uint64("BeginTS", cpt.BeginTs()),
		zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1072 1073 1074
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1075 1076 1077 1078

	if err := cpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish("CreatePartition"),
D
dragondriver 已提交
1079
			zap.Error(err),
1080
			zap.String("traceID", traceID),
1081
			zap.String("role", typeutil.ProxyRole),
1082 1083 1084
			zap.Int64("MsgID", cpt.ID()),
			zap.Uint64("BeginTS", cpt.BeginTs()),
			zap.Uint64("EndTS", cpt.EndTs()),
D
dragondriver 已提交
1085 1086 1087 1088
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

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

1091
		return &commonpb.Status{
1092
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1093 1094 1095
			Reason:    err.Error(),
		}, nil
	}
1096 1097 1098 1099

	log.Debug(
		rpcDone("CreatePartition"),
		zap.String("traceID", traceID),
1100
		zap.String("role", typeutil.ProxyRole),
1101 1102 1103 1104 1105 1106 1107
		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 已提交
1108 1109
	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()))
1110 1111 1112
	return cpt.result, nil
}

1113
// DropPartition drop a partition in specific collection.
C
Cai Yudong 已提交
1114
func (node *Proxy) DropPartition(ctx context.Context, request *milvuspb.DropPartitionRequest) (*commonpb.Status, error) {
1115 1116 1117
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1118

1119
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-DropPartition")
1120 1121
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1122 1123
	method := "DropPartition"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
1124
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
1125

1126
	dpt := &dropPartitionTask{
S
sunby 已提交
1127
		ctx:                  ctx,
1128 1129
		Condition:            NewTaskCondition(ctx),
		DropPartitionRequest: request,
1130
		rootCoord:            node.rootCoord,
1131 1132 1133
		result:               nil,
	}

1134 1135 1136
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1137
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1138 1139 1140
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1141 1142 1143 1144 1145 1146

	if err := node.sched.ddQueue.Enqueue(dpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1147
			zap.String("role", typeutil.ProxyRole),
1148 1149 1150 1151
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

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

1154
		return &commonpb.Status{
1155
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1156 1157 1158
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1159

1160 1161 1162
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1163
		zap.String("role", typeutil.ProxyRole),
1164 1165 1166
		zap.Int64("MsgID", dpt.ID()),
		zap.Uint64("BeginTS", dpt.BeginTs()),
		zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1167 1168 1169
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1170 1171 1172 1173

	if err := dpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1174
			zap.Error(err),
1175
			zap.String("traceID", traceID),
1176
			zap.String("role", typeutil.ProxyRole),
1177 1178 1179
			zap.Int64("MsgID", dpt.ID()),
			zap.Uint64("BeginTS", dpt.BeginTs()),
			zap.Uint64("EndTS", dpt.EndTs()),
D
dragondriver 已提交
1180 1181 1182 1183
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

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

1186
		return &commonpb.Status{
1187
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1188 1189 1190
			Reason:    err.Error(),
		}, nil
	}
1191 1192 1193 1194

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1195
		zap.String("role", typeutil.ProxyRole),
1196 1197 1198 1199 1200 1201 1202
		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 已提交
1203 1204
	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()))
1205 1206 1207
	return dpt.result, nil
}

1208
// HasPartition check if partition exist.
C
Cai Yudong 已提交
1209
func (node *Proxy) HasPartition(ctx context.Context, request *milvuspb.HasPartitionRequest) (*milvuspb.BoolResponse, error) {
1210 1211 1212 1213 1214
	if !node.checkHealthy() {
		return &milvuspb.BoolResponse{
			Status: unhealthyStatus(),
		}, nil
	}
D
dragondriver 已提交
1215

D
dragondriver 已提交
1216
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-HasPartition")
D
dragondriver 已提交
1217 1218
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1219 1220 1221
	method := "HasPartition"
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1222
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1223
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
1224

1225
	hpt := &hasPartitionTask{
S
sunby 已提交
1226
		ctx:                 ctx,
1227 1228
		Condition:           NewTaskCondition(ctx),
		HasPartitionRequest: request,
1229
		rootCoord:           node.rootCoord,
1230 1231 1232
		result:              nil,
	}

D
dragondriver 已提交
1233 1234 1235
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1236
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1237 1238 1239
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1240 1241 1242 1243 1244 1245

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

X
Xiaofan 已提交
1251
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1252
			metrics.AbandonLabel).Inc()
1253

1254 1255
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1256
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1257 1258 1259 1260 1261
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1262

D
dragondriver 已提交
1263 1264 1265
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1266
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1267 1268 1269
		zap.Int64("MsgID", hpt.ID()),
		zap.Uint64("BeginTS", hpt.BeginTs()),
		zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1270 1271 1272
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
D
dragondriver 已提交
1273 1274 1275 1276

	if err := hpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1277
			zap.Error(err),
D
dragondriver 已提交
1278
			zap.String("traceID", traceID),
1279
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1280 1281 1282
			zap.Int64("MsgID", hpt.ID()),
			zap.Uint64("BeginTS", hpt.BeginTs()),
			zap.Uint64("EndTS", hpt.EndTs()),
D
dragondriver 已提交
1283 1284 1285 1286
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1287
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1288
			metrics.FailLabel).Inc()
1289

1290 1291
		return &milvuspb.BoolResponse{
			Status: &commonpb.Status{
1292
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1293 1294 1295 1296 1297
				Reason:    err.Error(),
			},
			Value: false,
		}, nil
	}
D
dragondriver 已提交
1298 1299 1300 1301

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1302
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1303 1304 1305 1306 1307 1308 1309
		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 已提交
1310
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1311
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1312
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1313 1314 1315
	return hpt.result, nil
}

1316
// LoadPartitions load specific partitions into query nodes.
C
Cai Yudong 已提交
1317
func (node *Proxy) LoadPartitions(ctx context.Context, request *milvuspb.LoadPartitionsRequest) (*commonpb.Status, error) {
1318 1319 1320
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1321

D
dragondriver 已提交
1322
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-LoadPartitions")
1323 1324
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
1325 1326
	method := "LoadPartitions"
	tr := timerecord.NewTimeRecorder(method)
1327

1328
	lpt := &loadPartitionsTask{
G
godchen 已提交
1329 1330 1331
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		LoadPartitionsRequest: request,
1332
		queryCoord:            node.queryCoord,
1333 1334
	}

1335 1336 1337
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1338
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1339 1340 1341
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1342 1343 1344 1345 1346 1347

	if err := node.sched.ddQueue.Enqueue(lpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1348
			zap.String("role", typeutil.ProxyRole),
1349 1350 1351 1352
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1353
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1354
			metrics.AbandonLabel).Inc()
1355

1356
		return &commonpb.Status{
1357
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1358 1359 1360 1361
			Reason:    err.Error(),
		}, nil
	}

1362 1363 1364
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1365
		zap.String("role", typeutil.ProxyRole),
1366 1367 1368
		zap.Int64("MsgID", lpt.ID()),
		zap.Uint64("BeginTS", lpt.BeginTs()),
		zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1369 1370 1371
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1372 1373 1374 1375

	if err := lpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1376
			zap.Error(err),
1377
			zap.String("traceID", traceID),
1378
			zap.String("role", typeutil.ProxyRole),
1379 1380 1381
			zap.Int64("MsgID", lpt.ID()),
			zap.Uint64("BeginTS", lpt.BeginTs()),
			zap.Uint64("EndTS", lpt.EndTs()),
D
dragondriver 已提交
1382 1383 1384 1385
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1386
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1387
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1388
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1389
			metrics.FailLabel).Inc()
1390

1391
		return &commonpb.Status{
1392
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1393 1394 1395 1396
			Reason:    err.Error(),
		}, nil
	}

1397 1398 1399
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1400
		zap.String("role", typeutil.ProxyRole),
1401 1402 1403 1404 1405 1406 1407
		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 已提交
1408
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1409
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1410
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1411
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1412
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1413
	return lpt.result, nil
1414 1415
}

1416
// ReleasePartitions release specific partitions from query nodes.
C
Cai Yudong 已提交
1417
func (node *Proxy) ReleasePartitions(ctx context.Context, request *milvuspb.ReleasePartitionsRequest) (*commonpb.Status, error) {
1418 1419 1420
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
1421 1422 1423 1424 1425

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

1426
	rpt := &releasePartitionsTask{
G
godchen 已提交
1427 1428 1429
		ctx:                      ctx,
		Condition:                NewTaskCondition(ctx),
		ReleasePartitionsRequest: request,
1430
		queryCoord:               node.queryCoord,
1431 1432
	}

1433
	method := "ReleasePartitions"
1434
	tr := timerecord.NewTimeRecorder(method)
1435 1436 1437 1438

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1439
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1440 1441 1442
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1443 1444 1445 1446 1447 1448

	if err := node.sched.ddQueue.Enqueue(rpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1449
			zap.String("role", typeutil.ProxyRole),
1450 1451 1452 1453
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1454
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1455
			metrics.AbandonLabel).Inc()
1456

1457
		return &commonpb.Status{
1458
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1459 1460 1461 1462
			Reason:    err.Error(),
		}, nil
	}

1463 1464 1465
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1466
		zap.String("role", typeutil.ProxyRole),
1467 1468 1469
		zap.Int64("msgID", rpt.Base.MsgID),
		zap.Uint64("BeginTS", rpt.BeginTs()),
		zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1470 1471 1472
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
1473 1474 1475 1476

	if err := rpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1477
			zap.Error(err),
1478
			zap.String("traceID", traceID),
1479
			zap.String("role", typeutil.ProxyRole),
1480 1481 1482
			zap.Int64("msgID", rpt.Base.MsgID),
			zap.Uint64("BeginTS", rpt.BeginTs()),
			zap.Uint64("EndTS", rpt.EndTs()),
D
dragondriver 已提交
1483 1484 1485 1486
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))

X
Xiaofan 已提交
1487
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1488
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1489
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1490
			metrics.FailLabel).Inc()
1491

1492
		return &commonpb.Status{
1493
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1494 1495 1496 1497
			Reason:    err.Error(),
		}, nil
	}

1498 1499 1500
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1501
		zap.String("role", typeutil.ProxyRole),
1502 1503 1504 1505 1506 1507 1508
		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 已提交
1509
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1510
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1511
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1512
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1513
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1514
	return rpt.result, nil
1515 1516
}

1517
// GetPartitionStatistics get the statistics of partition, such as num_rows.
C
Cai Yudong 已提交
1518
func (node *Proxy) GetPartitionStatistics(ctx context.Context, request *milvuspb.GetPartitionStatisticsRequest) (*milvuspb.GetPartitionStatisticsResponse, error) {
1519 1520 1521 1522 1523
	if !node.checkHealthy() {
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1524 1525 1526 1527

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

1531
	g := &getPartitionStatisticsTask{
1532 1533 1534
		ctx:                           ctx,
		Condition:                     NewTaskCondition(ctx),
		GetPartitionStatisticsRequest: request,
1535
		dataCoord:                     node.dataCoord,
1536 1537
	}

1538 1539 1540
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1541
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1542 1543 1544
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1545 1546 1547 1548 1549 1550

	if err := node.sched.ddQueue.Enqueue(g); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1551
			zap.String("role", typeutil.ProxyRole),
1552 1553 1554 1555
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1556
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1557
			metrics.AbandonLabel).Inc()
1558

1559 1560 1561 1562 1563 1564 1565 1566
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1567 1568 1569
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1570
		zap.String("role", typeutil.ProxyRole),
1571 1572 1573
		zap.Int64("msgID", g.ID()),
		zap.Uint64("BeginTS", g.BeginTs()),
		zap.Uint64("EndTS", g.EndTs()),
1574 1575 1576
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName))
1577 1578 1579 1580

	if err := g.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
1581
			zap.Error(err),
1582
			zap.String("traceID", traceID),
1583
			zap.String("role", typeutil.ProxyRole),
1584 1585 1586
			zap.Int64("msgID", g.ID()),
			zap.Uint64("BeginTS", g.BeginTs()),
			zap.Uint64("EndTS", g.EndTs()),
1587 1588 1589 1590
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("partition", request.PartitionName))

X
Xiaofan 已提交
1591
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1592
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1593
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1594
			metrics.FailLabel).Inc()
1595

1596 1597 1598 1599 1600 1601 1602 1603
		return &milvuspb.GetPartitionStatisticsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

1604 1605 1606
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1607
		zap.String("role", typeutil.ProxyRole),
1608 1609 1610 1611 1612 1613 1614
		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 已提交
1615
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1616
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1617
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1618
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1619
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1620
	return g.result, nil
1621 1622
}

1623
// ShowPartitions list all partitions in the specific collection.
C
Cai Yudong 已提交
1624
func (node *Proxy) ShowPartitions(ctx context.Context, request *milvuspb.ShowPartitionsRequest) (*milvuspb.ShowPartitionsResponse, error) {
1625 1626 1627 1628 1629
	if !node.checkHealthy() {
		return &milvuspb.ShowPartitionsResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1630 1631 1632 1633 1634

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

1635
	spt := &showPartitionsTask{
G
godchen 已提交
1636 1637 1638
		ctx:                   ctx,
		Condition:             NewTaskCondition(ctx),
		ShowPartitionsRequest: request,
1639
		rootCoord:             node.rootCoord,
1640
		queryCoord:            node.queryCoord,
G
godchen 已提交
1641
		result:                nil,
1642 1643
	}

1644
	method := "ShowPartitions"
1645 1646
	tr := timerecord.NewTimeRecorder(method)
	//TODO: use collectionID instead of collectionName
X
Xiaofan 已提交
1647
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1648
		metrics.TotalLabel).Inc()
1649 1650 1651 1652

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1653
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1654
		zap.Any("request", request))
1655 1656 1657 1658 1659 1660

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

X
Xiaofan 已提交
1664
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1665
			metrics.AbandonLabel).Inc()
1666

G
godchen 已提交
1667
		return &milvuspb.ShowPartitionsResponse{
1668
			Status: &commonpb.Status{
1669
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1670 1671 1672 1673 1674
				Reason:    err.Error(),
			},
		}, nil
	}

1675 1676 1677
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1678
		zap.String("role", typeutil.ProxyRole),
1679 1680 1681
		zap.Int64("msgID", spt.ID()),
		zap.Uint64("BeginTS", spt.BeginTs()),
		zap.Uint64("EndTS", spt.EndTs()),
1682 1683
		zap.String("db", spt.ShowPartitionsRequest.DbName),
		zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
1684 1685 1686 1687 1688
		zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))

	if err := spt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1689
			zap.Error(err),
1690
			zap.String("traceID", traceID),
1691
			zap.String("role", typeutil.ProxyRole),
1692 1693 1694 1695 1696 1697
			zap.Int64("msgID", spt.ID()),
			zap.Uint64("BeginTS", spt.BeginTs()),
			zap.Uint64("EndTS", spt.EndTs()),
			zap.String("db", spt.ShowPartitionsRequest.DbName),
			zap.String("collection", spt.ShowPartitionsRequest.CollectionName),
			zap.Any("partitions", spt.ShowPartitionsRequest.PartitionNames))
D
dragondriver 已提交
1698

X
Xiaofan 已提交
1699
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1700
			metrics.FailLabel).Inc()
1701

G
godchen 已提交
1702
		return &milvuspb.ShowPartitionsResponse{
1703
			Status: &commonpb.Status{
1704
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1705 1706 1707 1708
				Reason:    err.Error(),
			},
		}, nil
	}
1709 1710 1711 1712

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1713
		zap.String("role", typeutil.ProxyRole),
1714 1715 1716 1717 1718 1719 1720
		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 已提交
1721
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1722
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1723
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1724 1725 1726
	return spt.result, nil
}

1727
// CreateIndex create index for collection.
C
Cai Yudong 已提交
1728
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
1729 1730 1731
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1732 1733 1734 1735 1736

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

1737
	cit := &createIndexTask{
S
sunby 已提交
1738
		ctx:                ctx,
1739 1740
		Condition:          NewTaskCondition(ctx),
		CreateIndexRequest: request,
1741
		rootCoord:          node.rootCoord,
1742 1743
	}

D
dragondriver 已提交
1744
	method := "CreateIndex"
1745
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
1746 1747 1748 1749

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1750
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1751 1752 1753 1754
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1755 1756 1757 1758 1759 1760

	if err := node.sched.ddQueue.Enqueue(cit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1761
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1762 1763 1764 1765 1766
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

X
Xiaofan 已提交
1767
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1768
			metrics.AbandonLabel).Inc()
1769

1770
		return &commonpb.Status{
1771
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1772 1773 1774 1775
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1776 1777 1778
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1779
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1780 1781 1782
		zap.Int64("MsgID", cit.ID()),
		zap.Uint64("BeginTs", cit.BeginTs()),
		zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1783 1784 1785 1786
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.Any("extra_params", request.ExtraParams))
D
dragondriver 已提交
1787 1788 1789 1790

	if err := cit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1791
			zap.Error(err),
D
dragondriver 已提交
1792
			zap.String("traceID", traceID),
1793
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1794 1795 1796
			zap.Int64("MsgID", cit.ID()),
			zap.Uint64("BeginTs", cit.BeginTs()),
			zap.Uint64("EndTs", cit.EndTs()),
D
dragondriver 已提交
1797 1798 1799 1800 1801
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.Any("extra_params", request.ExtraParams))

X
Xiaofan 已提交
1802
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1803
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1804
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1805
			metrics.FailLabel).Inc()
1806

1807
		return &commonpb.Status{
1808
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
1809 1810 1811 1812
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
1813 1814 1815
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1816
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1817 1818 1819 1820 1821 1822 1823 1824
		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 已提交
1825
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1826
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1827
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1828
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1829
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1830 1831 1832
	return cit.result, nil
}

1833
// DescribeIndex get the meta information of index, such as index state, index id and etc.
C
Cai Yudong 已提交
1834
func (node *Proxy) DescribeIndex(ctx context.Context, request *milvuspb.DescribeIndexRequest) (*milvuspb.DescribeIndexResponse, error) {
1835 1836 1837 1838 1839
	if !node.checkHealthy() {
		return &milvuspb.DescribeIndexResponse{
			Status: unhealthyStatus(),
		}, nil
	}
1840 1841 1842 1843 1844

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

1845
	dit := &describeIndexTask{
S
sunby 已提交
1846
		ctx:                  ctx,
1847 1848
		Condition:            NewTaskCondition(ctx),
		DescribeIndexRequest: request,
1849
		rootCoord:            node.rootCoord,
1850 1851
	}

1852 1853 1854
	method := "DescribeIndex"
	// avoid data race
	indexName := request.IndexName
1855
	tr := timerecord.NewTimeRecorder(method)
1856 1857 1858 1859

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1860
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1861 1862 1863
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
1864 1865 1866 1867 1868 1869 1870
		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),
1871
			zap.String("role", typeutil.ProxyRole),
1872 1873 1874 1875 1876
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", indexName))

X
Xiaofan 已提交
1877
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1878
			metrics.AbandonLabel).Inc()
1879

1880 1881
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
1882
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
1883 1884 1885 1886 1887
				Reason:    err.Error(),
			},
		}, nil
	}

1888 1889 1890
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
1891
		zap.String("role", typeutil.ProxyRole),
1892 1893 1894
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
1895 1896 1897
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
1898 1899 1900 1901 1902
		zap.String("index name", indexName))

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
1903
			zap.Error(err),
1904
			zap.String("traceID", traceID),
1905
			zap.String("role", typeutil.ProxyRole),
1906 1907 1908
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
1909 1910 1911
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
1912
			zap.String("index name", indexName))
D
dragondriver 已提交
1913

Z
zhenshan.cao 已提交
1914 1915 1916 1917
		errCode := commonpb.ErrorCode_UnexpectedError
		if dit.result != nil {
			errCode = dit.result.Status.GetErrorCode()
		}
X
Xiaofan 已提交
1918
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1919
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1920
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1921
			metrics.FailLabel).Inc()
1922

1923 1924
		return &milvuspb.DescribeIndexResponse{
			Status: &commonpb.Status{
Z
zhenshan.cao 已提交
1925
				ErrorCode: errCode,
1926 1927 1928 1929 1930
				Reason:    err.Error(),
			},
		}, nil
	}

1931 1932 1933
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
1934
		zap.String("role", typeutil.ProxyRole),
1935 1936 1937 1938 1939 1940 1941 1942
		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 已提交
1943
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1944
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
1945
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1946
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
1947
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
1948 1949 1950
	return dit.result, nil
}

1951
// DropIndex drop the index of collection.
C
Cai Yudong 已提交
1952
func (node *Proxy) DropIndex(ctx context.Context, request *milvuspb.DropIndexRequest) (*commonpb.Status, error) {
1953 1954 1955
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
1956 1957 1958 1959 1960

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

1961
	dit := &dropIndexTask{
S
sunby 已提交
1962
		ctx:              ctx,
B
BossZou 已提交
1963 1964
		Condition:        NewTaskCondition(ctx),
		DropIndexRequest: request,
1965
		rootCoord:        node.rootCoord,
B
BossZou 已提交
1966
	}
G
godchen 已提交
1967

D
dragondriver 已提交
1968
	method := "DropIndex"
1969
	tr := timerecord.NewTimeRecorder(method)
D
dragondriver 已提交
1970 1971 1972 1973

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
1974
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
1975 1976 1977 1978 1979
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))

D
dragondriver 已提交
1980 1981 1982 1983 1984
	if err := node.sched.ddQueue.Enqueue(dit); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
1985
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
1986 1987 1988 1989
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
1990
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
1991
			metrics.AbandonLabel).Inc()
D
dragondriver 已提交
1992

B
BossZou 已提交
1993
		return &commonpb.Status{
1994
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
1995 1996 1997
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
1998

D
dragondriver 已提交
1999 2000 2001
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2002
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2003 2004 2005
		zap.Int64("MsgID", dit.ID()),
		zap.Uint64("BeginTs", dit.BeginTs()),
		zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2006 2007 2008 2009
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
D
dragondriver 已提交
2010 2011 2012 2013

	if err := dit.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2014
			zap.Error(err),
D
dragondriver 已提交
2015
			zap.String("traceID", traceID),
2016
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2017 2018 2019
			zap.Int64("MsgID", dit.ID()),
			zap.Uint64("BeginTs", dit.BeginTs()),
			zap.Uint64("EndTs", dit.EndTs()),
D
dragondriver 已提交
2020 2021 2022 2023 2024
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2025
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2026
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2027
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2028
			metrics.FailLabel).Inc()
2029

B
BossZou 已提交
2030
		return &commonpb.Status{
2031
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
B
BossZou 已提交
2032 2033 2034
			Reason:    err.Error(),
		}, nil
	}
D
dragondriver 已提交
2035 2036 2037 2038

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2039
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2040 2041 2042 2043 2044 2045 2046 2047
		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 已提交
2048
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2049
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2050
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2051
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2052
	metrics.ProxyDMLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
B
BossZou 已提交
2053 2054 2055
	return dit.result, nil
}

2056 2057
// 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.
C
Cai Yudong 已提交
2058
func (node *Proxy) GetIndexBuildProgress(ctx context.Context, request *milvuspb.GetIndexBuildProgressRequest) (*milvuspb.GetIndexBuildProgressResponse, error) {
2059 2060 2061 2062 2063
	if !node.checkHealthy() {
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2064 2065 2066 2067 2068

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

2069
	gibpt := &getIndexBuildProgressTask{
2070 2071 2072
		ctx:                          ctx,
		Condition:                    NewTaskCondition(ctx),
		GetIndexBuildProgressRequest: request,
2073 2074
		indexCoord:                   node.indexCoord,
		rootCoord:                    node.rootCoord,
2075
		dataCoord:                    node.dataCoord,
2076 2077
	}

2078
	method := "GetIndexBuildProgress"
2079
	tr := timerecord.NewTimeRecorder(method)
2080 2081 2082 2083

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2084
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2085 2086 2087 2088
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2089 2090 2091 2092 2093 2094

	if err := node.sched.ddQueue.Enqueue(gibpt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2095
			zap.String("role", typeutil.ProxyRole),
2096 2097 2098 2099
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2100
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2101
			metrics.AbandonLabel).Inc()
2102

2103 2104 2105 2106 2107 2108 2109 2110
		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2111 2112 2113
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2114
		zap.String("role", typeutil.ProxyRole),
2115 2116 2117
		zap.Int64("MsgID", gibpt.ID()),
		zap.Uint64("BeginTs", gibpt.BeginTs()),
		zap.Uint64("EndTs", gibpt.EndTs()),
2118 2119 2120 2121
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2122 2123 2124 2125

	if err := gibpt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
2126
			zap.Error(err),
2127
			zap.String("traceID", traceID),
2128
			zap.String("role", typeutil.ProxyRole),
2129 2130 2131
			zap.Int64("MsgID", gibpt.ID()),
			zap.Uint64("BeginTs", gibpt.BeginTs()),
			zap.Uint64("EndTs", gibpt.EndTs()),
2132 2133 2134 2135
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))
X
Xiaofan 已提交
2136
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2137
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2138
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2139
			metrics.FailLabel).Inc()
2140 2141 2142 2143 2144 2145 2146 2147

		return &milvuspb.GetIndexBuildProgressResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2148 2149 2150 2151

	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2152
		zap.String("role", typeutil.ProxyRole),
2153 2154 2155 2156 2157 2158 2159 2160
		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))
2161

X
Xiaofan 已提交
2162
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2163
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2164
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2165
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2166
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2167
	return gibpt.result, nil
2168 2169
}

2170
// GetIndexState get the build-state of index.
C
Cai Yudong 已提交
2171
func (node *Proxy) GetIndexState(ctx context.Context, request *milvuspb.GetIndexStateRequest) (*milvuspb.GetIndexStateResponse, error) {
2172 2173 2174 2175 2176
	if !node.checkHealthy() {
		return &milvuspb.GetIndexStateResponse{
			Status: unhealthyStatus(),
		}, nil
	}
2177 2178 2179 2180 2181

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

2182
	dipt := &getIndexStateTask{
G
godchen 已提交
2183 2184 2185
		ctx:                  ctx,
		Condition:            NewTaskCondition(ctx),
		GetIndexStateRequest: request,
2186 2187
		indexCoord:           node.indexCoord,
		rootCoord:            node.rootCoord,
2188 2189
	}

2190
	method := "GetIndexState"
2191
	tr := timerecord.NewTimeRecorder(method)
2192 2193 2194 2195

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2196
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2197 2198 2199 2200
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2201 2202 2203 2204 2205 2206

	if err := node.sched.ddQueue.Enqueue(dipt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2207
			zap.String("role", typeutil.ProxyRole),
2208 2209 2210 2211 2212
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2213
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2214
			metrics.AbandonLabel).Inc()
2215

G
godchen 已提交
2216
		return &milvuspb.GetIndexStateResponse{
2217
			Status: &commonpb.Status{
2218
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2219 2220 2221 2222 2223
				Reason:    err.Error(),
			},
		}, nil
	}

2224 2225 2226
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2227
		zap.String("role", typeutil.ProxyRole),
2228 2229 2230
		zap.Int64("MsgID", dipt.ID()),
		zap.Uint64("BeginTs", dipt.BeginTs()),
		zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2231 2232 2233 2234
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("field", request.FieldName),
		zap.String("index name", request.IndexName))
2235 2236 2237 2238

	if err := dipt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2239
			zap.Error(err),
2240
			zap.String("traceID", traceID),
2241
			zap.String("role", typeutil.ProxyRole),
2242 2243 2244
			zap.Int64("MsgID", dipt.ID()),
			zap.Uint64("BeginTs", dipt.BeginTs()),
			zap.Uint64("EndTs", dipt.EndTs()),
D
dragondriver 已提交
2245 2246 2247 2248 2249
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.String("field", request.FieldName),
			zap.String("index name", request.IndexName))

X
Xiaofan 已提交
2250
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2251
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2252
		metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2253
			metrics.FailLabel).Inc()
2254

G
godchen 已提交
2255
		return &milvuspb.GetIndexStateResponse{
2256
			Status: &commonpb.Status{
2257
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2258 2259 2260 2261 2262
				Reason:    err.Error(),
			},
		}, nil
	}

2263 2264 2265
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2266
		zap.String("role", typeutil.ProxyRole),
2267 2268 2269 2270 2271 2272 2273 2274
		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 已提交
2275
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2276
		metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2277
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2278
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
2279
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
2280 2281 2282
	return dipt.result, nil
}

2283
// Insert insert records into collection.
C
Cai Yudong 已提交
2284
func (node *Proxy) Insert(ctx context.Context, request *milvuspb.InsertRequest) (*milvuspb.MutationResult, error) {
X
Xiangyu Wang 已提交
2285 2286 2287 2288 2289 2290
	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))

2291 2292 2293 2294 2295
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}
2296 2297
	method := "Insert"
	tr := timerecord.NewTimeRecorder(method)
2298 2299
	receiveSize := proto.Size(request)
	metrics.ProxyMutationReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(receiveSize))
D
dragondriver 已提交
2300

2301 2302 2303 2304 2305
	defer func() {
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.TotalLabel).Inc()
	}()

2306
	it := &insertTask{
2307 2308
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
X
xige-16 已提交
2309
		// req:       request,
2310 2311 2312 2313
		BaseInsertTask: BaseInsertTask{
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2314
			InsertRequest: internalpb.InsertRequest{
2315
				Base: &commonpb.MsgBase{
X
xige-16 已提交
2316 2317
					MsgType:  commonpb.MsgType_Insert,
					MsgID:    0,
X
Xiaofan 已提交
2318
					SourceID: Params.ProxyCfg.GetNodeID(),
2319 2320 2321
				},
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
X
xige-16 已提交
2322 2323 2324
				FieldsData:     request.FieldsData,
				NumRows:        uint64(request.NumRows),
				Version:        internalpb.InsertDataVersion_ColumnBased,
2325
				// RowData: transfer column based request to this
2326 2327
			},
		},
2328 2329 2330 2331
		idAllocator:   node.idAllocator,
		segIDAssigner: node.segAssigner,
		chMgr:         node.chMgr,
		chTicker:      node.chTicker,
2332
	}
2333 2334

	if len(it.PartitionName) <= 0 {
2335
		it.PartitionName = Params.CommonCfg.DefaultPartitionName
2336 2337
	}

X
Xiangyu Wang 已提交
2338
	constructFailedResponse := func(err error) *milvuspb.MutationResult {
X
xige-16 已提交
2339
		numRows := request.NumRows
2340 2341 2342 2343
		errIndex := make([]uint32, numRows)
		for i := uint32(0); i < numRows; i++ {
			errIndex[i] = i
		}
2344

X
Xiangyu Wang 已提交
2345 2346 2347 2348 2349 2350 2351
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
			ErrIndex: errIndex,
		}
2352 2353
	}

X
Xiangyu Wang 已提交
2354
	log.Debug("Enqueue insert request in Proxy",
2355
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2356 2357 2358 2359 2360
		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)),
2361 2362
		zap.Uint32("NumRows", request.NumRows),
		zap.String("traceID", traceID))
D
dragondriver 已提交
2363

X
Xiangyu Wang 已提交
2364 2365
	if err := node.sched.dmQueue.Enqueue(it); err != nil {
		log.Debug("Failed to enqueue insert task: " + err.Error())
2366 2367
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
			metrics.AbandonLabel).Inc()
X
Xiangyu Wang 已提交
2368
		return constructFailedResponse(err), nil
2369
	}
D
dragondriver 已提交
2370

X
Xiangyu Wang 已提交
2371
	log.Debug("Detail of insert request in Proxy",
2372
		zap.String("role", typeutil.ProxyRole),
X
Xiangyu Wang 已提交
2373
		zap.Int64("msgID", it.Base.MsgID),
D
dragondriver 已提交
2374 2375 2376 2377 2378
		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 已提交
2379 2380 2381 2382 2383
		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))
2384
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2385
			metrics.FailLabel).Inc()
X
Xiangyu Wang 已提交
2386 2387 2388 2389 2390
		return constructFailedResponse(err), nil
	}

	if it.result.Status.ErrorCode != commonpb.ErrorCode_Success {
		setErrorIndex := func() {
X
xige-16 已提交
2391
			numRows := request.NumRows
X
Xiangyu Wang 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
			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 已提交
2403
	it.result.InsertCnt = int64(request.NumRows)
D
dragondriver 已提交
2404

2405
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2406
		metrics.SuccessLabel).Inc()
2407 2408
	successCnt := it.result.InsertCnt - int64(len(it.result.ErrIndex))
	metrics.ProxyInsertVectors.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(successCnt))
2409
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.InsertLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2410 2411 2412
	return it.result, nil
}

2413
// Delete delete records from collection, then these records cannot be searched.
G
groot 已提交
2414
func (node *Proxy) Delete(ctx context.Context, request *milvuspb.DeleteRequest) (*milvuspb.MutationResult, error) {
2415 2416 2417
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Delete")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2418 2419
	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))
2420

2421 2422 2423
	receiveSize := proto.Size(request)
	metrics.ProxyMutationReceiveBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(receiveSize))

G
groot 已提交
2424 2425 2426 2427 2428 2429
	if !node.checkHealthy() {
		return &milvuspb.MutationResult{
			Status: unhealthyStatus(),
		}, nil
	}

2430 2431 2432
	method := "Delete"
	tr := timerecord.NewTimeRecorder(method)

2433 2434
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
2435
	dt := &deleteTask{
X
xige-16 已提交
2436 2437 2438
		ctx:        ctx,
		Condition:  NewTaskCondition(ctx),
		deleteExpr: request.Expr,
G
godchen 已提交
2439
		BaseDeleteTask: BaseDeleteTask{
G
godchen 已提交
2440 2441 2442
			BaseMsg: msgstream.BaseMsg{
				HashValues: request.HashKeys,
			},
G
godchen 已提交
2443 2444 2445 2446 2447
			DeleteRequest: internalpb.DeleteRequest{
				Base: &commonpb.MsgBase{
					MsgType: commonpb.MsgType_Delete,
					MsgID:   0,
				},
X
xige-16 已提交
2448
				DbName:         request.DbName,
G
godchen 已提交
2449 2450 2451
				CollectionName: request.CollectionName,
				PartitionName:  request.PartitionName,
				// RowData: transfer column based request to this
C
Cai Yudong 已提交
2452 2453 2454 2455
			},
		},
		chMgr:    node.chMgr,
		chTicker: node.chTicker,
G
groot 已提交
2456 2457
	}

2458
	log.Debug("Enqueue delete request in Proxy",
2459
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2460 2461 2462 2463
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.String("partition", request.PartitionName),
		zap.String("expr", request.Expr))
2464 2465 2466 2467

	// 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 已提交
2468
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2469
			metrics.FailLabel).Inc()
2470

G
groot 已提交
2471 2472 2473 2474 2475 2476 2477 2478
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

2479
	log.Debug("Detail of delete request in Proxy",
2480
		zap.String("role", typeutil.ProxyRole),
G
groot 已提交
2481 2482 2483 2484 2485
		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),
2486 2487
		zap.String("expr", request.Expr),
		zap.String("traceID", traceID))
G
groot 已提交
2488

2489 2490
	if err := dt.WaitToFinish(); err != nil {
		log.Error("Failed to execute delete task in task scheduler: "+err.Error(), zap.String("traceID", traceID))
X
Xiaofan 已提交
2491
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2492
			metrics.TotalLabel).Inc()
X
Xiaofan 已提交
2493
		metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2494
			metrics.FailLabel).Inc()
G
groot 已提交
2495 2496 2497 2498 2499 2500 2501 2502
		return &milvuspb.MutationResult{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}

X
Xiaofan 已提交
2503
	metrics.ProxyDMLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
2504
		metrics.SuccessLabel).Inc()
2505
	metrics.ProxyMutationLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), metrics.DeleteLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
G
groot 已提交
2506 2507 2508
	return dt.result, nil
}

2509
// Search search the most similar records of requests.
C
Cai Yudong 已提交
2510
func (node *Proxy) Search(ctx context.Context, request *milvuspb.SearchRequest) (*milvuspb.SearchResults, error) {
2511 2512 2513 2514 2515
	if !node.checkHealthy() {
		return &milvuspb.SearchResults{
			Status: unhealthyStatus(),
		}, nil
	}
2516 2517
	method := "Search"
	tr := timerecord.NewTimeRecorder(method)
2518 2519
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.TotalLabel).Inc()
D
dragondriver 已提交
2520

C
cai.zhang 已提交
2521 2522
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Search")
	defer sp.Finish()
D
dragondriver 已提交
2523 2524
	traceID, _, _ := trace.InfoFromSpan(sp)

2525
	qt := &searchTask{
S
sunby 已提交
2526
		ctx:       ctx,
2527
		Condition: NewTaskCondition(ctx),
G
godchen 已提交
2528
		SearchRequest: &internalpb.SearchRequest{
2529
			Base: &commonpb.MsgBase{
2530
				MsgType:  commonpb.MsgType_Search,
X
Xiaofan 已提交
2531
				SourceID: Params.ProxyCfg.GetNodeID(),
2532
			},
2533
			ReqID: Params.ProxyCfg.GetNodeID(),
2534
		},
2535 2536 2537 2538
		request:  request,
		qc:       node.queryCoord,
		tr:       timerecord.NewTimeRecorder("search"),
		shardMgr: node.shardMgr,
2539 2540
	}

2541 2542 2543 2544 2545
	travelTs := request.TravelTimestamp
	guaranteeTs := request.GuaranteeTimestamp

	log.Debug(
		rpcReceived(method),
D
dragondriver 已提交
2546
		zap.String("traceID", traceID),
2547
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2548 2549 2550 2551 2552
		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)),
2553 2554 2555 2556
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2557

2558 2559 2560
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
D
dragondriver 已提交
2561 2562
			zap.Error(err),
			zap.String("traceID", traceID),
2563
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2564 2565 2566 2567 2568 2569
			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),
2570 2571 2572
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2573

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

2577 2578
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2579
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2580 2581 2582 2583
				Reason:    err.Error(),
			},
		}, nil
	}
2584
	tr.Record("search request enqueue")
2585

2586 2587
	log.Debug(
		rpcEnqueued(method),
D
dragondriver 已提交
2588
		zap.String("traceID", traceID),
2589
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2590
		zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2591 2592 2593 2594 2595
		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),
2596
		zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2597 2598 2599 2600
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2601

2602 2603 2604
	if err := qt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2605
			zap.Error(err),
D
dragondriver 已提交
2606
			zap.String("traceID", traceID),
2607
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2608
			zap.Int64("msgID", qt.ID()),
D
dragondriver 已提交
2609 2610 2611 2612
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames),
			zap.Any("dsl", request.Dsl),
2613
			zap.Any("len(PlaceholderGroup)", len(request.PlaceholderGroup)),
2614 2615 2616 2617
			zap.Any("OutputFields", request.OutputFields),
			zap.Any("search_params", request.SearchParams),
			zap.Uint64("travel_timestamp", travelTs),
			zap.Uint64("guarantee_timestamp", guaranteeTs))
2618

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

2622 2623
		return &milvuspb.SearchResults{
			Status: &commonpb.Status{
2624
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
2625 2626 2627 2628 2629
				Reason:    err.Error(),
			},
		}, nil
	}

2630 2631 2632
	span := tr.Record("wait search result")
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.SearchLabel).Observe(float64(span.Milliseconds()))
2633 2634
	log.Debug(
		rpcDone(method),
D
dragondriver 已提交
2635
		zap.String("traceID", traceID),
2636
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2637 2638 2639 2640 2641 2642
		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)),
2643 2644 2645 2646
		zap.Any("OutputFields", request.OutputFields),
		zap.Any("search_params", request.SearchParams),
		zap.Uint64("travel_timestamp", travelTs),
		zap.Uint64("guarantee_timestamp", guaranteeTs))
D
dragondriver 已提交
2647

2648 2649 2650
	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 已提交
2651
	searchDur := tr.ElapseSpan().Milliseconds()
X
Xiaofan 已提交
2652
	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2653
		metrics.SearchLabel).Observe(float64(searchDur))
2654 2655 2656 2657 2658

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

2662
// Flush notify data nodes to persist the data of collection.
2663 2664 2665 2666 2667 2668 2669
func (node *Proxy) Flush(ctx context.Context, request *milvuspb.FlushRequest) (*milvuspb.FlushResponse, error) {
	resp := &milvuspb.FlushResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    "",
		},
	}
2670
	if !node.checkHealthy() {
2671 2672
		resp.Status.Reason = "proxy is not healthy"
		return resp, nil
2673
	}
D
dragondriver 已提交
2674 2675 2676 2677 2678

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

2679
	ft := &flushTask{
T
ThreadDao 已提交
2680 2681 2682
		ctx:          ctx,
		Condition:    NewTaskCondition(ctx),
		FlushRequest: request,
2683
		dataCoord:    node.dataCoord,
2684 2685
	}

D
dragondriver 已提交
2686
	method := "Flush"
2687
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
2688
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2689 2690 2691 2692

	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2693
		zap.String("role", typeutil.ProxyRole),
G
godchen 已提交
2694 2695
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2696 2697 2698 2699 2700 2701

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

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

2708 2709
		resp.Status.Reason = err.Error()
		return resp, nil
2710 2711
	}

D
dragondriver 已提交
2712 2713 2714
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2715
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2716 2717 2718
		zap.Int64("MsgID", ft.ID()),
		zap.Uint64("BeginTs", ft.BeginTs()),
		zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2719 2720
		zap.String("db", request.DbName),
		zap.Any("collections", request.CollectionNames))
D
dragondriver 已提交
2721 2722 2723 2724

	if err := ft.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
D
dragondriver 已提交
2725
			zap.Error(err),
D
dragondriver 已提交
2726
			zap.String("traceID", traceID),
2727
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2728 2729 2730
			zap.Int64("MsgID", ft.ID()),
			zap.Uint64("BeginTs", ft.BeginTs()),
			zap.Uint64("EndTs", ft.EndTs()),
D
dragondriver 已提交
2731 2732 2733
			zap.String("db", request.DbName),
			zap.Any("collections", request.CollectionNames))

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

D
dragondriver 已提交
2736
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
2737 2738
		resp.Status.Reason = err.Error()
		return resp, nil
2739 2740
	}

D
dragondriver 已提交
2741 2742 2743
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
2744
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2745 2746 2747 2748 2749 2750
		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 已提交
2751 2752
	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()))
2753
	return ft.result, nil
2754 2755
}

2756
// Query get the records by primary keys.
C
Cai Yudong 已提交
2757
func (node *Proxy) Query(ctx context.Context, request *milvuspb.QueryRequest) (*milvuspb.QueryResults, error) {
2758 2759 2760 2761 2762
	if !node.checkHealthy() {
		return &milvuspb.QueryResults{
			Status: unhealthyStatus(),
		}, nil
	}
2763

D
dragondriver 已提交
2764 2765 2766
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-Query")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)
2767
	tr := timerecord.NewTimeRecorder("Query")
D
dragondriver 已提交
2768

2769
	qt := &queryTask{
2770 2771 2772 2773 2774
		ctx:       ctx,
		Condition: NewTaskCondition(ctx),
		RetrieveRequest: &internalpb.RetrieveRequest{
			Base: &commonpb.MsgBase{
				MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
2775
				SourceID: Params.ProxyCfg.GetNodeID(),
2776
			},
2777
			ReqID: Params.ProxyCfg.GetNodeID(),
2778
		},
2779 2780
		request:          request,
		qc:               node.queryCoord,
2781
		queryShardPolicy: mergeRoundRobinPolicy,
2782
		shardMgr:         node.shardMgr,
2783 2784
	}

D
dragondriver 已提交
2785 2786
	method := "Query"

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

D
dragondriver 已提交
2790 2791 2792
	log.Debug(
		rpcReceived(method),
		zap.String("traceID", traceID),
2793
		zap.String("role", typeutil.ProxyRole),
2794 2795
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2796 2797 2798 2799 2800
		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 已提交
2801

D
dragondriver 已提交
2802 2803 2804 2805 2806 2807
	if err := node.sched.dqQueue.Enqueue(qt); err != nil {
		log.Warn(
			rpcFailedToEnqueue(method),
			zap.Error(err),
			zap.String("traceID", traceID),
			zap.String("role", typeutil.ProxyRole),
2808 2809 2810
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2811

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

2815 2816 2817 2818 2819 2820
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
2821
	}
2822
	tr.Record("query request enqueue")
2823

D
dragondriver 已提交
2824 2825 2826
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2827
		zap.String("role", typeutil.ProxyRole),
2828
		zap.Int64("msgID", qt.ID()),
2829 2830
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
2831
		zap.Strings("partitions", request.PartitionNames))
D
dragondriver 已提交
2832 2833 2834 2835 2836 2837

	if err := qt.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
			zap.Error(err),
			zap.String("traceID", traceID),
2838
			zap.String("role", typeutil.ProxyRole),
2839
			zap.Int64("msgID", qt.ID()),
2840 2841 2842
			zap.String("db", request.DbName),
			zap.String("collection", request.CollectionName),
			zap.Any("partitions", request.PartitionNames))
2843

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

2847 2848 2849 2850 2851 2852 2853
		return &milvuspb.QueryResults{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
				Reason:    err.Error(),
			},
		}, nil
	}
2854 2855 2856
	span := tr.Record("wait query result")
	metrics.ProxyWaitForSearchResultLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
		metrics.QueryLabel).Observe(float64(span.Milliseconds()))
D
dragondriver 已提交
2857 2858 2859 2860
	log.Debug(
		rpcDone(method),
		zap.String("traceID", traceID),
		zap.String("role", typeutil.ProxyRole),
2861
		zap.Int64("msgID", qt.ID()),
2862 2863 2864
		zap.String("db", request.DbName),
		zap.String("collection", request.CollectionName),
		zap.Any("partitions", request.PartitionNames))
D
dragondriver 已提交
2865

2866 2867 2868 2869
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
		metrics.SuccessLabel).Inc()

	metrics.ProxySearchLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10),
2870
		metrics.QueryLabel).Observe(float64(tr.ElapseSpan().Milliseconds()))
2871 2872

	ret := &milvuspb.QueryResults{
2873 2874
		Status:     qt.result.Status,
		FieldsData: qt.result.FieldsData,
2875 2876 2877 2878
	}
	sentSize := proto.Size(qt.result)
	metrics.ProxyReadReqSendBytes.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Add(float64(sentSize))
	return ret, nil
2879
}
2880

2881
// CreateAlias create alias for collection, then you can search the collection with alias.
Y
Yusup 已提交
2882 2883 2884 2885
func (node *Proxy) CreateAlias(ctx context.Context, request *milvuspb.CreateAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2886 2887 2888 2889 2890

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

Y
Yusup 已提交
2891 2892 2893 2894 2895 2896 2897
	cat := &CreateAliasTask{
		ctx:                ctx,
		Condition:          NewTaskCondition(ctx),
		CreateAliasRequest: request,
		rootCoord:          node.rootCoord,
	}

D
dragondriver 已提交
2898
	method := "CreateAlias"
2899
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
2900
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919

	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 已提交
2920
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.AbandonLabel).Inc()
2921

Y
Yusup 已提交
2922 2923 2924 2925 2926 2927
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
2928 2929 2930
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
2931
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2932 2933 2934 2935
		zap.Int64("MsgID", cat.ID()),
		zap.Uint64("BeginTs", cat.BeginTs()),
		zap.Uint64("EndTs", cat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
2936 2937
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
2938 2939 2940 2941

	if err := cat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
2942
			zap.Error(err),
D
dragondriver 已提交
2943
			zap.String("traceID", traceID),
2944
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
2945 2946 2947 2948
			zap.Int64("MsgID", cat.ID()),
			zap.Uint64("BeginTs", cat.BeginTs()),
			zap.Uint64("EndTs", cat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
2949 2950
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))
X
Xiaofan 已提交
2951
		metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.FailLabel).Inc()
Y
Yusup 已提交
2952 2953 2954 2955 2956 2957 2958

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

D
dragondriver 已提交
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
	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 已提交
2970 2971
	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 已提交
2972 2973 2974
	return cat.result, nil
}

2975
// DropAlias alter the alias of collection.
Y
Yusup 已提交
2976 2977 2978 2979
func (node *Proxy) DropAlias(ctx context.Context, request *milvuspb.DropAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
2980 2981 2982 2983 2984

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

Y
Yusup 已提交
2985 2986 2987 2988 2989 2990 2991
	dat := &DropAliasTask{
		ctx:              ctx,
		Condition:        NewTaskCondition(ctx),
		DropAliasRequest: request,
		rootCoord:        node.rootCoord,
	}

D
dragondriver 已提交
2992
	method := "DropAlias"
2993
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
2994
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010

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

Y
Yusup 已提交
3013 3014 3015 3016 3017 3018
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3019 3020 3021
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3022
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3023 3024 3025 3026
		zap.Int64("MsgID", dat.ID()),
		zap.Uint64("BeginTs", dat.BeginTs()),
		zap.Uint64("EndTs", dat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3027
		zap.String("alias", request.Alias))
D
dragondriver 已提交
3028 3029 3030 3031

	if err := dat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3032
			zap.Error(err),
D
dragondriver 已提交
3033
			zap.String("traceID", traceID),
3034
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3035 3036 3037 3038
			zap.Int64("MsgID", dat.ID()),
			zap.Uint64("BeginTs", dat.BeginTs()),
			zap.Uint64("EndTs", dat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3039 3040
			zap.String("alias", request.Alias))

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

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

D
dragondriver 已提交
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
	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 已提交
3059 3060
	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 已提交
3061 3062 3063
	return dat.result, nil
}

3064
// AlterAlias alter alias of collection.
Y
Yusup 已提交
3065 3066 3067 3068
func (node *Proxy) AlterAlias(ctx context.Context, request *milvuspb.AlterAliasRequest) (*commonpb.Status, error) {
	if !node.checkHealthy() {
		return unhealthyStatus(), nil
	}
D
dragondriver 已提交
3069 3070 3071 3072 3073

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

Y
Yusup 已提交
3074 3075 3076 3077 3078 3079 3080
	aat := &AlterAliasTask{
		ctx:               ctx,
		Condition:         NewTaskCondition(ctx),
		AlterAliasRequest: request,
		rootCoord:         node.rootCoord,
	}

D
dragondriver 已提交
3081
	method := "AlterAlias"
3082
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3083
	metrics.ProxyDDLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method, metrics.TotalLabel).Inc()
D
dragondriver 已提交
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101

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

Y
Yusup 已提交
3104 3105 3106 3107 3108 3109
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, nil
	}

D
dragondriver 已提交
3110 3111 3112
	log.Debug(
		rpcEnqueued(method),
		zap.String("traceID", traceID),
3113
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3114 3115 3116 3117
		zap.Int64("MsgID", aat.ID()),
		zap.Uint64("BeginTs", aat.BeginTs()),
		zap.Uint64("EndTs", aat.EndTs()),
		zap.String("db", request.DbName),
Y
Yusup 已提交
3118 3119
		zap.String("alias", request.Alias),
		zap.String("collection", request.CollectionName))
D
dragondriver 已提交
3120 3121 3122 3123

	if err := aat.WaitToFinish(); err != nil {
		log.Warn(
			rpcFailedToWaitToFinish(method),
Y
Yusup 已提交
3124
			zap.Error(err),
D
dragondriver 已提交
3125
			zap.String("traceID", traceID),
3126
			zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3127 3128 3129 3130
			zap.Int64("MsgID", aat.ID()),
			zap.Uint64("BeginTs", aat.BeginTs()),
			zap.Uint64("EndTs", aat.EndTs()),
			zap.String("db", request.DbName),
Y
Yusup 已提交
3131 3132 3133
			zap.String("alias", request.Alias),
			zap.String("collection", request.CollectionName))

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

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

D
dragondriver 已提交
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152
	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 已提交
3153 3154
	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 已提交
3155 3156 3157
	return aat.result, nil
}

3158
// CalcDistance calculates the distances between vectors.
3159
func (node *Proxy) CalcDistance(ctx context.Context, request *milvuspb.CalcDistanceRequest) (*milvuspb.CalcDistanceResults, error) {
3160 3161 3162 3163 3164
	if !node.checkHealthy() {
		return &milvuspb.CalcDistanceResults{
			Status: unhealthyStatus(),
		}, nil
	}
3165

3166 3167 3168 3169
	sp, ctx := trace.StartSpanFromContextWithOperationName(ctx, "Proxy-CalcDistance")
	defer sp.Finish()
	traceID, _, _ := trace.InfoFromSpan(sp)

3170 3171
	query := func(ids *milvuspb.VectorIDs) (*milvuspb.QueryResults, error) {
		outputFields := []string{ids.FieldName}
3172

3173 3174 3175 3176 3177
		queryRequest := &milvuspb.QueryRequest{
			DbName:         "",
			CollectionName: ids.CollectionName,
			PartitionNames: ids.PartitionNames,
			OutputFields:   outputFields,
3178 3179
		}

3180
		qt := &queryTask{
3181 3182 3183 3184 3185
			ctx:       ctx,
			Condition: NewTaskCondition(ctx),
			RetrieveRequest: &internalpb.RetrieveRequest{
				Base: &commonpb.MsgBase{
					MsgType:  commonpb.MsgType_Retrieve,
X
Xiaofan 已提交
3186
					SourceID: Params.ProxyCfg.GetNodeID(),
3187
				},
3188
				ReqID: Params.ProxyCfg.GetNodeID(),
3189
			},
3190 3191 3192 3193
			request: queryRequest,
			qc:      node.queryCoord,
			ids:     ids.IdArray,

3194
			queryShardPolicy: mergeRoundRobinPolicy,
3195
			shardMgr:         node.shardMgr,
3196 3197
		}

G
groot 已提交
3198 3199 3200 3201 3202 3203
		items := []zapcore.Field{
			zap.String("collection", queryRequest.CollectionName),
			zap.Any("partitions", queryRequest.PartitionNames),
			zap.Any("OutputFields", queryRequest.OutputFields),
		}

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

3208 3209 3210 3211 3212
			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3213
			}, err
3214
		}
3215

G
groot 已提交
3216
		log.Debug("CalcDistance queryTask enqueued", items...)
3217 3218 3219

		err = qt.WaitToFinish()
		if err != nil {
G
groot 已提交
3220
			log.Error("CalcDistance queryTask failed to WaitToFinish", append(items, zap.Error(err))...)
3221 3222 3223 3224 3225 3226

			return &milvuspb.QueryResults{
				Status: &commonpb.Status{
					ErrorCode: commonpb.ErrorCode_UnexpectedError,
					Reason:    err.Error(),
				},
3227
			}, err
3228
		}
3229

G
groot 已提交
3230
		log.Debug("CalcDistance queryTask Done", items...)
3231 3232

		return &milvuspb.QueryResults{
3233 3234
			Status:     qt.result.Status,
			FieldsData: qt.result.FieldsData,
3235 3236 3237
		}, nil
	}

G
groot 已提交
3238 3239 3240 3241
	// calcDistanceTask is not a standard task, no need to enqueue
	task := &calcDistanceTask{
		traceID:   traceID,
		queryFunc: query,
3242 3243
	}

G
groot 已提交
3244
	return task.Execute(ctx, request)
3245 3246
}

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

3252
// GetPersistentSegmentInfo get the information of sealed segment.
C
Cai Yudong 已提交
3253
func (node *Proxy) GetPersistentSegmentInfo(ctx context.Context, req *milvuspb.GetPersistentSegmentInfoRequest) (*milvuspb.GetPersistentSegmentInfoResponse, error) {
D
dragondriver 已提交
3254
	log.Debug("GetPersistentSegmentInfo",
3255
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3256 3257 3258
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3259
	resp := &milvuspb.GetPersistentSegmentInfoResponse{
X
XuanYang-cn 已提交
3260
		Status: &commonpb.Status{
3261
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
XuanYang-cn 已提交
3262 3263
		},
	}
3264 3265 3266 3267
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3268 3269
	method := "GetPersistentSegmentInfo"
	tr := timerecord.NewTimeRecorder(method)
X
Xiaofan 已提交
3270
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3271
		metrics.TotalLabel).Inc()
G
godchen 已提交
3272
	segments, err := node.getSegmentsOfCollection(ctx, req.DbName, req.CollectionName)
X
XuanYang-cn 已提交
3273
	if err != nil {
3274
		resp.Status.Reason = fmt.Errorf("getSegmentsOfCollection, err:%w", err).Error()
X
XuanYang-cn 已提交
3275 3276
		return resp, nil
	}
3277
	infoResp, err := node.dataCoord.GetSegmentInfo(ctx, &datapb.GetSegmentInfoRequest{
X
XuanYang-cn 已提交
3278
		Base: &commonpb.MsgBase{
3279
			MsgType:   commonpb.MsgType_SegmentInfo,
X
XuanYang-cn 已提交
3280 3281
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3282
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3283 3284 3285 3286
		},
		SegmentIDs: segments,
	})
	if err != nil {
3287
		log.Debug("GetPersistentSegmentInfo fail", zap.Error(err))
3288
		resp.Status.Reason = fmt.Errorf("dataCoord:GetSegmentInfo, err:%w", err).Error()
X
XuanYang-cn 已提交
3289 3290
		return resp, nil
	}
3291
	log.Debug("GetPersistentSegmentInfo ", zap.Int("len(infos)", len(infoResp.Infos)), zap.Any("status", infoResp.Status))
3292
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3293 3294 3295 3296 3297 3298
		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 已提交
3299
			SegmentID:    info.ID,
X
XuanYang-cn 已提交
3300 3301
			CollectionID: info.CollectionID,
			PartitionID:  info.PartitionID,
S
sunby 已提交
3302
			NumRows:      info.NumOfRows,
X
XuanYang-cn 已提交
3303 3304 3305
			State:        info.State,
		}
	}
X
Xiaofan 已提交
3306
	metrics.ProxyDQLFunctionCall.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method,
3307
		metrics.SuccessLabel).Inc()
X
Xiaofan 已提交
3308
	metrics.ProxyDQLReqLatency.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10), method).Observe(float64(tr.ElapseSpan().Milliseconds()))
3309
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
X
XuanYang-cn 已提交
3310 3311 3312 3313
	resp.Infos = persistentInfos
	return resp, nil
}

J
jingkl 已提交
3314
// GetQuerySegmentInfo gets segment information from QueryCoord.
C
Cai Yudong 已提交
3315
func (node *Proxy) GetQuerySegmentInfo(ctx context.Context, req *milvuspb.GetQuerySegmentInfoRequest) (*milvuspb.GetQuerySegmentInfoResponse, error) {
D
dragondriver 已提交
3316
	log.Debug("GetQuerySegmentInfo",
3317
		zap.String("role", typeutil.ProxyRole),
D
dragondriver 已提交
3318 3319 3320
		zap.String("db", req.DbName),
		zap.Any("collection", req.CollectionName))

G
godchen 已提交
3321
	resp := &milvuspb.GetQuerySegmentInfoResponse{
Z
zhenshan.cao 已提交
3322
		Status: &commonpb.Status{
3323
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
Z
zhenshan.cao 已提交
3324 3325
		},
	}
3326 3327 3328 3329
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3330

3331 3332 3333 3334 3335
	collID, err := globalMetaCache.GetCollectionID(ctx, req.CollectionName)
	if err != nil {
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3336
	infoResp, err := node.queryCoord.GetSegmentInfo(ctx, &querypb.GetSegmentInfoRequest{
Z
zhenshan.cao 已提交
3337
		Base: &commonpb.MsgBase{
3338
			MsgType:   commonpb.MsgType_SegmentInfo,
Z
zhenshan.cao 已提交
3339 3340
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3341
			SourceID:  Params.ProxyCfg.GetNodeID(),
Z
zhenshan.cao 已提交
3342
		},
3343
		CollectionID: collID,
Z
zhenshan.cao 已提交
3344 3345
	})
	if err != nil {
3346
		log.Error("Failed to get segment info from QueryCoord",
3347
			zap.Error(err))
Z
zhenshan.cao 已提交
3348 3349 3350
		resp.Status.Reason = err.Error()
		return resp, nil
	}
3351
	log.Debug("GetQuerySegmentInfo ", zap.Any("infos", infoResp.Infos), zap.Any("status", infoResp.Status))
3352
	if infoResp.Status.ErrorCode != commonpb.ErrorCode_Success {
3353
		log.Error("Failed to get segment info from QueryCoord", zap.String("errMsg", infoResp.Status.Reason))
Z
zhenshan.cao 已提交
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
		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 已提交
3367
			State:        info.SegmentState,
3368
			NodeIds:      info.NodeIds,
Z
zhenshan.cao 已提交
3369 3370
		}
	}
3371
	resp.Status.ErrorCode = commonpb.ErrorCode_Success
Z
zhenshan.cao 已提交
3372 3373 3374 3375
	resp.Infos = queryInfos
	return resp, nil
}

C
Cai Yudong 已提交
3376
func (node *Proxy) getSegmentsOfCollection(ctx context.Context, dbName string, collectionName string) ([]UniqueID, error) {
3377
	describeCollectionResponse, err := node.rootCoord.DescribeCollection(ctx, &milvuspb.DescribeCollectionRequest{
X
XuanYang-cn 已提交
3378
		Base: &commonpb.MsgBase{
3379
			MsgType:   commonpb.MsgType_DescribeCollection,
X
XuanYang-cn 已提交
3380 3381
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3382
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3383 3384 3385 3386 3387 3388 3389
		},
		DbName:         dbName,
		CollectionName: collectionName,
	})
	if err != nil {
		return nil, err
	}
3390
	if describeCollectionResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3391 3392 3393
		return nil, errors.New(describeCollectionResponse.Status.Reason)
	}
	collectionID := describeCollectionResponse.CollectionID
3394
	showPartitionsResp, err := node.rootCoord.ShowPartitions(ctx, &milvuspb.ShowPartitionsRequest{
X
XuanYang-cn 已提交
3395
		Base: &commonpb.MsgBase{
3396
			MsgType:   commonpb.MsgType_ShowPartitions,
X
XuanYang-cn 已提交
3397 3398
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3399
			SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3400 3401 3402 3403 3404 3405 3406 3407
		},
		DbName:         dbName,
		CollectionName: collectionName,
		CollectionID:   collectionID,
	})
	if err != nil {
		return nil, err
	}
3408
	if showPartitionsResp.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3409 3410 3411 3412 3413
		return nil, errors.New(showPartitionsResp.Status.Reason)
	}

	ret := make([]UniqueID, 0)
	for _, partitionID := range showPartitionsResp.PartitionIDs {
3414
		showSegmentResponse, err := node.rootCoord.ShowSegments(ctx, &milvuspb.ShowSegmentsRequest{
X
XuanYang-cn 已提交
3415
			Base: &commonpb.MsgBase{
3416
				MsgType:   commonpb.MsgType_ShowSegments,
X
XuanYang-cn 已提交
3417 3418
				MsgID:     0,
				Timestamp: 0,
X
Xiaofan 已提交
3419
				SourceID:  Params.ProxyCfg.GetNodeID(),
X
XuanYang-cn 已提交
3420 3421 3422 3423 3424 3425 3426
			},
			CollectionID: collectionID,
			PartitionID:  partitionID,
		})
		if err != nil {
			return nil, err
		}
3427
		if showSegmentResponse.Status.ErrorCode != commonpb.ErrorCode_Success {
X
XuanYang-cn 已提交
3428 3429 3430 3431 3432 3433
			return nil, errors.New(showSegmentResponse.Status.Reason)
		}
		ret = append(ret, showSegmentResponse.SegmentIDs...)
	}
	return ret, nil
}
3434

J
jingkl 已提交
3435
// Dummy handles dummy request
C
Cai Yudong 已提交
3436
func (node *Proxy) Dummy(ctx context.Context, req *milvuspb.DummyRequest) (*milvuspb.DummyResponse, error) {
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447
	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
	}

3448 3449
	if drt.RequestType == "query" {
		drr, err := parseDummyQueryRequest(req.RequestType)
3450
		if err != nil {
3451
			log.Debug("Failed to parse dummy query request")
3452 3453 3454
			return failedResponse, nil
		}

3455
		request := &milvuspb.QueryRequest{
3456 3457 3458
			DbName:         drr.DbName,
			CollectionName: drr.CollectionName,
			PartitionNames: drr.PartitionNames,
3459
			OutputFields:   drr.OutputFields,
X
Xiangyu Wang 已提交
3460 3461
		}

3462
		_, err = node.Query(ctx, request)
3463
		if err != nil {
3464
			log.Debug("Failed to execute dummy query")
3465 3466
			return failedResponse, err
		}
X
Xiangyu Wang 已提交
3467 3468 3469 3470 3471 3472

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

3473 3474
	log.Debug("cannot find specify dummy request type")
	return failedResponse, nil
X
Xiangyu Wang 已提交
3475 3476
}

J
jingkl 已提交
3477
// RegisterLink registers a link
C
Cai Yudong 已提交
3478
func (node *Proxy) RegisterLink(ctx context.Context, req *milvuspb.RegisterLinkRequest) (*milvuspb.RegisterLinkResponse, error) {
G
godchen 已提交
3479
	code := node.stateCode.Load().(internalpb.StateCode)
D
dragondriver 已提交
3480
	log.Debug("RegisterLink",
3481
		zap.String("role", typeutil.ProxyRole),
C
Cai Yudong 已提交
3482
		zap.Any("state code of proxy", code))
D
dragondriver 已提交
3483

G
godchen 已提交
3484
	if code != internalpb.StateCode_Healthy {
3485 3486 3487
		return &milvuspb.RegisterLinkResponse{
			Address: nil,
			Status: &commonpb.Status{
3488
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3489
				Reason:    "proxy not healthy",
3490 3491 3492
			},
		}, nil
	}
X
Xiaofan 已提交
3493
	//metrics.ProxyLinkedSDKs.WithLabelValues(strconv.FormatInt(Params.ProxyCfg.GetNodeID(), 10)).Inc()
3494 3495 3496
	return &milvuspb.RegisterLinkResponse{
		Address: nil,
		Status: &commonpb.Status{
3497
			ErrorCode: commonpb.ErrorCode_Success,
3498
			Reason:    os.Getenv(metricsinfo.DeployModeEnvKey),
3499 3500 3501
		},
	}, nil
}
3502

3503
// GetMetrics gets the metrics of proxy
3504 3505 3506
// 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 已提交
3507
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3508 3509 3510 3511
		zap.String("req", req.Request))

	if !node.checkHealthy() {
		log.Warn("Proxy.GetMetrics failed",
X
Xiaofan 已提交
3512
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3513
			zap.String("req", req.Request),
X
Xiaofan 已提交
3514
			zap.Error(errProxyIsUnhealthy(Params.ProxyCfg.GetNodeID())))
3515 3516 3517 3518

		return &milvuspb.GetMetricsResponse{
			Status: &commonpb.Status{
				ErrorCode: commonpb.ErrorCode_UnexpectedError,
X
Xiaofan 已提交
3519
				Reason:    msgProxyIsUnhealthy(Params.ProxyCfg.GetNodeID()),
3520 3521 3522 3523 3524 3525 3526 3527
			},
			Response: "",
		}, nil
	}

	metricType, err := metricsinfo.ParseMetricType(req.Request)
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to parse metric type",
X
Xiaofan 已提交
3528
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
			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 已提交
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553
	msgID := UniqueID(0)
	msgID, err = node.idAllocator.AllocOne()
	if err != nil {
		log.Warn("Proxy.GetMetrics failed to allocate id",
			zap.Error(err))
	}
	req.Base = &commonpb.MsgBase{
		MsgType:   commonpb.MsgType_SystemInfo,
		MsgID:     msgID,
		Timestamp: 0,
X
Xiaofan 已提交
3554
		SourceID:  Params.ProxyCfg.GetNodeID(),
D
dragondriver 已提交
3555 3556
	}

3557
	if metricType == metricsinfo.SystemInfoMetrics {
3558 3559 3560 3561 3562 3563 3564
		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))

3565
		metrics, err := getSystemInfoMetrics(ctx, req, node)
3566 3567

		log.Debug("Proxy.GetMetrics",
X
Xiaofan 已提交
3568
			zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3569 3570 3571 3572 3573
			zap.String("req", req.Request),
			zap.String("metric_type", metricType),
			zap.Any("metrics", metrics), // TODO(dragondriver): necessary? may be very large
			zap.Error(err))

3574 3575
		node.metricsCacheManager.UpdateSystemInfoMetrics(metrics)

G
godchen 已提交
3576
		return metrics, nil
3577 3578 3579
	}

	log.Debug("Proxy.GetMetrics failed, request metric type is not implemented yet",
X
Xiaofan 已提交
3580
		zap.Int64("node_id", Params.ProxyCfg.GetNodeID()),
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592
		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
}

B
bigsheeper 已提交
3593 3594 3595
// 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 已提交
3596
		zap.Int64("proxy_id", Params.ProxyCfg.GetNodeID()),
B
bigsheeper 已提交
3597 3598 3599 3600 3601 3602 3603 3604 3605
		zap.Any("req", req))

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

	status := &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
	}
3606 3607 3608 3609 3610 3611 3612

	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 已提交
3613 3614 3615 3616 3617
	infoResp, err := node.queryCoord.LoadBalance(ctx, &querypb.LoadBalanceRequest{
		Base: &commonpb.MsgBase{
			MsgType:   commonpb.MsgType_LoadBalanceSegments,
			MsgID:     0,
			Timestamp: 0,
X
Xiaofan 已提交
3618
			SourceID:  Params.ProxyCfg.GetNodeID(),
B
bigsheeper 已提交
3619 3620 3621
		},
		SourceNodeIDs:    []int64{req.SrcNodeID},
		DstNodeIDs:       req.DstNodeIDs,
X
xige-16 已提交
3622
		BalanceReason:    querypb.TriggerCondition_GrpcRequest,
B
bigsheeper 已提交
3623
		SealedSegmentIDs: req.SealedSegmentIDs,
3624
		CollectionID:     collectionID,
B
bigsheeper 已提交
3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
	})
	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 已提交
3642
//GetCompactionState gets the compaction state of multiple segments
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
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
}

3656
// ManualCompaction invokes compaction on specified collection
3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
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
}

3670
// GetCompactionStateWithPlans returns the compactions states with the given plan ID
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
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 已提交
3684 3685 3686
// 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))
3687
	var err error
B
Bingyi Sun 已提交
3688 3689 3690 3691 3692 3693 3694
	resp := &milvuspb.GetFlushStateResponse{}
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		log.Info("unable to get flush state because of closed server")
		return resp, nil
	}

3695
	resp, err = node.dataCoord.GetFlushState(ctx, req)
X
Xiaofan 已提交
3696 3697 3698 3699
	if err != nil {
		log.Info("failed to get flush state response", zap.Error(err))
		return nil, err
	}
B
Bingyi Sun 已提交
3700 3701 3702 3703
	log.Info("received get flush state response", zap.Any("response", resp))
	return resp, err
}

C
Cai Yudong 已提交
3704 3705
// checkHealthy checks proxy state is Healthy
func (node *Proxy) checkHealthy() bool {
3706 3707 3708 3709
	code := node.stateCode.Load().(internalpb.StateCode)
	return code == internalpb.StateCode_Healthy
}

3710 3711 3712 3713 3714
func (node *Proxy) checkHealthyAndReturnCode() (internalpb.StateCode, bool) {
	code := node.stateCode.Load().(internalpb.StateCode)
	return code, code == internalpb.StateCode_Healthy
}

J
jingkl 已提交
3715
//unhealthyStatus returns the proxy not healthy status
3716 3717 3718
func unhealthyStatus() *commonpb.Status {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
C
Cai Yudong 已提交
3719
		Reason:    "proxy not healthy",
3720 3721
	}
}
G
groot 已提交
3722 3723 3724

// 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) {
3725 3726 3727
	log.Info("received import request",
		zap.String("collection name", req.GetCollectionName()),
		zap.Bool("row-based", req.GetRowBased()))
3728 3729 3730 3731 3732 3733
	resp := &milvuspb.ImportResponse{
		Status: &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_Success,
			Reason:    "",
		},
	}
G
groot 已提交
3734 3735 3736 3737
	if !node.checkHealthy() {
		resp.Status = unhealthyStatus()
		return resp, nil
	}
3738 3739 3740 3741 3742 3743 3744 3745
	// Get collection ID and then channel names.
	collID, err := globalMetaCache.GetCollectionID(ctx, req.GetCollectionName())
	if err != nil {
		log.Error("collection ID not found",
			zap.String("collection name", req.GetCollectionName()),
			zap.Error(err))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
3746
		return resp, nil
3747 3748 3749
	}
	chNames, err := node.chMgr.getVChannels(collID)
	if err != nil {
3750 3751 3752 3753 3754 3755 3756
		log.Error("failed to get virtual channels",
			zap.Error(err),
			zap.String("collection", req.GetCollectionName()),
			zap.Int64("collection_id", collID))
		resp.Status.ErrorCode = commonpb.ErrorCode_UnexpectedError
		resp.Status.Reason = err.Error()
		return resp, nil
3757 3758
	}
	req.ChannelNames = chNames
3759 3760 3761
	if req.GetPartitionName() == "" {
		req.PartitionName = Params.CommonCfg.DefaultPartitionName
	}
3762
	// Call rootCoord to finish import.
3763 3764 3765 3766 3767 3768 3769 3770
	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 已提交
3771 3772
}

G
groot 已提交
3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800
// GetImportState checks import task state from datanode
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 已提交
3801 3802 3803 3804 3805 3806 3807 3808 3809
// 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
	}

3810 3811
	req.Base = &commonpb.MsgBase{
		MsgType:  commonpb.MsgType_GetReplicas,
X
Xiaofan 已提交
3812
		SourceID: Params.ProxyCfg.GetNodeID(),
3813 3814
	}

X
XuanYang-cn 已提交
3815 3816 3817 3818 3819
	resp, err := node.queryCoord.GetReplicas(ctx, req)
	log.Info("received get replicas response", zap.Any("resp", resp), zap.Error(err))
	return resp, err
}

3820 3821 3822 3823 3824 3825
// 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))
3826 3827 3828
	if !node.checkHealthy() {
		return unhealthyStatus(), errorutil.UnhealthyError()
	}
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849

	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))
3850 3851 3852
	if !node.checkHealthy() {
		return unhealthyStatus(), errorutil.UnhealthyError()
	}
3853 3854

	credInfo := &internalpb.CredentialInfo{
3855 3856
		Username:       request.Username,
		Sha256Password: request.Password,
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
	}
	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) {
3872 3873 3874 3875
	log.Debug("CreateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
		return unhealthyStatus(), errorutil.UnhealthyError()
	}
3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
	// 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
	}
3907

3908 3909 3910
	credInfo := &internalpb.CredentialInfo{
		Username:          req.Username,
		EncryptedPassword: encryptedPassword,
3911
		Sha256Password:    crypto.SHA256(rawPassword, req.Username),
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
	}
	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 已提交
3924
func (node *Proxy) UpdateCredential(ctx context.Context, req *milvuspb.UpdateCredentialRequest) (*commonpb.Status, error) {
3925 3926 3927 3928
	log.Debug("UpdateCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
		return unhealthyStatus(), errorutil.UnhealthyError()
	}
C
codeman 已提交
3929 3930 3931 3932 3933 3934 3935 3936 3937
	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)
3938 3939 3940 3941 3942 3943 3944
	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 已提交
3945 3946
	// valid new password
	if err = ValidatePassword(rawNewPassword); err != nil {
3947 3948 3949 3950 3951 3952
		log.Error("illegal password", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, nil
	}
C
codeman 已提交
3953 3954 3955 3956 3957 3958 3959 3960 3961
	// check old password is correct
	oldCredInfo, err := globalMetaCache.GetCredentialInfo(ctx, req.Username)
	if err != nil {
		log.Error("found no credential", zap.String("username", req.Username), zap.Error(err))
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "found no credential:" + req.Username,
		}, nil
	}
3962
	if !crypto.PasswordVerify(rawOldPassword, oldCredInfo) {
C
codeman 已提交
3963 3964 3965 3966 3967 3968 3969
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UpdateCredentialFailure,
			Reason:    "old password is not correct:" + req.Username,
		}, nil
	}
	// update meta data
	encryptedPassword, err := crypto.PasswordEncrypt(rawNewPassword)
3970 3971 3972 3973 3974 3975 3976
	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 已提交
3977
	updateCredReq := &internalpb.CredentialInfo{
3978
		Username:          req.Username,
3979
		Sha256Password:    crypto.SHA256(rawNewPassword, req.Username),
3980 3981
		EncryptedPassword: encryptedPassword,
	}
C
codeman 已提交
3982
	result, err := node.rootCoord.UpdateCredential(ctx, updateCredReq)
3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993
	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) {
3994 3995 3996 3997 3998
	log.Debug("DeleteCredential", zap.String("role", typeutil.ProxyRole), zap.String("username", req.Username))
	if !node.checkHealthy() {
		return unhealthyStatus(), errorutil.UnhealthyError()
	}

3999 4000 4001 4002 4003 4004
	if req.Username == util.UserRoot {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_DeleteCredentialFailure,
			Reason:    "user root cannot be deleted",
		}, nil
	}
4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
	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) {
4017 4018 4019 4020
	log.Debug("ListCredUsers", zap.String("role", typeutil.ProxyRole))
	if !node.checkHealthy() {
		return &milvuspb.ListCredUsersResponse{Status: unhealthyStatus()}, errorutil.UnhealthyError()
	}
4021 4022 4023 4024 4025 4026
	rootCoordReq := &milvuspb.ListCredUsersRequest{
		Base: &commonpb.MsgBase{
			MsgType: commonpb.MsgType_ListCredUsernames,
		},
	}
	resp, err := node.rootCoord.ListCredUsers(ctx, rootCoordReq)
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038
	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,
		},
4039
		Usernames: resp.Usernames,
4040 4041
	}, nil
}
4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057

// SendSearchResult needs to be removed TODO
func (node *Proxy) SendSearchResult(ctx context.Context, req *internalpb.SearchResults) (*commonpb.Status, error) {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
		Reason:    "Not implemented",
	}, nil
}

// SendRetrieveResult needs to be removed TODO
func (node *Proxy) SendRetrieveResult(ctx context.Context, req *internalpb.RetrieveResults) (*commonpb.Status, error) {
	return &commonpb.Status{
		ErrorCode: commonpb.ErrorCode_UnexpectedError,
		Reason:    "Not implemented",
	}, nil
}
4058

4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084
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 {
		return errorutil.UnhealthyStatus(code), errorutil.UnhealthyError()
	}

	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(),
		}, err
	}

	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(),
		}, err
	}
	return result, nil
4085 4086
}

4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106
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 {
		return errorutil.UnhealthyStatus(code), errorutil.UnhealthyError()
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, err
	}
	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(),
		}, err
	}
	return result, nil
4107 4108
}

4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135
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 {
		return errorutil.UnhealthyStatus(code), errorutil.UnhealthyError()
	}
	if err := ValidateUsername(req.Username); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, err
	}
	if err := ValidateRoleName(req.RoleName); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, err
	}

	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(),
		}, err
	}
	return result, nil
4136 4137
}

4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
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 {
		return &milvuspb.SelectRoleResponse{Status: errorutil.UnhealthyStatus(code)}, errorutil.UnhealthyError()
	}

	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(),
				},
			}, err
		}
	}

	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(),
			},
		}, err
	}
	return result, nil
4166 4167
}

4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
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 {
		return &milvuspb.SelectUserResponse{Status: errorutil.UnhealthyStatus(code)}, errorutil.UnhealthyError()
	}

	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(),
				},
			}, err
		}
	}

	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(),
			},
		}, err
	}
	return result, nil
4196 4197
}

4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
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
4228 4229
}

4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
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 {
		return errorutil.UnhealthyStatus(code), errorutil.UnhealthyError()
	}
	if err := node.validPrivilegeParams(req); err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_IllegalArgument,
			Reason:    err.Error(),
		}, err
	}
	curUser, err := GetCurUserFromContext(ctx)
	if err != nil {
		return &commonpb.Status{
			ErrorCode: commonpb.ErrorCode_UnexpectedError,
			Reason:    err.Error(),
		}, err
	}
	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(),
		}, err
	}
	return result, nil
4258 4259
}

4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
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 {
		return &milvuspb.SelectGrantResponse{Status: errorutil.UnhealthyStatus(code)}, errorutil.UnhealthyError()
	}

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

	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(),
			},
		}, err
	}
	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
4338
}