GrpcRequestHandler.cpp 56.3 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
2
//
3 4
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
J
jinhai 已提交
5
//
6 7 8 9 10
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
11 12 13

#include "server/grpc_impl/GrpcRequestHandler.h"

S
shengjh 已提交
14
#include <fiu-local.h>
J
JinHai-CN 已提交
15
#include <algorithm>
Z
Zhiru Zhu 已提交
16
#include <memory>
17
#include <string>
Z
Zhiru Zhu 已提交
18
#include <unordered_map>
19
#include <utility>
Z
Zhiru Zhu 已提交
20 21
#include <vector>

22 23
#include "context/HybridSearchContext.h"
#include "query/BinaryQuery.h"
G
groot 已提交
24
#include "server/context/ConnectionContext.h"
Z
Zhiru Zhu 已提交
25 26
#include "tracing/TextMapCarrier.h"
#include "tracing/TracerUtil.h"
B
BossZou 已提交
27
#include "utils/Log.h"
28
#include "utils/LogUtil.h"
K
kun yu 已提交
29 30 31 32
#include "utils/TimeRecorder.h"

namespace milvus {
namespace server {
Y
Yu Kun 已提交
33
namespace grpc {
K
kun yu 已提交
34

35 36 37 38 39 40 41 42 43 44 45 46 47
::milvus::grpc::ErrorCode
ErrorMap(ErrorCode code) {
    static const std::map<ErrorCode, ::milvus::grpc::ErrorCode> code_map = {
        {SERVER_UNEXPECTED_ERROR, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_UNSUPPORTED_ERROR, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_NULL_POINTER, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_INVALID_ARGUMENT, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
        {SERVER_FILE_NOT_FOUND, ::milvus::grpc::ErrorCode::FILE_NOT_FOUND},
        {SERVER_NOT_IMPLEMENT, ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR},
        {SERVER_CANNOT_CREATE_FOLDER, ::milvus::grpc::ErrorCode::CANNOT_CREATE_FOLDER},
        {SERVER_CANNOT_CREATE_FILE, ::milvus::grpc::ErrorCode::CANNOT_CREATE_FILE},
        {SERVER_CANNOT_DELETE_FOLDER, ::milvus::grpc::ErrorCode::CANNOT_DELETE_FOLDER},
        {SERVER_CANNOT_DELETE_FILE, ::milvus::grpc::ErrorCode::CANNOT_DELETE_FILE},
G
groot 已提交
48 49 50
        {SERVER_COLLECTION_NOT_EXIST, ::milvus::grpc::ErrorCode::COLLECTION_NOT_EXISTS},
        {SERVER_INVALID_COLLECTION_NAME, ::milvus::grpc::ErrorCode::ILLEGAL_COLLECTION_NAME},
        {SERVER_INVALID_COLLECTION_DIMENSION, ::milvus::grpc::ErrorCode::ILLEGAL_DIMENSION},
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
        {SERVER_INVALID_VECTOR_DIMENSION, ::milvus::grpc::ErrorCode::ILLEGAL_DIMENSION},

        {SERVER_INVALID_INDEX_TYPE, ::milvus::grpc::ErrorCode::ILLEGAL_INDEX_TYPE},
        {SERVER_INVALID_ROWRECORD, ::milvus::grpc::ErrorCode::ILLEGAL_ROWRECORD},
        {SERVER_INVALID_ROWRECORD_ARRAY, ::milvus::grpc::ErrorCode::ILLEGAL_ROWRECORD},
        {SERVER_INVALID_TOPK, ::milvus::grpc::ErrorCode::ILLEGAL_TOPK},
        {SERVER_INVALID_NPROBE, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
        {SERVER_INVALID_INDEX_NLIST, ::milvus::grpc::ErrorCode::ILLEGAL_NLIST},
        {SERVER_INVALID_INDEX_METRIC_TYPE, ::milvus::grpc::ErrorCode::ILLEGAL_METRIC_TYPE},
        {SERVER_INVALID_INDEX_FILE_SIZE, ::milvus::grpc::ErrorCode::ILLEGAL_ARGUMENT},
        {SERVER_ILLEGAL_VECTOR_ID, ::milvus::grpc::ErrorCode::ILLEGAL_VECTOR_ID},
        {SERVER_ILLEGAL_SEARCH_RESULT, ::milvus::grpc::ErrorCode::ILLEGAL_SEARCH_RESULT},
        {SERVER_CACHE_FULL, ::milvus::grpc::ErrorCode::CACHE_FAILED},
        {DB_META_TRANSACTION_FAILED, ::milvus::grpc::ErrorCode::META_FAILED},
        {SERVER_BUILD_INDEX_ERROR, ::milvus::grpc::ErrorCode::BUILD_INDEX_ERROR},
        {SERVER_OUT_OF_MEMORY, ::milvus::grpc::ErrorCode::OUT_OF_MEMORY},
    };

    if (code_map.find(code) != code_map.end()) {
        return code_map.at(code);
    } else {
        return ::milvus::grpc::ErrorCode::UNEXPECTED_ERROR;
    }
}

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
std::string
RequestMap(BaseRequest::RequestType request_type) {
    static const std::unordered_map<BaseRequest::RequestType, std::string> request_map = {
        {BaseRequest::kInsert, "Insert"},
        {BaseRequest::kCreateIndex, "CreateIndex"},
        {BaseRequest::kSearch, "Search"},
        {BaseRequest::kSearchByID, "SearchByID"},
        {BaseRequest::kHybridSearch, "HybridSearch"},
        {BaseRequest::kFlush, "Flush"},
        {BaseRequest::kCompact, "Compact"},
    };

    if (request_map.find(request_type) != request_map.end()) {
        return request_map.at(request_type);
    } else {
        return "OtherRequest";
    }
}

G
groot 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
namespace {
void
CopyRowRecords(const google::protobuf::RepeatedPtrField<::milvus::grpc::RowRecord>& grpc_records,
               const google::protobuf::RepeatedField<google::protobuf::int64>& grpc_id_array,
               engine::VectorsData& vectors) {
    // step 1: copy vector data
    int64_t float_data_size = 0, binary_data_size = 0;
    for (auto& record : grpc_records) {
        float_data_size += record.float_data_size();
        binary_data_size += record.binary_data().size();
    }

    std::vector<float> float_array(float_data_size, 0.0f);
    std::vector<uint8_t> binary_array(binary_data_size, 0);
    int64_t float_offset = 0, binary_offset = 0;
    if (float_data_size > 0) {
        for (auto& record : grpc_records) {
            memcpy(&float_array[float_offset], record.float_data().data(), record.float_data_size() * sizeof(float));
            float_offset += record.float_data_size();
        }
    } else if (binary_data_size > 0) {
        for (auto& record : grpc_records) {
            memcpy(&binary_array[binary_offset], record.binary_data().data(), record.binary_data().size());
            binary_offset += record.binary_data().size();
        }
    }

    // step 2: copy id array
    std::vector<int64_t> id_array;
    if (grpc_id_array.size() > 0) {
        id_array.resize(grpc_id_array.size());
        memcpy(id_array.data(), grpc_id_array.data(), grpc_id_array.size() * sizeof(int64_t));
    }

    // step 3: contruct vectors
    vectors.vector_count_ = grpc_records.size();
    vectors.float_data_.swap(float_array);
    vectors.binary_data_.swap(binary_array);
    vectors.id_array_.swap(id_array);
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
void
ConstructResults(const TopKQueryResult& result, ::milvus::grpc::TopKQueryResult* response) {
    if (!response) {
        return;
    }

    response->set_row_num(result.row_num_);

    response->mutable_ids()->Resize(static_cast<int>(result.id_list_.size()), 0);
    memcpy(response->mutable_ids()->mutable_data(), result.id_list_.data(), result.id_list_.size() * sizeof(int64_t));

    response->mutable_distances()->Resize(static_cast<int>(result.distance_list_.size()), 0.0);
    memcpy(response->mutable_distances()->mutable_data(), result.distance_list_.data(),
           result.distance_list_.size() * sizeof(float));
}

Y
yukun 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
void
ConstructHEntityResults(const std::vector<engine::AttrsData>& attrs, const std::vector<engine::VectorsData>& vectors,
                        std::vector<std::string>& field_names, ::milvus::grpc::HEntity* response) {
    if (!response) {
        return;
    }

    response->set_row_num(attrs.size());
    if (field_names.size() > 0) {
        for (auto& name : field_names) {
            response->add_field_names(name);
        }
    } else {
        if (attrs.size() > 0) {
            auto attr_it = attrs[0].attr_type_.begin();
            for (; attr_it != attrs[0].attr_type_.end(); attr_it++) {
                field_names.emplace_back(attr_it->first);
                response->add_field_names(attr_it->first);
            }
        }
    }

    for (uint64_t i = 0; i < field_names.size() - 1; i++) {
        auto field_name = field_names[i];
        if (attrs.size() > 0) {
            if (attrs[0].attr_type_.find(field_name) != attrs[0].attr_type_.end()) {
                response->add_data_types((::milvus::grpc::DataType)attrs[0].attr_type_.at(field_name));
            }
        }
        auto grpc_attr_data = response->add_attr_data();
        std::vector<int64_t> int_data;
        std::vector<double> double_data;
        for (auto& attr : attrs) {
            auto attr_data = attr.attr_data_.at(field_name);
            int64_t grpc_int_data;
            double grpc_double_data;
            switch (attr.attr_type_.at(field_name)) {
                case engine::meta::hybrid::DataType::INT8: {
                    if (attr_data.size() == sizeof(int8_t)) {
                        grpc_int_data = attr_data[0];
                        int_data.emplace_back(grpc_int_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT16: {
                    if (attr_data.size() == sizeof(int16_t)) {
                        memcpy(&grpc_int_data, attr_data.data(), sizeof(int16_t));
                        int_data.emplace_back(grpc_int_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT32: {
                    if (attr_data.size() == sizeof(int32_t)) {
                        memcpy(&grpc_int_data, attr_data.data(), sizeof(int32_t));
                        int_data.emplace_back(grpc_int_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT64: {
                    if (attr_data.size() == sizeof(int64_t)) {
                        memcpy(&grpc_int_data, attr_data.data(), sizeof(int64_t));
                        int_data.emplace_back(grpc_int_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::FLOAT: {
                    if (attr_data.size() == sizeof(float)) {
                        float float_data;
                        memcpy(&float_data, attr_data.data(), sizeof(float));
                        grpc_double_data = float_data;
                        double_data.emplace_back(grpc_double_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::DOUBLE: {
                    if (attr_data.size() == sizeof(double)) {
                        memcpy(&grpc_double_data, attr_data.data(), sizeof(double));
                        double_data.emplace_back(grpc_double_data);
                    } else {
                        response->mutable_status()->set_error_code(::milvus::grpc::ErrorCode::UNEXPECTED_ERROR);
                        return;
                    }
                    break;
                }
                default: { break; }
            }
        }
        if (int_data.size() > 0) {
            grpc_attr_data->mutable_int_value()->Resize(static_cast<int>(int_data.size()), 0);
            memcpy(grpc_attr_data->mutable_int_value()->mutable_data(), int_data.data(),
                   int_data.size() * sizeof(int64_t));
        } else if (double_data.size() > 0) {
            grpc_attr_data->mutable_double_value()->Resize(static_cast<int>(double_data.size()), 0.0);
            memcpy(grpc_attr_data->mutable_double_value()->mutable_data(), double_data.data(),
                   double_data.size() * sizeof(double));
        }
    }

    ::milvus::grpc::VectorFieldRecord* grpc_vector_data = response->add_vector_data();
    for (auto& vector : vectors) {
        auto grpc_data = grpc_vector_data->add_value();
        if (!vector.float_data_.empty()) {
            grpc_data->mutable_float_data()->Resize(vector.float_data_.size(), 0);
            memcpy(grpc_data->mutable_float_data()->mutable_data(), vector.float_data_.data(),
                   vector.float_data_.size() * sizeof(float));
        } else if (!vector.binary_data_.empty()) {
            grpc_data->mutable_binary_data()->resize(vector.binary_data_.size());
            memcpy(grpc_data->mutable_binary_data()->data(), vector.binary_data_.data(),
                   vector.binary_data_.size() * sizeof(uint8_t));
        }
    }
}

G
groot 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
class GrpcConnectionContext : public milvus::server::ConnectionContext {
 public:
    explicit GrpcConnectionContext(::grpc::ServerContext* context) : context_(context) {
    }

    bool
    IsConnectionBroken() const override {
        if (context_ == nullptr) {
            return true;
        }

        return context_->IsCancelled();
    }

 private:
    ::grpc::ServerContext* context_ = nullptr;
};

G
groot 已提交
298 299
}  // namespace

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
namespace {

#define REQ_ID ("request_id")

std::atomic<int64_t> _sequential_id;

int64_t
get_sequential_id() {
    return _sequential_id++;
}

void
set_request_id(::grpc::ServerContext* context, const std::string& request_id) {
    if (not context) {
        // error
315
        LOG_SERVER_ERROR_ << "set_request_id: grpc::ServerContext is nullptr" << std::endl;
316 317 318 319 320 321 322 323 324 325
        return;
    }

    context->AddInitialMetadata(REQ_ID, request_id);
}

std::string
get_request_id(::grpc::ServerContext* context) {
    if (not context) {
        // error
326
        LOG_SERVER_ERROR_ << "get_request_id: grpc::ServerContext is nullptr" << std::endl;
327 328 329 330 331 332 333 334
        return "INVALID_ID";
    }

    auto server_metadata = context->server_metadata();

    auto request_id_kv = server_metadata.find(REQ_ID);
    if (request_id_kv == server_metadata.end()) {
        // error
335
        LOG_SERVER_ERROR_ << std::string(REQ_ID) << " not found in grpc.server_metadata" << std::endl;
336 337 338 339 340 341 342 343
        return "INVALID_ID";
    }

    return request_id_kv->second.data();
}

}  // namespace

Z
Zhiru Zhu 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
GrpcRequestHandler::GrpcRequestHandler(const std::shared_ptr<opentracing::Tracer>& tracer)
    : tracer_(tracer), random_num_generator_() {
    std::random_device random_device;
    random_num_generator_.seed(random_device());
}

void
GrpcRequestHandler::OnPostRecvInitialMetaData(
    ::grpc::experimental::ServerRpcInfo* server_rpc_info,
    ::grpc::experimental::InterceptorBatchMethods* interceptor_batch_methods) {
    std::unordered_map<std::string, std::string> text_map;
    auto* metadata_map = interceptor_batch_methods->GetRecvInitialMetadata();
    auto context_kv = metadata_map->find(tracing::TracerUtil::GetTraceContextHeaderName());
    if (context_kv != metadata_map->end()) {
        text_map[std::string(context_kv->first.data(), context_kv->first.length())] =
            std::string(context_kv->second.data(), context_kv->second.length());
    }
    // test debug mode
    //    if (std::string(server_rpc_info->method()).find("Search") != std::string::npos) {
    //        text_map["demo-debug-id"] = "debug-id";
    //    }

    tracing::TextMapCarrier carrier{text_map};
    auto span_context_maybe = tracer_->Extract(carrier);
    if (!span_context_maybe) {
        std::cerr << span_context_maybe.error().message() << std::endl;
        return;
    }
    auto span = tracer_->StartSpan(server_rpc_info->method(), {opentracing::ChildOf(span_context_maybe->get())});
373

Z
Zhiru Zhu 已提交
374 375
    auto server_context = server_rpc_info->server_context();
    auto client_metadata = server_context->client_metadata();
376 377 378

    // if client provide request_id in metadata, milvus just use it,
    // else milvus generate a sequential id.
Z
Zhiru Zhu 已提交
379 380 381 382
    std::string request_id;
    auto request_id_kv = client_metadata.find("request_id");
    if (request_id_kv != client_metadata.end()) {
        request_id = request_id_kv->second.data();
383
        LOG_SERVER_DEBUG_ << "client provide request_id: " << request_id;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

        // if request_id is being used by another request,
        // convert it to request_id_n.
        std::lock_guard<std::mutex> lock(context_map_mutex_);
        if (context_map_.find(request_id) == context_map_.end()) {
            // if not found exist, mark
            context_map_[request_id] = nullptr;
        } else {
            // Finding a unused suffix
            int64_t suffix = 1;
            std::string try_request_id;
            bool exist = true;
            do {
                try_request_id = request_id + "_" + std::to_string(suffix);
                exist = context_map_.find(try_request_id) != context_map_.end();
                suffix++;
            } while (exist);
            context_map_[try_request_id] = nullptr;
        }
Z
Zhiru Zhu 已提交
403
    } else {
404 405
        request_id = std::to_string(get_sequential_id());
        set_request_id(server_context, request_id);
406
        LOG_SERVER_DEBUG_ << "milvus generate request_id: " << request_id;
Z
Zhiru Zhu 已提交
407
    }
408

Z
Zhiru Zhu 已提交
409 410 411
    auto trace_context = std::make_shared<tracing::TraceContext>(span);
    auto context = std::make_shared<Context>(request_id);
    context->SetTraceContext(trace_context);
412
    SetContext(server_rpc_info->server_context(), context);
Z
Zhiru Zhu 已提交
413 414 415 416 417
}

void
GrpcRequestHandler::OnPreSendMessage(::grpc::experimental::ServerRpcInfo* server_rpc_info,
                                     ::grpc::experimental::InterceptorBatchMethods* interceptor_batch_methods) {
418
    std::lock_guard<std::mutex> lock(context_map_mutex_);
419 420 421 422
    auto request_id = get_request_id(server_rpc_info->server_context());

    if (context_map_.find(request_id) == context_map_.end()) {
        // error
423
        LOG_SERVER_ERROR_ << "request_id " << request_id << " not found in context_map_";
424
        return;
Z
Zhiru Zhu 已提交
425
    }
426 427
    context_map_[request_id]->GetTraceContext()->GetSpan()->Finish();
    context_map_.erase(request_id);
Z
Zhiru Zhu 已提交
428 429
}

J
Jin Hai 已提交
430
std::shared_ptr<Context>
Z
Zhiru Zhu 已提交
431
GrpcRequestHandler::GetContext(::grpc::ServerContext* server_context) {
432
    std::lock_guard<std::mutex> lock(context_map_mutex_);
433
    auto request_id = get_request_id(server_context);
G
groot 已提交
434 435 436

    auto iter = context_map_.find(request_id);
    if (iter == context_map_.end()) {
437
        LOG_SERVER_ERROR_ << "GetContext: request_id " << request_id << " not found in context_map_";
438 439
        return nullptr;
    }
G
groot 已提交
440 441 442 443 444 445

    if (iter->second != nullptr) {
        ConnectionContextPtr connection_context = std::make_shared<GrpcConnectionContext>(server_context);
        iter->second->SetConnectionContext(connection_context);
    }
    return iter->second;
Z
Zhiru Zhu 已提交
446 447 448 449
}

void
GrpcRequestHandler::SetContext(::grpc::ServerContext* server_context, const std::shared_ptr<Context>& context) {
450
    std::lock_guard<std::mutex> lock(context_map_mutex_);
451 452
    auto request_id = get_request_id(server_context);
    context_map_[request_id] = context;
Z
Zhiru Zhu 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466
}

uint64_t
GrpcRequestHandler::random_id() const {
    std::lock_guard<std::mutex> lock(random_mutex_);
    auto value = random_num_generator_();
    while (value == 0) {
        value = random_num_generator_();
    }
    return value;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

K
kun yu 已提交
467
::grpc::Status
G
groot 已提交
468 469
GrpcRequestHandler::CreateCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionSchema* request,
                                     ::milvus::grpc::Status* response) {
470
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
471
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
472

473
    Status status =
474
        request_handler_.CreateCollection(GetContext(context), request->collection_name(), request->dimension(),
475
                                          request->index_file_size(), request->metric_type());
W
Wang XiangYu 已提交
476 477

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
478 479
    SET_RESPONSE(response, status, context);

K
kun yu 已提交
480 481 482 483
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
484 485
GrpcRequestHandler::HasCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                  ::milvus::grpc::BoolReply* response) {
486
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
487
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
488

489
    bool has_collection = false;
490

491
    Status status = request_handler_.HasCollection(GetContext(context), request->collection_name(), has_collection);
492
    response->set_bool_reply(has_collection);
W
Wang XiangYu 已提交
493 494

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
495 496
    SET_RESPONSE(response->mutable_status(), status, context);

K
kun yu 已提交
497 498 499 500
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
501 502
GrpcRequestHandler::DropCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                   ::milvus::grpc::Status* response) {
503
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
504
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
505

506
    Status status = request_handler_.DropCollection(GetContext(context), request->collection_name());
507

W
Wang XiangYu 已提交
508
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
509
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
510 511 512 513
    return ::grpc::Status::OK;
}

::grpc::Status
S
starlord 已提交
514 515
GrpcRequestHandler::CreateIndex(::grpc::ServerContext* context, const ::milvus::grpc::IndexParam* request,
                                ::milvus::grpc::Status* response) {
516
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
517
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
518

519 520 521 522 523 524 525 526
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

527 528
    Status status = request_handler_.CreateIndex(GetContext(context), request->collection_name(), request->index_type(),
                                                 json_params);
529

W
Wang XiangYu 已提交
530
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
531
    SET_RESPONSE(response, status, context);
K
kun yu 已提交
532 533 534 535
    return ::grpc::Status::OK;
}

::grpc::Status
S
starlord 已提交
536 537
GrpcRequestHandler::Insert(::grpc::ServerContext* context, const ::milvus::grpc::InsertParam* request,
                           ::milvus::grpc::VectorIds* response) {
538
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
539
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
540

G
groot 已提交
541 542 543
    // step 1: copy vector data
    engine::VectorsData vectors;
    CopyRowRecords(request->row_record_array(), request->row_id_array(), vectors);
544

G
groot 已提交
545
    // step 2: insert vectors
546
    Status status =
547
        request_handler_.Insert(GetContext(context), request->collection_name(), vectors, request->partition_tag());
548

G
groot 已提交
549 550 551 552
    // step 3: return id array
    response->mutable_vector_id_array()->Resize(static_cast<int>(vectors.id_array_.size()), 0);
    memcpy(response->mutable_vector_id_array()->mutable_data(), vectors.id_array_.data(),
           vectors.id_array_.size() * sizeof(int64_t));
553

W
Wang XiangYu 已提交
554
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
555
    SET_RESPONSE(response->mutable_status(), status, context);
K
kun yu 已提交
556 557 558
    return ::grpc::Status::OK;
}

559
::grpc::Status
560 561
GrpcRequestHandler::GetVectorsByID(::grpc::ServerContext* context, const ::milvus::grpc::VectorsIdentity* request,
                                   ::milvus::grpc::VectorsData* response) {
562
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
563
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
564

565 566 567 568 569 570 571
    std::vector<int64_t> vector_ids;
    vector_ids.reserve(request->id_array_size());
    for (int i = 0; i < request->id_array_size(); i++) {
        vector_ids.push_back(request->id_array(i));
    }

    std::vector<engine::VectorsData> vectors;
G
groot 已提交
572
    Status status =
573 574 575 576 577 578 579 580 581 582 583 584 585
        request_handler_.GetVectorsByID(GetContext(context), request->collection_name(), vector_ids, vectors);

    for (auto& vector : vectors) {
        auto grpc_data = response->add_vectors_data();
        if (!vector.float_data_.empty()) {
            grpc_data->mutable_float_data()->Resize(vector.float_data_.size(), 0);
            memcpy(grpc_data->mutable_float_data()->mutable_data(), vector.float_data_.data(),
                   vector.float_data_.size() * sizeof(float));
        } else if (!vector.binary_data_.empty()) {
            grpc_data->mutable_binary_data()->resize(vector.binary_data_.size());
            memcpy(grpc_data->mutable_binary_data()->data(), vector.binary_data_.data(),
                   vector.binary_data_.size() * sizeof(uint8_t));
        }
586
    }
587

W
Wang XiangYu 已提交
588
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
589 590 591 592 593 594 595 596 597
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::GetVectorIDs(::grpc::ServerContext* context, const ::milvus::grpc::GetVectorIDsParam* request,
                                 ::milvus::grpc::VectorIds* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
598
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
599 600

    std::vector<int64_t> vector_ids;
601
    Status status = request_handler_.GetVectorIDs(GetContext(context), request->collection_name(),
G
groot 已提交
602
                                                  request->segment_name(), vector_ids);
603 604 605 606 607 608

    if (!vector_ids.empty()) {
        response->mutable_vector_id_array()->Resize(vector_ids.size(), -1);
        memcpy(response->mutable_vector_id_array()->mutable_data(), vector_ids.data(),
               vector_ids.size() * sizeof(int64_t));
    }
W
Wang XiangYu 已提交
609 610

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
611 612 613 614 615
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

K
kun yu 已提交
616
::grpc::Status
S
starlord 已提交
617
GrpcRequestHandler::Search(::grpc::ServerContext* context, const ::milvus::grpc::SearchParam* request,
618
                           ::milvus::grpc::TopKQueryResult* response) {
619
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
620
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
621

G
groot 已提交
622 623 624
    // step 1: copy vector data
    engine::VectorsData vectors;
    CopyRowRecords(request->query_record_array(), google::protobuf::RepeatedField<google::protobuf::int64>(), vectors);
625

G
groot 已提交
626
    // step 2: partition tags
627
    std::vector<std::string> partitions;
J
JinHai-CN 已提交
628 629
    std::copy(request->partition_tag_array().begin(), request->partition_tag_array().end(),
              std::back_inserter(partitions));
630

631 632 633 634 635 636 637 638 639 640
    // step 3: parse extra parameters
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

    // step 4: search vectors
641 642
    std::vector<std::string> file_ids;
    TopKQueryResult result;
S
shengjh 已提交
643
    fiu_do_on("GrpcRequestHandler.Search.not_empty_file_ids", file_ids.emplace_back("test_file_id"));
644 645

    Status status = request_handler_.Search(GetContext(context), request->collection_name(), vectors, request->topk(),
646
                                            json_params, partitions, file_ids, result);
647

648
    // step 5: construct and return result
649
    ConstructResults(result, response);
650

W
Wang XiangYu 已提交
651
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
652
    SET_RESPONSE(response->mutable_status(), status, context);
653

654 655 656 657 658 659 660
    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::SearchByID(::grpc::ServerContext* context, const ::milvus::grpc::SearchByIDParam* request,
                               ::milvus::grpc::TopKQueryResult* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
661
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
662 663 664

    // step 1: partition tags
    std::vector<std::string> partitions;
665 666
    std::copy(request->partition_tag_array().begin(), request->partition_tag_array().end(),
              std::back_inserter(partitions));
667

668 669 670 671 672 673 674
    // step 2: partition tags
    std::vector<int64_t> id_array;
    for (int i = 0; i < request->id_array_size(); i++) {
        id_array.push_back(request->id_array(i));
    }

    // step 3: parse extra parameters
675 676 677 678 679 680 681 682
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

683
    // step 4: search vectors
684
    TopKQueryResult result;
685
    Status status = request_handler_.SearchByID(GetContext(context), request->collection_name(), id_array,
686
                                                request->topk(), json_params, partitions, result);
687

688
    // step 5: construct and return result
689
    ConstructResults(result, response);
690

W
Wang XiangYu 已提交
691
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
692 693
    SET_RESPONSE(response->mutable_status(), status, context);

Y
Yu Kun 已提交
694
    return ::grpc::Status::OK;
K
kun yu 已提交
695 696 697
}

::grpc::Status
S
starlord 已提交
698
GrpcRequestHandler::SearchInFiles(::grpc::ServerContext* context, const ::milvus::grpc::SearchInFilesParam* request,
699
                                  ::milvus::grpc::TopKQueryResult* response) {
700
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
701
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
702 703 704

    auto* search_request = &request->search_param();

G
groot 已提交
705 706 707 708
    // step 1: copy vector data
    engine::VectorsData vectors;
    CopyRowRecords(search_request->query_record_array(), google::protobuf::RepeatedField<google::protobuf::int64>(),
                   vectors);
709

G
groot 已提交
710 711
    // step 2: copy file id array
    std::vector<std::string> file_ids;
C
Cross 已提交
712
    std::copy(request->file_id_array().begin(), request->file_id_array().end(), std::back_inserter(file_ids));
G
groot 已提交
713 714

    // step 3: partition tags
715
    std::vector<std::string> partitions;
PJZero's avatar
PJZero 已提交
716 717
    std::copy(search_request->partition_tag_array().begin(), search_request->partition_tag_array().end(),
              std::back_inserter(partitions));
718

719 720 721 722 723 724 725 726 727 728
    // step 4: parse extra parameters
    milvus::json json_params;
    for (int i = 0; i < search_request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = search_request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }

    // step 5: search vectors
729
    TopKQueryResult result;
730
    Status status = request_handler_.Search(GetContext(context), search_request->collection_name(), vectors,
731
                                            search_request->topk(), json_params, partitions, file_ids, result);
732

733
    // step 6: construct and return result
734
    ConstructResults(result, response);
735

W
Wang XiangYu 已提交
736
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
737 738
    SET_RESPONSE(response->mutable_status(), status, context);

Y
Yu Kun 已提交
739
    return ::grpc::Status::OK;
K
kun yu 已提交
740 741 742
}

::grpc::Status
G
groot 已提交
743 744
GrpcRequestHandler::DescribeCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                       ::milvus::grpc::CollectionSchema* response) {
745
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
746
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
747

G
groot 已提交
748 749
    CollectionSchema collection_schema;
    Status status =
750
        request_handler_.DescribeCollection(GetContext(context), request->collection_name(), collection_schema);
G
groot 已提交
751 752 753 754
    response->set_collection_name(collection_schema.collection_name_);
    response->set_dimension(collection_schema.dimension_);
    response->set_index_file_size(collection_schema.index_file_size_);
    response->set_metric_type(collection_schema.metric_type_);
755

W
Wang XiangYu 已提交
756
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
757
    SET_RESPONSE(response->mutable_status(), status, context);
W
Wang XiangYu 已提交
758

K
kun yu 已提交
759 760 761 762
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
763 764
GrpcRequestHandler::CountCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                    ::milvus::grpc::CollectionRowCount* response) {
765
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
766
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
767

K
kun yu 已提交
768
    int64_t row_count = 0;
769
    Status status = request_handler_.CountCollection(GetContext(context), request->collection_name(), row_count);
G
groot 已提交
770
    response->set_collection_row_count(row_count);
W
Wang XiangYu 已提交
771 772

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
773
    SET_RESPONSE(response->mutable_status(), status, context);
W
Wang XiangYu 已提交
774

K
kun yu 已提交
775 776 777 778
    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
779 780
GrpcRequestHandler::ShowCollections(::grpc::ServerContext* context, const ::milvus::grpc::Command* request,
                                    ::milvus::grpc::CollectionNameList* response) {
781
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
782
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
783

G
groot 已提交
784
    std::vector<std::string> collections;
785
    Status status = request_handler_.ShowCollections(GetContext(context), collections);
G
groot 已提交
786 787
    for (auto& collection : collections) {
        response->add_collection_names(collection);
788
    }
W
Wang XiangYu 已提交
789 790

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
791 792
    SET_RESPONSE(response->mutable_status(), status, context);

793
    return ::grpc::Status::OK;
K
kun yu 已提交
794 795
}

796
::grpc::Status
G
groot 已提交
797 798
GrpcRequestHandler::ShowCollectionInfo(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                       ::milvus::grpc::CollectionInfo* response) {
799
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
800
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
801

802
    std::string collection_info;
G
groot 已提交
803
    Status status =
804
        request_handler_.ShowCollectionInfo(GetContext(context), request->collection_name(), collection_info);
805
    response->set_json_info(collection_info);
W
Wang XiangYu 已提交
806 807

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
808 809 810 811 812
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

K
kun yu 已提交
813
::grpc::Status
S
starlord 已提交
814 815
GrpcRequestHandler::Cmd(::grpc::ServerContext* context, const ::milvus::grpc::Command* request,
                        ::milvus::grpc::StringReply* response) {
816
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
817
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
818 819

    std::string reply;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    Status status;

    std::string cmd = request->cmd();
    std::vector<std::string> requests;
    if (cmd == "requests") {
        std::lock_guard<std::mutex> lock(context_map_mutex_);
        for (auto& iter : context_map_) {
            if (nullptr == iter.second) {
                continue;
            }
            if (iter.second->RequestID() == get_request_id(context)) {
                continue;
            }
            auto request_str = RequestMap(iter.second->GetRequestType()) + "-" + iter.second->RequestID();
            requests.emplace_back(request_str);
        }
        nlohmann::json reply_json;
        reply_json["requests"] = requests;
        reply = reply_json.dump();
        response->set_string_reply(reply);
    } else {
        status = request_handler_.Cmd(GetContext(context), cmd, reply);
        response->set_string_reply(reply);
    }
W
Wang XiangYu 已提交
844 845

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
846 847
    SET_RESPONSE(response->mutable_status(), status, context);

K
kun yu 已提交
848 849 850
    return ::grpc::Status::OK;
}

Y
Yu Kun 已提交
851
::grpc::Status
852 853
GrpcRequestHandler::DeleteByID(::grpc::ServerContext* context, const ::milvus::grpc::DeleteByIDParam* request,
                               ::milvus::grpc::Status* response) {
854
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
855
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
856

857 858 859 860 861 862 863
    // step 1: prepare id array
    std::vector<int64_t> vector_ids;
    for (int i = 0; i < request->id_array_size(); i++) {
        vector_ids.push_back(request->id_array(i));
    }

    // step 2: delete vector
864
    Status status = request_handler_.DeleteByID(GetContext(context), request->collection_name(), vector_ids);
W
Wang XiangYu 已提交
865 866

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
867 868
    SET_RESPONSE(response, status, context);

869
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
870 871 872
}

::grpc::Status
G
groot 已提交
873 874
GrpcRequestHandler::PreloadCollection(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
                                      ::milvus::grpc::Status* response) {
875
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
876
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
877

878
    Status status = request_handler_.PreloadCollection(GetContext(context), request->collection_name());
W
Wang XiangYu 已提交
879 880

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
881 882
    SET_RESPONSE(response, status, context);

Y
Yu Kun 已提交
883
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
884 885 886
}

::grpc::Status
G
groot 已提交
887
GrpcRequestHandler::DescribeIndex(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
S
starlord 已提交
888
                                  ::milvus::grpc::IndexParam* response) {
889
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
890
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
891 892

    IndexParam param;
893
    Status status = request_handler_.DescribeIndex(GetContext(context), request->collection_name(), param);
G
groot 已提交
894
    response->set_collection_name(param.collection_name_);
895 896 897 898
    response->set_index_type(param.index_type_);
    ::milvus::grpc::KeyValuePair* kv = response->add_extra_params();
    kv->set_key(EXTRA_PARAM_KEY);
    kv->set_value(param.extra_params_);
W
Wang XiangYu 已提交
899 900

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
901 902
    SET_RESPONSE(response->mutable_status(), status, context);

903
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
904 905 906
}

::grpc::Status
G
groot 已提交
907
GrpcRequestHandler::DropIndex(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
S
starlord 已提交
908
                              ::milvus::grpc::Status* response) {
909
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
910
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
911

912
    Status status = request_handler_.DropIndex(GetContext(context), request->collection_name());
W
Wang XiangYu 已提交
913 914

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
915 916
    SET_RESPONSE(response, status, context);

917
    return ::grpc::Status::OK;
Y
Yu Kun 已提交
918 919
}

G
groot 已提交
920 921 922
::grpc::Status
GrpcRequestHandler::CreatePartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                    ::milvus::grpc::Status* response) {
923
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
924
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
925

926
    Status status = request_handler_.CreatePartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
927 928

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
929 930
    SET_RESPONSE(response, status, context);

G
groot 已提交
931 932 933
    return ::grpc::Status::OK;
}

934 935 936 937
::grpc::Status
GrpcRequestHandler::HasPartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                 ::milvus::grpc::BoolReply* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
938
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
939 940 941 942 943 944

    bool has_collection = false;

    Status status =
        request_handler_.HasPartition(GetContext(context), request->collection_name(), request->tag(), has_collection);
    response->set_bool_reply(has_collection);
W
Wang XiangYu 已提交
945 946

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
947 948 949 950 951
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

G
groot 已提交
952
::grpc::Status
G
groot 已提交
953
GrpcRequestHandler::ShowPartitions(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
G
groot 已提交
954
                                   ::milvus::grpc::PartitionList* response) {
955
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
956
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
957 958

    std::vector<PartitionParam> partitions;
959
    Status status = request_handler_.ShowPartitions(GetContext(context), request->collection_name(), partitions);
960
    for (auto& partition : partitions) {
961
        response->add_partition_tag_array(partition.tag_);
962 963
    }

W
Wang XiangYu 已提交
964
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
965 966
    SET_RESPONSE(response->mutable_status(), status, context);

G
groot 已提交
967 968 969 970 971 972
    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::DropPartition(::grpc::ServerContext* context, const ::milvus::grpc::PartitionParam* request,
                                  ::milvus::grpc::Status* response) {
973
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
974
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
975

976
    Status status = request_handler_.DropPartition(GetContext(context), request->collection_name(), request->tag());
W
Wang XiangYu 已提交
977 978

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
979 980 981 982 983 984 985 986 987
    SET_RESPONSE(response, status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::Flush(::grpc::ServerContext* context, const ::milvus::grpc::FlushParam* request,
                          ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
988
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
989

J
Jin Hai 已提交
990
    std::vector<std::string> collection_names;
G
groot 已提交
991 992
    for (int32_t i = 0; i < request->collection_name_array().size(); i++) {
        collection_names.push_back(request->collection_name_array(i));
993
    }
994
    Status status = request_handler_.Flush(GetContext(context), collection_names);
W
Wang XiangYu 已提交
995 996

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
997 998 999 1000 1001 1002
    SET_RESPONSE(response, status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
G
groot 已提交
1003
GrpcRequestHandler::Compact(::grpc::ServerContext* context, const ::milvus::grpc::CollectionName* request,
1004 1005
                            ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1006
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1007

G
groot 已提交
1008 1009
    double compact_threshold = 0.1;  // compact trigger threshold: delete_counts/segment_counts
    Status status = request_handler_.Compact(GetContext(context), request->collection_name(), compact_threshold);
W
Wang XiangYu 已提交
1010 1011

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1012 1013
    SET_RESPONSE(response, status, context);

G
groot 已提交
1014 1015 1016
    return ::grpc::Status::OK;
}

1017 1018 1019 1020 1021 1022
/*******************************************New Interface*********************************************/

::grpc::Status
GrpcRequestHandler::CreateHybridCollection(::grpc::ServerContext* context, const ::milvus::grpc::Mapping* request,
                                           ::milvus::grpc::Status* response) {
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1023
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

    std::vector<std::pair<std::string, engine::meta::hybrid::DataType>> field_types;
    std::vector<std::pair<std::string, uint64_t>> vector_dimensions;
    std::vector<std::pair<std::string, std::string>> field_params;
    for (uint64_t i = 0; i < request->fields_size(); ++i) {
        if (request->fields(i).type().has_vector_param()) {
            auto vector_dimension =
                std::make_pair(request->fields(i).name(), request->fields(i).type().vector_param().dimension());
            vector_dimensions.emplace_back(vector_dimension);
        } else {
            auto type = std::make_pair(request->fields(i).name(),
                                       (engine::meta::hybrid::DataType)request->fields(i).type().data_type());
            field_types.emplace_back(type);
        }
        // Currently only one extra_param
        if (request->fields(i).extra_params_size() != 0) {
            auto extra_params = std::make_pair(request->fields(i).name(), request->fields(i).extra_params(0).value());
            field_params.emplace_back(extra_params);
        } else {
            auto extra_params = std::make_pair(request->fields(i).name(), "");
            field_params.emplace_back(extra_params);
        }
    }

    Status status = request_handler_.CreateHybridCollection(GetContext(context), request->collection_name(),
                                                            field_types, vector_dimensions, field_params);

W
Wang XiangYu 已提交
1051
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1052 1053 1054 1055 1056
    SET_RESPONSE(response, status, context);

    return ::grpc::Status::OK;
}

1057 1058 1059 1060
::grpc::Status
GrpcRequestHandler::DescribeHybridCollection(::grpc::ServerContext* context,
                                             const ::milvus::grpc::CollectionName* request,
                                             ::milvus::grpc::Mapping* response) {
W
Wang XiangYu 已提交
1061
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1062
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1063
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1064 1065
}

1066 1067 1068
::grpc::Status
GrpcRequestHandler::InsertEntity(::grpc::ServerContext* context, const ::milvus::grpc::HInsertParam* request,
                                 ::milvus::grpc::HEntityIDs* response) {
Y
yukun 已提交
1069 1070 1071
    //    engine::VectorsData vectors;
    //    CopyRowRecords(request->entity().vector_data(0).value(), request->entity_id_array(), vectors);

1072
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1073
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1074

Y
yukun 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    auto attr_size = request->entity().attr_data().size();
    uint64_t row_num = request->entity().row_num();
    std::vector<uint8_t> attr_data(attr_size * row_num * sizeof(int64_t));
    std::unordered_map<std::string, engine::VectorsData> vector_data;
    int64_t offset = 0;
    for (uint64_t i = 0; i < attr_size; i++) {
        auto grpc_int_size = request->entity().attr_data(i).int_value_size();
        auto grpc_double_size = request->entity().attr_data(i).double_value_size();
        if (grpc_int_size > 0) {
            memcpy(attr_data.data() + offset, request->entity().attr_data(i).int_value().data(),
                   grpc_int_size * sizeof(int64_t));
            offset += grpc_int_size * sizeof(int64_t);
        } else if (grpc_double_size > 0) {
            memcpy(attr_data.data() + offset, request->entity().attr_data(i).double_value().data(),
                   grpc_double_size * sizeof(double));
            offset += grpc_double_size * sizeof(double);
        }
    }
1093 1094

    std::vector<std::string> field_names;
Y
yukun 已提交
1095
    auto field_size = request->entity().field_names_size();
1096 1097
    field_names.resize(field_size - 1);
    for (uint64_t i = 0; i < field_size - 1; ++i) {
Y
yukun 已提交
1098
        field_names[i] = request->entity().field_names(i);
1099 1100
    }

Y
yukun 已提交
1101
    auto vector_size = request->entity().vector_data_size();
1102 1103
    for (uint64_t i = 0; i < vector_size; ++i) {
        engine::VectorsData vectors;
Y
yukun 已提交
1104 1105
        CopyRowRecords(request->entity().vector_data(i).value(), request->entity_id_array(), vectors);
        vector_data.insert(std::make_pair(request->entity().field_names(field_size - 1), vectors));
1106 1107 1108 1109
    }

    std::string collection_name = request->collection_name();
    std::string partition_tag = request->partition_tag();
1110
    Status status = request_handler_.InsertEntity(GetContext(context), collection_name, partition_tag, row_num,
Y
yukun 已提交
1111
                                                  field_names, attr_data, vector_data);
1112

Y
yukun 已提交
1113 1114 1115
    response->mutable_entity_id_array()->Resize(static_cast<int>(vector_data.begin()->second.id_array_.size()), 0);
    memcpy(response->mutable_entity_id_array()->mutable_data(), vector_data.begin()->second.id_array_.data(),
           vector_data.begin()->second.id_array_.size() * sizeof(int64_t));
1116

W
Wang XiangYu 已提交
1117
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1118
    SET_RESPONSE(response->mutable_status(), status, context);
W
Wang XiangYu 已提交
1119

1120 1121 1122 1123
    return ::grpc::Status::OK;
}

void
1124
DeSerialization(const ::milvus::grpc::GeneralQuery& general_query, query::BooleanQueryPtr& boolean_clause) {
1125
    if (general_query.has_boolean_query()) {
1126
        boolean_clause->SetOccur((query::Occur)general_query.boolean_query().occur());
1127 1128
        for (uint64_t i = 0; i < general_query.boolean_query().general_query_size(); ++i) {
            if (general_query.boolean_query().general_query(i).has_boolean_query()) {
1129
                query::BooleanQueryPtr query = std::make_shared<query::BooleanQuery>();
1130 1131 1132 1133 1134 1135 1136 1137 1138
                DeSerialization(general_query.boolean_query().general_query(i), query);
                boolean_clause->AddBooleanQuery(query);
            } else {
                auto leaf_query = std::make_shared<query::LeafQuery>();
                auto query = general_query.boolean_query().general_query(i);
                if (query.has_term_query()) {
                    query::TermQueryPtr term_query = std::make_shared<query::TermQuery>();
                    term_query->field_name = query.term_query().field_name();
                    term_query->boost = query.term_query().boost();
Y
yukun 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
                    size_t int_size = query.term_query().int_value_size();
                    size_t double_size = query.term_query().double_value_size();
                    if (int_size > 0) {
                        term_query->field_value.resize(int_size * sizeof(int64_t));
                        memcpy(term_query->field_value.data(), query.term_query().int_value().data(),
                               int_size * sizeof(int64_t));
                    } else if (double_size > 0) {
                        term_query->field_value.resize(double_size * sizeof(double));
                        memcpy(term_query->field_value.data(), query.term_query().double_value().data(),
                               double_size * sizeof(double));
                    }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
                    leaf_query->term_query = term_query;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
                if (query.has_range_query()) {
                    query::RangeQueryPtr range_query = std::make_shared<query::RangeQuery>();
                    range_query->field_name = query.range_query().field_name();
                    range_query->boost = query.range_query().boost();
                    range_query->compare_expr.resize(query.range_query().operand_size());
                    for (uint64_t j = 0; j < query.range_query().operand_size(); ++j) {
                        range_query->compare_expr[j].compare_operator =
                            query::CompareOperator(query.range_query().operand(j).operator_());
                        range_query->compare_expr[j].operand = query.range_query().operand(j).operand();
                    }
                    leaf_query->range_query = range_query;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
                if (query.has_vector_query()) {
                    query::VectorQueryPtr vector_query = std::make_shared<query::VectorQuery>();

                    engine::VectorsData vectors;
                    CopyRowRecords(query.vector_query().records(),
                                   google::protobuf::RepeatedField<google::protobuf::int64>(), vectors);

                    vector_query->query_vector.float_data = vectors.float_data_;
                    vector_query->query_vector.binary_data = vectors.binary_data_;

                    vector_query->boost = query.vector_query().query_boost();
                    vector_query->field_name = query.vector_query().field_name();
                    vector_query->topk = query.vector_query().topk();

                    milvus::json json_params;
                    for (int j = 0; j < query.vector_query().extra_params_size(); j++) {
                        const ::milvus::grpc::KeyValuePair& extra = query.vector_query().extra_params(j);
                        if (extra.key() == EXTRA_PARAM_KEY) {
                            json_params = json::parse(extra.value());
                        }
                    }
                    vector_query->extra_params = json_params;
                    leaf_query->vector_query = vector_query;
                    boolean_clause->AddLeafQuery(leaf_query);
                }
            }
        }
    }
}

::grpc::Status
GrpcRequestHandler::HybridSearch(::grpc::ServerContext* context, const ::milvus::grpc::HSearchParam* request,
Y
yukun 已提交
1198
                                 ::milvus::grpc::HQueryResult* response) {
1199
    CHECK_NULLPTR_RETURN(request);
W
Wang XiangYu 已提交
1200
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

    context::HybridSearchContextPtr hybrid_search_context = std::make_shared<context::HybridSearchContext>();

    query::BooleanQueryPtr boolean_query = std::make_shared<query::BooleanQuery>();
    DeSerialization(request->general_query(), boolean_query);

    query::GeneralQueryPtr general_query = std::make_shared<query::GeneralQuery>();
    query::GenBinaryQuery(boolean_query, general_query->bin);

    Status status;

    if (!query::ValidateBinaryQuery(general_query->bin)) {
        status = Status{SERVER_INVALID_BINARY_QUERY, "Generate wrong binary query tree"};
        SET_RESPONSE(response->mutable_status(), status, context);
        return ::grpc::Status::OK;
    }

    hybrid_search_context->general_query_ = general_query;

    std::vector<std::string> partition_list;
    partition_list.resize(request->partition_tag_array_size());
    for (uint64_t i = 0; i < request->partition_tag_array_size(); ++i) {
        partition_list[i] = request->partition_tag_array(i);
    }

Y
yukun 已提交
1226 1227 1228 1229 1230 1231 1232
    milvus::json json_params;
    for (int i = 0; i < request->extra_params_size(); i++) {
        const ::milvus::grpc::KeyValuePair& extra = request->extra_params(i);
        if (extra.key() == EXTRA_PARAM_KEY) {
            json_params = json::parse(extra.value());
        }
    }
1233

Y
yukun 已提交
1234 1235
    engine::QueryResult result;
    std::vector<std::string> field_names;
1236
    status = request_handler_.HybridSearch(GetContext(context), hybrid_search_context, request->collection_name(),
Y
yukun 已提交
1237
                                           partition_list, general_query, json_params, field_names, result);
1238 1239

    // step 6: construct and return result
Y
yukun 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    response->set_row_num(result.row_num_);
    auto grpc_entity = response->mutable_entity();
    ConstructHEntityResults(result.attrs_, result.vectors_, field_names, grpc_entity);
    grpc_entity->mutable_entity_id()->Resize(static_cast<int>(result.result_ids_.size()), 0);
    memcpy(grpc_entity->mutable_entity_id()->mutable_data(), result.result_ids_.data(),
           result.result_ids_.size() * sizeof(int64_t));

    response->mutable_distance()->Resize(static_cast<int>(result.result_distances_.size()), 0.0);
    memcpy(response->mutable_distance()->mutable_data(), result.result_distances_.data(),
           result.result_distances_.size() * sizeof(float));

    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

::grpc::Status
GrpcRequestHandler::GetEntityByID(::grpc::ServerContext* context, const ::milvus::grpc::VectorsIdentity* request,
                                  ::milvus::grpc::HEntity* response) {
    CHECK_NULLPTR_RETURN(request);
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s begin.", GetContext(context)->RequestID().c_str(), __func__);

    std::vector<int64_t> vector_ids;
    vector_ids.reserve(request->id_array_size());
    for (int i = 0; i < request->id_array_size(); i++) {
        vector_ids.push_back(request->id_array(i));
    }

    std::vector<engine::AttrsData> attrs;
    std::vector<engine::VectorsData> vectors;
    Status status =
        request_handler_.GetEntityByID(GetContext(context), request->collection_name(), vector_ids, attrs, vectors);

    std::vector<std::string> field_names;
    ConstructHEntityResults(attrs, vectors, field_names, response);
1276

W
Wang XiangYu 已提交
1277
    LOG_SERVER_INFO_ << LogOut("Request [%s] %s end.", GetContext(context)->RequestID().c_str(), __func__);
1278 1279 1280 1281 1282
    SET_RESPONSE(response->mutable_status(), status, context);

    return ::grpc::Status::OK;
}

S
starlord 已提交
1283 1284 1285
}  // namespace grpc
}  // namespace server
}  // namespace milvus