WebRequestHandler.cpp 51.5 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
B
BossZou 已提交
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
B
BossZou 已提交
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.
B
BossZou 已提交
11 12 13

#include "server/web_impl/handler/WebRequestHandler.h"

14
#include <algorithm>
B
BossZou 已提交
15
#include <cmath>
16
#include <ctime>
B
BossZou 已提交
17 18 19 20 21 22 23 24 25
#include <string>
#include <vector>

#include "metrics/SystemInfo.h"
#include "server/Config.h"
#include "server/delivery/request/BaseRequest.h"
#include "server/web_impl/Constants.h"
#include "server/web_impl/Types.h"
#include "server/web_impl/dto/PartitionDto.hpp"
26
#include "server/web_impl/utils/Util.h"
27
#include "thirdparty/nlohmann/json.hpp"
28
#include "utils/StringHelpFunctions.h"
B
BossZou 已提交
29
#include "utils/ValidationUtil.h"
B
BossZou 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

namespace milvus {
namespace server {
namespace web {

StatusCode
WebErrorMap(ErrorCode code) {
    static const std::map<ErrorCode, StatusCode> code_map = {
        {SERVER_UNEXPECTED_ERROR, StatusCode::UNEXPECTED_ERROR},
        {SERVER_UNSUPPORTED_ERROR, StatusCode::UNEXPECTED_ERROR},
        {SERVER_NULL_POINTER, StatusCode::UNEXPECTED_ERROR},
        {SERVER_INVALID_ARGUMENT, StatusCode::ILLEGAL_ARGUMENT},
        {SERVER_FILE_NOT_FOUND, StatusCode::FILE_NOT_FOUND},
        {SERVER_NOT_IMPLEMENT, StatusCode::UNEXPECTED_ERROR},
        {SERVER_CANNOT_CREATE_FOLDER, StatusCode::CANNOT_CREATE_FOLDER},
        {SERVER_CANNOT_CREATE_FILE, StatusCode::CANNOT_CREATE_FILE},
        {SERVER_CANNOT_DELETE_FOLDER, StatusCode::CANNOT_DELETE_FOLDER},
        {SERVER_CANNOT_DELETE_FILE, StatusCode::CANNOT_DELETE_FILE},
        {SERVER_TABLE_NOT_EXIST, StatusCode::TABLE_NOT_EXISTS},
        {SERVER_INVALID_TABLE_NAME, StatusCode::ILLEGAL_TABLE_NAME},
        {SERVER_INVALID_TABLE_DIMENSION, StatusCode::ILLEGAL_DIMENSION},
        {SERVER_INVALID_VECTOR_DIMENSION, StatusCode::ILLEGAL_DIMENSION},

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

        {DB_NOT_FOUND, StatusCode::TABLE_NOT_EXISTS},
        {DB_META_TRANSACTION_FAILED, StatusCode::META_FAILED},
    };
70 71 72
    if (code < StatusCode::MAX) {
        return StatusCode(code);
    } else if (code_map.find(code) != code_map.end()) {
B
BossZou 已提交
73 74 75 76 77 78
        return code_map.at(code);
    } else {
        return StatusCode::UNEXPECTED_ERROR;
    }
}

79
/////////////////////////////////// Private methods ///////////////////////////////////////
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
Status
WebRequestHandler::ParseQueryInteger(const OQueryParams& query_params, const std::string& key, int64_t& value,
                                     bool nullable) {
    auto query = query_params.get(key.c_str());
    if (nullptr != query.get() && query->getSize() > 0) {
        std::string value_str = query->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(value_str).ok()) {
            return Status(ILLEGAL_QUERY_PARAM,
                          "Query param \'offset\' is illegal, only non-negative integer supported");
        }

        value = std::stol(value_str);
    } else if (!nullable) {
        return Status(QUERY_PARAM_LOSS, "Query param \"" + key + "\" is required");
    }

    return Status::OK();
}

Status
WebRequestHandler::ParseQueryStr(const OQueryParams& query_params, const std::string& key, std::string& value,
                                 bool nullable) {
    auto query = query_params.get(key.c_str());
    if (nullptr != query.get() && query->getSize() > 0) {
        value = query->std_str();
    } else if (!nullable) {
        return Status(QUERY_PARAM_LOSS, "Query param \"" + key + "\" is required");
    }

    return Status::OK();
}

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
Status
WebRequestHandler::ParseQueryBool(const OQueryParams& query_params, const std::string& key, bool& value,
                                  bool nullable) {
    auto query = query_params.get(key.c_str());
    if (nullptr != query.get() && query->getSize() > 0) {
        std::string value_str = query->std_str();
        if (!ValidationUtil::ValidateStringIsBool(value_str).ok()) {
            return Status(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool");
        }
        value = value_str == "True" || value_str == "true";
        return Status::OK();
    }

    if (!nullable) {
        return Status(QUERY_PARAM_LOSS, "Query param \"" + key + "\" is required");
    }

    return Status::OK();
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
void
WebRequestHandler::AddStatusToJson(nlohmann::json& json, int64_t code, const std::string& msg) {
    json["code"] = (int64_t)code;
    json["message"] = msg;
}

Status
WebRequestHandler::ParseSegmentStat(const milvus::server::SegmentStat& seg_stat, nlohmann::json& json) {
    json["segment_name"] = seg_stat.name_;
    json["index"] = seg_stat.index_name_;
    json["count"] = seg_stat.row_num_;
    json["size"] = seg_stat.data_size_;

    return Status::OK();
}

Status
WebRequestHandler::ParsePartitionStat(const milvus::server::PartitionStat& par_stat, nlohmann::json& json) {
    json["partition_tag"] = par_stat.tag_;
    json["count"] = par_stat.total_row_num_;

    std::vector<nlohmann::json> seg_stat_json;
    for (auto& seg : par_stat.segments_stat_) {
        nlohmann::json seg_json;
        ParseSegmentStat(seg, seg_json);
        seg_stat_json.push_back(seg_json);
    }
    json["segments_stat"] = seg_stat_json;

    return Status::OK();
}

Status
165
WebRequestHandler::IsBinaryTable(const std::string& collection_name, bool& bin) {
166
    TableSchema schema;
167
    auto status = request_handler_.DescribeTable(context_ptr_, collection_name, schema);
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
    if (status.ok()) {
        auto metric = engine::MetricType(schema.metric_type_);
        bin = engine::MetricType::HAMMING == metric || engine::MetricType::JACCARD == metric ||
              engine::MetricType::TANIMOTO == metric;
    }

    return status;
}

Status
WebRequestHandler::CopyRecordsFromJson(const nlohmann::json& json, engine::VectorsData& vectors, bool bin) {
    if (!json.is_array()) {
        return Status(ILLEGAL_BODY, "field \"vectors\" must be a array");
    }

    vectors.vector_count_ = json.size();

    if (!bin) {
        for (auto& vec : json) {
            if (!vec.is_array()) {
                return Status(ILLEGAL_BODY, "A vector in field \"vectors\" must be a float array");
            }
            for (auto& data : vec) {
                vectors.float_data_.emplace_back(data.get<float>());
            }
        }
    } else {
        for (auto& vec : json) {
            if (!vec.is_array()) {
                return Status(ILLEGAL_BODY, "A vector in field \"vectors\" must be a float array");
            }
            for (auto& data : vec) {
                vectors.binary_data_.emplace_back(data.get<uint8_t>());
            }
        }
    }

    return Status::OK();
}

B
BossZou 已提交
208 209
///////////////////////// WebRequestHandler methods ///////////////////////////////////////
Status
210
WebRequestHandler::GetTableMetaInfo(const std::string& collection_name, nlohmann::json& json_out) {
B
BossZou 已提交
211
    TableSchema schema;
212
    auto status = request_handler_.DescribeTable(context_ptr_, collection_name, schema);
B
BossZou 已提交
213 214 215 216 217
    if (!status.ok()) {
        return status;
    }

    int64_t count;
218
    status = request_handler_.CountTable(context_ptr_, collection_name, count);
B
BossZou 已提交
219 220 221 222 223
    if (!status.ok()) {
        return status;
    }

    IndexParam index_param;
224
    status = request_handler_.DescribeIndex(context_ptr_, collection_name, index_param);
B
BossZou 已提交
225 226 227 228
    if (!status.ok()) {
        return status;
    }

229
    json_out["collection_name"] = schema.table_name_;
230 231 232
    json_out["dimension"] = schema.dimension_;
    json_out["index_file_size"] = schema.index_file_size_;
    json_out["index"] = IndexMap.at(engine::EngineType(index_param.index_type_));
233
    json_out["index_params"] = index_param.extra_params_;
234 235 236 237 238 239 240
    json_out["metric_type"] = MetricMap.at(engine::MetricType(schema.metric_type_));
    json_out["count"] = count;

    return Status::OK();
}

Status
241 242 243
WebRequestHandler::GetTableStat(const std::string& collection_name, nlohmann::json& json_out) {
    struct TableInfo collection_info;
    auto status = request_handler_.ShowTableInfo(context_ptr_, collection_name, collection_info);
244 245

    if (status.ok()) {
246
        json_out["count"] = collection_info.total_row_num_;
247 248

        std::vector<nlohmann::json> par_stat_json;
249
        for (auto& par : collection_info.partitions_stat_) {
250 251 252 253 254 255 256 257 258 259 260
            nlohmann::json par_json;
            ParsePartitionStat(par, par_json);
            par_stat_json.push_back(par_json);
        }
        json_out["partitions_stat"] = par_stat_json;
    }

    return status;
}

Status
261 262
WebRequestHandler::GetSegmentVectors(const std::string& collection_name, const std::string& segment_name,
                                     int64_t page_size, int64_t offset, nlohmann::json& json_out) {
263
    std::vector<int64_t> vector_ids;
264
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
265 266 267 268 269 270 271 272 273
    if (!status.ok()) {
        return status;
    }

    auto ids_begin = std::min(vector_ids.size(), (size_t)offset);
    auto ids_end = std::min(vector_ids.size(), (size_t)(offset + page_size));

    auto ids = std::vector<int64_t>(vector_ids.begin() + ids_begin, vector_ids.begin() + ids_end);
    nlohmann::json vectors_json;
274
    status = GetVectorsByIDs(collection_name, ids, vectors_json);
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

    nlohmann::json result_json;
    if (vectors_json.empty()) {
        json_out["vectors"] = std::vector<int64_t>();
    } else {
        json_out["vectors"] = vectors_json;
    }
    json_out["count"] = vector_ids.size();

    AddStatusToJson(json_out, status.code(), status.message());

    return Status::OK();
}

Status
290
WebRequestHandler::GetSegmentIds(const std::string& collection_name, const std::string& segment_name, int64_t page_size,
291 292
                                 int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
293
    auto status = request_handler_.GetVectorIDs(context_ptr_, collection_name, segment_name, vector_ids);
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
    if (status.ok()) {
        auto ids_begin = std::min(vector_ids.size(), (size_t)offset);
        auto ids_end = std::min(vector_ids.size(), (size_t)(offset + page_size));

        if (ids_begin >= ids_end) {
            json_out["ids"] = std::vector<int64_t>();
        } else {
            for (size_t i = ids_begin; i < ids_end; i++) {
                json_out["ids"].push_back(std::to_string(vector_ids.at(i)));
            }
        }
        json_out["count"] = vector_ids.size();
    }

    return status;
309
}
B
BossZou 已提交
310

311 312 313
Status
WebRequestHandler::CommandLine(const std::string& cmd, std::string& reply) {
    return request_handler_.Cmd(context_ptr_, cmd, reply);
B
BossZou 已提交
314 315
}

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
Status
WebRequestHandler::Cmd(const std::string& cmd, std::string& result_str) {
    std::string reply;
    auto status = CommandLine(cmd, reply);

    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result["reply"] = reply;
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::PreLoadTable(const nlohmann::json& json, std::string& result_str) {
333 334
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains collection_name");
335 336
    }

337 338
    auto collection_name = json["collection_name"];
    auto status = request_handler_.PreloadTable(context_ptr_, collection_name.get<std::string>());
339 340 341 342 343
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }
B
BossZou 已提交
344

345 346 347 348 349
    return status;
}

Status
WebRequestHandler::Flush(const nlohmann::json& json, std::string& result_str) {
350 351
    if (!json.contains("collection_names")) {
        return Status(BODY_FIELD_LOSS, "Field \"flush\" must contains collection_names");
352 353
    }

354 355 356
    auto collection_names = json["collection_names"];
    if (!collection_names.is_array()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be and array");
357 358 359
    }

    std::vector<std::string> names;
360
    for (auto& name : collection_names) {
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        names.emplace_back(name.get<std::string>());
    }

    auto status = request_handler_.Flush(context_ptr_, names);
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::Compact(const nlohmann::json& json, std::string& result_str) {
376 377
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains collection_names");
378 379
    }

380 381 382
    auto collection_name = json["collection_name"];
    if (!collection_name.is_string()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be a string");
383 384
    }

385
    auto name = collection_name.get<std::string>();
386 387 388 389 390

    auto status = request_handler_.Compact(context_ptr_, name);

    if (status.ok()) {
        nlohmann::json result;
391
        AddStatusToJson(result, status.code(), status.message());
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::GetConfig(std::string& result_str) {
    std::string cmd = "get_config *";
    std::string reply;
    auto status = CommandLine(cmd, reply);
    if (status.ok()) {
        nlohmann::json j = nlohmann::json::parse(reply);
#ifdef MILVUS_GPU_VERSION
        if (j.contains("gpu_resource_config")) {
            std::vector<std::string> gpus;
            if (j["gpu_resource_config"].contains("search_resources")) {
                auto gpu_search_res = j["gpu_resource_config"]["search_resources"].get<std::string>();
                StringHelpFunctions::SplitStringByDelimeter(gpu_search_res, ",", gpus);
                j["gpu_resource_config"]["search_resources"] = gpus;
            }
            if (j["gpu_resource_config"].contains("build_index_resources")) {
                auto gpu_build_res = j["gpu_resource_config"]["build_index_resources"].get<std::string>();
                gpus.clear();
                StringHelpFunctions::SplitStringByDelimeter(gpu_build_res, ",", gpus);
                j["gpu_resource_config"]["build_index_resources"] = gpus;
            }
        }
#endif
        // check if server require start
        Config& config = Config::GetInstance();
        bool required = false;
        config.GetServerRestartRequired(required);
        j["restart_required"] = required;
        result_str = j.dump();
    }

    return Status::OK();
}

Status
WebRequestHandler::SetConfig(const nlohmann::json& json, std::string& result_str) {
    if (!json.is_object()) {
        return Status(ILLEGAL_BODY, "Payload must be a map");
    }

    std::vector<std::string> cmds;
    for (auto& el : json.items()) {
        auto evalue = el.value();
        if (!evalue.is_object()) {
            return Status(ILLEGAL_BODY, "Invalid payload format, the root value must be json map");
        }

        for (auto& iel : el.value().items()) {
            auto ievalue = iel.value();
            if (!(ievalue.is_string() || ievalue.is_number() || ievalue.is_boolean())) {
                return Status(ILLEGAL_BODY, "Config value must be one of string, numeric or boolean");
            }
            std::ostringstream ss;
            if (ievalue.is_string()) {
                std::string vle = ievalue;
                ss << "set_config " << el.key() << "." << iel.key() << " " << vle;
            } else {
                ss << "set_config " << el.key() << "." << iel.key() << " " << ievalue;
            }
            cmds.emplace_back(ss.str());
        }
    }

    std::string msg;

    for (auto& c : cmds) {
        std::string reply;
        auto status = CommandLine(c, reply);
        if (!status.ok()) {
            return status;
        }
        msg += c + " successfully;";
    }

472 473 474
    nlohmann::json result;
    AddStatusToJson(result, StatusCode::SUCCESS, msg);

475 476 477 478 479 480 481 482 483 484 485
    bool required = false;
    Config& config = Config::GetInstance();
    config.GetServerRestartRequired(required);
    result["restart_required"] = required;

    result_str = result.dump();

    return Status::OK();
}

Status
486
WebRequestHandler::Search(const std::string& collection_name, const nlohmann::json& json, std::string& result_str) {
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    if (!json.contains("topk")) {
        return Status(BODY_FIELD_LOSS, "Field \'topk\' is required");
    }
    int64_t topk = json["topk"];

    std::vector<std::string> partition_tags;
    if (json.contains("partition_tags")) {
        auto tags = json["partition_tags"];
        if (!tags.is_null() && !tags.is_array()) {
            return Status(BODY_PARSE_FAIL, "Field \"partition_tags\" must be a array");
        }

        for (auto& tag : tags) {
            partition_tags.emplace_back(tag.get<std::string>());
        }
    }

504 505 506 507 508
    std::vector<std::string> file_id_vec;
    if (json.contains("file_ids")) {
        auto ids = json["file_ids"];
        if (!ids.is_null() && !ids.is_array()) {
            return Status(BODY_PARSE_FAIL, "Field \"file_ids\" must be a array");
509
        }
510 511
        for (auto& id : ids) {
            file_id_vec.emplace_back(id.get<std::string>());
512
        }
513
    }
514

515 516 517 518
    if (!json.contains("params")) {
        return Status(BODY_FIELD_LOSS, "Field \'params\' is required");
    }

519
    bool bin_flag = false;
520
    auto status = IsBinaryTable(collection_name, bin_flag);
521 522 523
    if (!status.ok()) {
        return status;
    }
524

525 526 527
    if (!json.contains("vectors")) {
        return Status(BODY_FIELD_LOSS, "Field \"vectors\" is required");
    }
528

529 530 531 532 533
    engine::VectorsData vectors_data;
    status = CopyRecordsFromJson(json["vectors"], vectors_data, bin_flag);
    if (!status.ok()) {
        return status;
    }
534

535
    TopKQueryResult result;
536
    status = request_handler_.Search(context_ptr_, collection_name, vectors_data, topk, json["params"], partition_tags,
537 538
                                     file_id_vec, result);

539 540
    if (!status.ok()) {
        return status;
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
    }

    nlohmann::json result_json;
    result_json["num"] = result.row_num_;
    if (result.row_num_ == 0) {
        result_json["result"] = std::vector<int64_t>();
        result_str = result_json.dump();
        return Status::OK();
    }

    auto step = result.id_list_.size() / result.row_num_;
    nlohmann::json search_result_json;
    for (size_t i = 0; i < result.row_num_; i++) {
        nlohmann::json raw_result_json;
        for (size_t j = 0; j < step; j++) {
            nlohmann::json one_result_json;
            one_result_json["id"] = std::to_string(result.id_list_.at(i * step + j));
            one_result_json["distance"] = std::to_string(result.distance_list_.at(i * step + j));
            raw_result_json.emplace_back(one_result_json);
        }
        search_result_json.emplace_back(raw_result_json);
    }
    result_json["result"] = search_result_json;
    result_str = result_json.dump();

    return Status::OK();
}

Status
570 571
WebRequestHandler::DeleteByIDs(const std::string& collection_name, const nlohmann::json& json,
                               std::string& result_str) {
572 573 574 575 576 577 578 579 580 581
    std::vector<int64_t> vector_ids;
    if (!json.contains("ids")) {
        return Status(BODY_FIELD_LOSS, "Field \"delete\" must contains \"ids\"");
    }
    auto ids = json["ids"];
    if (!ids.is_array()) {
        return Status(BODY_FIELD_LOSS, "\"ids\" must be an array");
    }

    for (auto& id : ids) {
582 583 584 585 586
        auto id_str = id.get<std::string>();
        if (!ValidationUtil::ValidateStringIsNumber(id_str).ok()) {
            return Status(ILLEGAL_BODY, "Members in \"ids\" must be integer string");
        }
        vector_ids.emplace_back(std::stol(id_str));
587 588
    }

589
    auto status = request_handler_.DeleteByID(context_ptr_, collection_name, vector_ids);
590 591 592 593

    nlohmann::json result_json;
    AddStatusToJson(result_json, status.code(), status.message());
    result_str = result_json.dump();
594 595 596 597 598

    return status;
}

Status
599
WebRequestHandler::GetVectorsByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
600 601 602 603 604
                                   nlohmann::json& json_out) {
    std::vector<engine::VectorsData> vector_batch;
    for (size_t i = 0; i < ids.size(); i++) {
        auto vec_ids = std::vector<int64_t>(ids.begin() + i, ids.begin() + i + 1);
        engine::VectorsData vectors_data;
605
        auto status = request_handler_.GetVectorByID(context_ptr_, collection_name, vec_ids, vectors_data);
606 607 608 609 610 611 612
        if (!status.ok()) {
            return status;
        }
        vector_batch.push_back(vectors_data);
    }

    bool bin;
613
    auto status = IsBinaryTable(collection_name, bin);
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    if (!status.ok()) {
        return status;
    }

    nlohmann::json vectors_json;
    for (size_t i = 0; i < vector_batch.size(); i++) {
        nlohmann::json vector_json;
        if (bin) {
            vector_json["vector"] = vector_batch.at(i).binary_data_;
        } else {
            vector_json["vector"] = vector_batch.at(i).float_data_;
        }
        vector_json["id"] = std::to_string(ids[i]);
        json_out.push_back(vector_json);
    }

    return Status::OK();
}

////////////////////////////////// Router methods ////////////////////////////////////////////
B
BossZou 已提交
634 635 636 637 638
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
639
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
640 641 642 643 644 645 646 647

    devices_dto->gpus = devices_dto->gpus->createShared();

#ifdef MILVUS_GPU_VERSION
    size_t count = system_info.num_device();
    std::vector<uint64_t> device_mems = system_info.GPUMemoryTotal();

    if (count != device_mems.size()) {
648
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
649 650 651 652
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
653
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
654 655 656 657 658 659 660 661 662 663
        devices_dto->gpus->put("GPU" + OString(std::to_string(i).c_str()), device_dto);
    }
#endif

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::GetAdvancedConfig(AdvancedConfigDto::ObjectWrapper& advanced_config) {
    Config& config = Config::GetInstance();
664 665
    std::string reply;
    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
B
BossZou 已提交
666

667 668
    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY);
    auto status = CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
669
    if (!status.ok()) {
670
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
671
    }
672
    advanced_config->cpu_cache_capacity = std::stol(reply);
B
BossZou 已提交
673

674 675
    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA);
    CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
676 677 678
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
679
    advanced_config->cache_insert_data = ("1" == reply || "true" == reply);
B
BossZou 已提交
680

681 682 683
    auto engine_cmd_prefix = "get_config " + std::string(CONFIG_ENGINE) + ".";
    auto engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_USE_BLAS_THRESHOLD);
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
684 685 686
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
687
    advanced_config->use_blas_threshold = std::stol(reply);
B
BossZou 已提交
688 689

#ifdef MILVUS_GPU_VERSION
690 691
    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_GPU_SEARCH_THRESHOLD);
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
692 693 694
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
695
    advanced_config->gpu_search_threshold = std::stol(reply);
B
BossZou 已提交
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
WebRequestHandler::SetAdvancedConfig(const AdvancedConfigDto::ObjectWrapper& advanced_config) {
    if (nullptr == advanced_config->cpu_cache_capacity.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cpu_cache_capacity\' miss.");
    }

    if (nullptr == advanced_config->cache_insert_data.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_insert_data\' miss.");
    }

    if (nullptr == advanced_config->use_blas_threshold.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'use_blas_threshold\' miss.");
    }

#ifdef MILVUS_GPU_VERSION
    if (nullptr == advanced_config->gpu_search_threshold.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'gpu_search_threshold\' miss.");
    }
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
#endif

    std::string reply;
    std::string cache_cmd_prefix = "set_config " + std::string(CONFIG_CACHE) + ".";

    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY) + " " +
                                   std::to_string(advanced_config->cpu_cache_capacity->getValue());
    auto status = CommandLine(cache_cmd_string, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA) + " " +
                       std::to_string(advanced_config->cache_insert_data->getValue());
    status = CommandLine(cache_cmd_string, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

    auto engine_cmd_prefix = "set_config " + std::string(CONFIG_ENGINE) + ".";

    auto engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_USE_BLAS_THRESHOLD) + " " +
                             std::to_string(advanced_config->use_blas_threshold->getValue());
    status = CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
743 744 745 746
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

747 748 749
#ifdef MILVUS_GPU_VERSION
    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_GPU_SEARCH_THRESHOLD) + " " +
                        std::to_string(advanced_config->gpu_search_threshold->getValue());
750
    status = CommandLine(engine_cmd_string, reply);
751 752 753
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
754 755 756 757 758 759 760 761
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

#ifdef MILVUS_GPU_VERSION
StatusDto::ObjectWrapper
WebRequestHandler::GetGpuConfig(GPUConfigDto::ObjectWrapper& gpu_config_dto) {
762 763
    std::string reply;
    std::string gpu_cmd_prefix = "get_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
B
BossZou 已提交
764

765 766
    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE);
    auto status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
767 768 769
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
770
    gpu_config_dto->enable = reply == "1" || reply == "true";
B
BossZou 已提交
771

772
    if (!gpu_config_dto->enable->getValue()) {
B
BossZou 已提交
773 774 775
        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    }

776 777
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
778 779 780
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
781
    gpu_config_dto->cache_capacity = std::stol(reply);
B
BossZou 已提交
782

783 784
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
785 786 787 788
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

789 790 791
    std::vector<std::string> gpu_entry;
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);

B
BossZou 已提交
792
    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
793 794
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
795
    }
796
    gpu_entry.clear();
B
BossZou 已提交
797

798 799
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
800 801 802 803
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

804
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
B
BossZou 已提交
805
    gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
806 807
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->build_index_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
808 809 810 811 812 813 814
    }

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::SetGpuConfig(const GPUConfigDto::ObjectWrapper& gpu_config_dto) {
815
    // Step 1: Check config param
B
BossZou 已提交
816 817 818
    if (nullptr == gpu_config_dto->enable.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'enable\' miss")
    }
819 820 821

    if (nullptr == gpu_config_dto->cache_capacity.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_capacity\' miss")
B
BossZou 已提交
822 823
    }

824 825 826
    if (nullptr == gpu_config_dto->search_resources.get()) {
        gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
        gpu_config_dto->search_resources->pushBack("GPU0");
B
BossZou 已提交
827 828
    }

829 830 831
    if (nullptr == gpu_config_dto->build_index_resources.get()) {
        gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
        gpu_config_dto->build_index_resources->pushBack("GPU0");
B
BossZou 已提交
832
    }
833 834 835 836 837 838 839

    // Step 2: Set config
    std::string reply;
    std::string gpu_cmd_prefix = "set_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE) + " " +
                                  std::to_string(gpu_config_dto->enable->getValue());
    auto status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
840 841 842 843
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

844 845 846 847 848 849 850 851 852
    if (!gpu_config_dto->enable->getValue()) {
        RETURN_STATUS_DTO(SUCCESS, "Set Gpu resources to false");
    }

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY) + " " +
                      std::to_string(gpu_config_dto->cache_capacity->getValue());
    status = CommandLine(gpu_cmd_request, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
B
BossZou 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866
    }

    std::vector<std::string> search_resources;
    gpu_config_dto->search_resources->forEach(
        [&search_resources](const OString& res) { search_resources.emplace_back(res->toLowerCase()->std_str()); });

    std::string search_resources_value;
    for (auto& res : search_resources) {
        search_resources_value += res + ",";
    }
    auto len = search_resources_value.size();
    if (len > 0) {
        search_resources_value.erase(len - 1);
    }
867 868 869

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " + search_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

    std::vector<std::string> build_resources;
    gpu_config_dto->build_index_resources->forEach(
        [&build_resources](const OString& res) { build_resources.emplace_back(res->toLowerCase()->std_str()); });

    std::string build_resources_value;
    for (auto& res : build_resources) {
        build_resources_value += res + ",";
    }
    len = build_resources_value.size();
    if (len > 0) {
        build_resources_value.erase(len - 1);
    }

887 888 889
    gpu_cmd_request =
        gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES) + " " + build_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
890 891 892 893 894 895 896 897
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}
#endif

898 899 900 901
/*************
 *
 * Table {
 */
B
BossZou 已提交
902
StatusDto::ObjectWrapper
903 904 905
WebRequestHandler::CreateTable(const TableRequestDto::ObjectWrapper& collection_schema) {
    if (nullptr == collection_schema->collection_name.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'collection_name\' is missing")
B
BossZou 已提交
906 907
    }

908
    if (nullptr == collection_schema->dimension.get()) {
B
BossZou 已提交
909 910 911
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'dimension\' is missing")
    }

912
    if (nullptr == collection_schema->index_file_size.get()) {
B
BossZou 已提交
913 914 915
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_file_size\' is missing")
    }

916
    if (nullptr == collection_schema->metric_type.get()) {
B
BossZou 已提交
917 918 919
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

920
    if (MetricNameMap.find(collection_schema->metric_type->std_str()) == MetricNameMap.end()) {
B
BossZou 已提交
921 922 923
        RETURN_STATUS_DTO(ILLEGAL_METRIC_TYPE, "metric_type is illegal")
    }

924 925 926 927
    auto status =
        request_handler_.CreateTable(context_ptr_, collection_schema->collection_name->std_str(),
                                     collection_schema->dimension, collection_schema->index_file_size,
                                     static_cast<int64_t>(MetricNameMap.at(collection_schema->metric_type->std_str())));
B
BossZou 已提交
928 929 930 931 932

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
933
WebRequestHandler::ShowTables(const OQueryParams& query_params, OString& result) {
934 935 936 937
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
938 939
    }

940 941 942 943
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
944 945
    }

946
    if (offset < 0 || page_size < 0) {
947
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
B
BossZou 已提交
948
    }
949

950
    bool all_required = false;
951 952 953
    ParseQueryBool(query_params, "all_required", all_required);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
954 955
    }

956 957
    std::vector<std::string> collections;
    status = request_handler_.ShowTables(context_ptr_, collections);
958 959 960
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
961

962
    if (all_required) {
963
        offset = 0;
964
        page_size = collections.size();
965
    } else {
966 967
        offset = std::min((size_t)offset, collections.size());
        page_size = std::min(collections.size() - offset, (size_t)page_size);
968 969
    }

970
    nlohmann::json collections_json;
971
    for (int64_t i = offset; i < page_size + offset; i++) {
972 973
        nlohmann::json collection_json;
        status = GetTableMetaInfo(collections.at(i), collection_json);
B
BossZou 已提交
974
        if (!status.ok()) {
975
            ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
976
        }
977
        collections_json.push_back(collection_json);
978
    }
979

980
    nlohmann::json result_json;
981 982 983
    result_json["count"] = collections.size();
    if (collections_json.empty()) {
        result_json["collections"] = std::vector<int64_t>();
984
    } else {
985
        result_json["collections"] = collections_json;
B
BossZou 已提交
986 987
    }

988 989
    result = result_json.dump().c_str();

B
BossZou 已提交
990 991 992
    ASSIGN_RETURN_STATUS_DTO(status)
}

993
StatusDto::ObjectWrapper
994 995 996
WebRequestHandler::GetTable(const OString& collection_name, const OQueryParams& query_params, OString& result) {
    if (nullptr == collection_name.get()) {
        RETURN_STATUS_DTO(PATH_PARAM_LOSS, "Path param \'collection_name\' is required!");
997 998
    }

999 1000 1001 1002 1003
    std::string stat;
    auto status = ParseQueryStr(query_params, "info", stat);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
    }
1004

1005
    if (!stat.empty() && stat == "stat") {
1006
        nlohmann::json json;
1007
        status = GetTableStat(collection_name->std_str(), json);
1008
        result = status.ok() ? json.dump().c_str() : "NULL";
1009 1010
    } else {
        nlohmann::json json;
1011
        status = GetTableMetaInfo(collection_name->std_str(), json);
1012
        result = status.ok() ? json.dump().c_str() : "NULL";
1013 1014 1015 1016 1017
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

B
BossZou 已提交
1018
StatusDto::ObjectWrapper
1019 1020
WebRequestHandler::DropTable(const OString& collection_name) {
    auto status = request_handler_.DropTable(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1021 1022 1023 1024

    ASSIGN_RETURN_STATUS_DTO(status)
}

1025 1026 1027 1028 1029
/***********
 *
 * Index {
 */

B
BossZou 已提交
1030
StatusDto::ObjectWrapper
1031 1032 1033 1034 1035 1036
WebRequestHandler::CreateIndex(const OString& table_name, const OString& body) {
    try {
        auto request_json = nlohmann::json::parse(body->std_str());
        if (!request_json.contains("index_type")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_type\' is required");
        }
B
BossZou 已提交
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        std::string index_type = request_json["index_type"];
        if (IndexNameMap.find(index_type) == IndexNameMap.end()) {
            RETURN_STATUS_DTO(ILLEGAL_INDEX_TYPE, "The index type is invalid.")
        }
        auto index = static_cast<int64_t>(IndexNameMap.at(index_type));
        if (!request_json.contains("params")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'params\' is required")
        }
        auto status = request_handler_.CreateIndex(context_ptr_, table_name->std_str(), index, request_json["params"]);
        ASSIGN_RETURN_STATUS_DTO(status);
    } catch (nlohmann::detail::parse_error& e) {
    } catch (nlohmann::detail::type_error& e) {
B
BossZou 已提交
1050 1051
    }

1052
    ASSIGN_RETURN_STATUS_DTO(Status::OK())
B
BossZou 已提交
1053 1054 1055
}

StatusDto::ObjectWrapper
1056
WebRequestHandler::GetIndex(const OString& collection_name, OString& result) {
B
BossZou 已提交
1057
    IndexParam param;
1058
    auto status = request_handler_.DescribeIndex(context_ptr_, collection_name->std_str(), param);
B
BossZou 已提交
1059 1060

    if (status.ok()) {
1061 1062 1063 1064 1065
        nlohmann::json json_out;
        auto index_type = IndexMap.at(engine::EngineType(param.index_type_));
        json_out["index_type"] = index_type;
        json_out["params"] = nlohmann::json::parse(param.extra_params_);
        result = json_out.dump().c_str();
B
BossZou 已提交
1066 1067 1068 1069 1070 1071
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1072 1073
WebRequestHandler::DropIndex(const OString& collection_name) {
    auto status = request_handler_.DropIndex(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1074 1075 1076 1077

    ASSIGN_RETURN_STATUS_DTO(status)
}

1078 1079 1080 1081
/***********
 *
 * Partition {
 */
B
BossZou 已提交
1082
StatusDto::ObjectWrapper
1083
WebRequestHandler::CreatePartition(const OString& collection_name, const PartitionRequestDto::ObjectWrapper& param) {
B
BossZou 已提交
1084 1085 1086 1087
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1088
    auto status =
1089
        request_handler_.CreatePartition(context_ptr_, collection_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1090 1091 1092 1093 1094

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1095
WebRequestHandler::ShowPartitions(const OString& collection_name, const OQueryParams& query_params,
B
BossZou 已提交
1096
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1097 1098 1099 1100
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
1101 1102
    }

1103 1104 1105 1106
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1107 1108
    }

1109
    if (offset < 0 || page_size < 0) {
1110 1111
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1112 1113
    }

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
        if (!ValidationUtil::ValidateStringIsBool(required_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

B
BossZou 已提交
1124
    std::vector<PartitionParam> partitions;
1125
    status = request_handler_.ShowPartitions(context_ptr_, collection_name->std_str(), partitions);
1126 1127 1128
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1129

1130
    if (all_required) {
1131 1132
        offset = 0;
        page_size = partitions.size();
1133
    } else {
1134 1135
        offset = std::min((size_t)offset, partitions.size());
        page_size = std::min(partitions.size() - offset, (size_t)page_size);
1136 1137
    }

1138
    partition_list_dto->count = partitions.size();
1139 1140
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

1141 1142
    if (offset < partitions.size()) {
        for (int64_t i = offset; i < page_size + offset; i++) {
1143 1144 1145
            auto partition_dto = PartitionFieldsDto::createShared();
            partition_dto->partition_tag = partitions.at(i).tag_.c_str();
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1146 1147 1148 1149 1150 1151 1152
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1153
WebRequestHandler::DropPartition(const OString& collection_name, const OString& body) {
1154 1155 1156 1157 1158 1159 1160 1161 1162
    std::string tag;
    try {
        auto json = nlohmann::json::parse(body->std_str());
        tag = json["partition_tag"].get<std::string>();
    } catch (nlohmann::detail::parse_error& e) {
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
    } catch (nlohmann::detail::type_error& e) {
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
    }
1163
    auto status = request_handler_.DropPartition(context_ptr_, collection_name->std_str(), tag);
B
BossZou 已提交
1164 1165 1166 1167

    ASSIGN_RETURN_STATUS_DTO(status)
}

1168 1169 1170 1171
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1172
StatusDto::ObjectWrapper
1173
WebRequestHandler::ShowSegments(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1174 1175 1176 1177
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1178 1179
    }

1180 1181 1182 1183
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1184 1185
    }

1186
    if (offset < 0 || page_size < 0) {
1187 1188 1189
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
        if (!ValidationUtil::ValidateStringIsBool(required_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1200 1201 1202 1203 1204
    std::string tag;
    if (nullptr != query_params.get("partition_tag").get()) {
        tag = query_params.get("partition_tag")->std_str();
    }

1205
    TableInfo info;
1206
    status = request_handler_.ShowTableInfo(context_ptr_, collection_name->std_str(), info);
1207 1208 1209 1210
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1211 1212 1213
    typedef std::pair<std::string, SegmentStat> Pair;
    std::vector<Pair> segments;
    for (auto& par_stat : info.partitions_stat_) {
1214
        if (!(all_required || tag.empty() || tag == par_stat.tag_)) {
1215 1216 1217 1218 1219 1220
            continue;
        }
        for (auto& seg_stat : par_stat.segments_stat_) {
            auto segment_stat = std::pair<std::string, SegmentStat>(par_stat.tag_, seg_stat);
            segments.push_back(segment_stat);
        }
B
BossZou 已提交
1221 1222
    }

1223
    auto compare = [](Pair& a, Pair& b) -> bool { return a.second.name_ >= b.second.name_; };
1224 1225 1226 1227 1228 1229 1230 1231 1232
    std::sort(segments.begin(), segments.end(), compare);

    int64_t size = segments.size();
    int64_t iter_begin = 0;
    int64_t iter_end = size;
    if (!all_required) {
        iter_begin = std::min(size, offset);
        iter_end = std::min(size, offset + page_size);
    }
1233 1234

    nlohmann::json result_json;
1235
    if (segments.empty()) {
1236 1237 1238
        result_json["segments"] = std::vector<int64_t>();
    } else {
        nlohmann::json segs_json;
1239
        for (auto iter = iter_begin; iter < iter_end; iter++) {
1240
            nlohmann::json seg_json;
1241 1242
            ParseSegmentStat(segments.at(iter).second, seg_json);
            seg_json["partition_tag"] = segments.at(iter).first;
1243
            segs_json.push_back(seg_json);
B
BossZou 已提交
1244
        }
1245
        result_json["segments"] = segs_json;
B
BossZou 已提交
1246 1247
    }

1248 1249 1250 1251 1252
    result_json["count"] = size;
    AddStatusToJson(result_json, status.code(), status.message());

    response = result_json.dump().c_str();

B
BossZou 已提交
1253 1254 1255 1256
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1257
WebRequestHandler::GetSegmentInfo(const OString& collection_name, const OString& segment_name, const OString& info,
1258
                                  const OQueryParams& query_params, OString& result) {
1259 1260 1261 1262
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1263 1264
    }

1265 1266 1267 1268
    int64_t page_size = 10;
    status = ParseQueryInteger(query_params, "page_size", page_size);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
B
BossZou 已提交
1269 1270
    }

1271
    if (offset < 0 || page_size < 0) {
1272 1273 1274 1275 1276
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
    }

    std::string re = info->std_str();
1277
    status = Status::OK();
1278 1279 1280
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
1281
        status = GetSegmentVectors(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
1282 1283
        // Get vector ids
    } else if (re == "ids") {
1284
        status = GetSegmentIds(collection_name->std_str(), segment_name->std_str(), page_size, offset, json);
B
BossZou 已提交
1285 1286
    }

1287
    result = status.ok() ? json.dump().c_str() : "NULL";
B
BossZou 已提交
1288

1289 1290 1291 1292 1293 1294 1295 1296
    ASSIGN_RETURN_STATUS_DTO(status)
}

/**********
 *
 * Vector {
 */
StatusDto::ObjectWrapper
1297
WebRequestHandler::Insert(const OString& collection_name, const OString& body, VectorIdsDto::ObjectWrapper& ids_dto) {
1298 1299
    if (nullptr == body.get() || body->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Request payload is required.")
B
BossZou 已提交
1300 1301
    }

1302 1303
    // step 1: copy vectors
    bool bin_flag;
1304
    auto status = IsBinaryTable(collection_name->std_str(), bin_flag);
1305 1306
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1307 1308
    }

1309 1310 1311 1312
    auto body_json = nlohmann::json::parse(body->std_str());
    if (!body_json.contains("vectors")) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'vectors\' is required");
    }
G
groot 已提交
1313
    engine::VectorsData vectors;
1314 1315 1316 1317
    CopyRecordsFromJson(body_json["vectors"], vectors, bin_flag);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1318

1319 1320 1321 1322 1323
    // step 2: copy id array
    if (body_json.contains("ids")) {
        auto& ids_json = body_json["ids"];
        if (!ids_json.is_array()) {
            RETURN_STATUS_DTO(ILLEGAL_BODY, "Field \"ids\" must be a array");
1324
        }
1325 1326 1327 1328
        auto& id_array = vectors.id_array_;
        id_array.clear();
        for (auto& id : ids_json) {
            id_array.emplace_back(id.get<int64_t>());
1329
        }
G
groot 已提交
1330
    }
B
BossZou 已提交
1331

1332 1333 1334 1335
    // step 3: copy partition tag
    std::string tag;
    if (body_json.contains("partition_tag")) {
        tag = body_json["partition_tag"];
1336
    }
B
BossZou 已提交
1337

1338
    // step 4: construct result
1339
    status = request_handler_.Insert(context_ptr_, collection_name->std_str(), vectors, tag);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    if (status.ok()) {
        ids_dto->ids = ids_dto->ids->createShared();
        for (auto& id : vectors.id_array_) {
            ids_dto->ids->pushBack(std::to_string(id).c_str());
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1351
WebRequestHandler::GetVector(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1352 1353 1354 1355
    int64_t id = 0;
    auto status = ParseQueryInteger(query_params, "id", id, false);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1356 1357 1358 1359 1360
    }

    std::vector<int64_t> ids = {id};
    engine::VectorsData vectors;
    nlohmann::json vectors_json;
1361
    status = GetVectorsByIDs(collection_name->std_str(), ids, vectors_json);
B
BossZou 已提交
1362
    if (!status.ok()) {
1363
        response = "NULL";
B
BossZou 已提交
1364 1365 1366
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1367
    nlohmann::json json;
1368
    AddStatusToJson(json, status.code(), status.message());
1369 1370 1371 1372
    if (vectors_json.empty()) {
        json["vectors"] = std::vector<int64_t>();
    } else {
        json["vectors"] = vectors_json;
B
BossZou 已提交
1373 1374
    }

1375 1376 1377 1378 1379 1380
    response = json.dump().c_str();

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1381
WebRequestHandler::VectorsOp(const OString& collection_name, const OString& payload, OString& response) {
1382 1383 1384 1385 1386 1387 1388
    auto status = Status::OK();
    std::string result_str;

    try {
        nlohmann::json payload_json = nlohmann::json::parse(payload->std_str());

        if (payload_json.contains("delete")) {
1389
            status = DeleteByIDs(collection_name->std_str(), payload_json["delete"], result_str);
1390
        } else if (payload_json.contains("search")) {
1391
            status = Search(collection_name->std_str(), payload_json["search"], result_str);
1392 1393
        } else {
            status = Status(ILLEGAL_BODY, "Unknown body");
B
BossZou 已提交
1394
        }
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
    }

1405
    response = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1406 1407 1408 1409

    ASSIGN_RETURN_STATUS_DTO(status)
}

1410 1411 1412 1413
/**********
 *
 * System {
 */
B
BossZou 已提交
1414
StatusDto::ObjectWrapper
1415
WebRequestHandler::SystemInfo(const OString& cmd, const OQueryParams& query_params, OString& response_str) {
1416
    std::string info = cmd->std_str();
1417

1418 1419
    auto status = Status::OK();
    std::string result_str;
1420

1421 1422 1423 1424 1425 1426
    try {
        if (info == "config") {
            status = GetConfig(result_str);
        } else {
            if ("info" == info) {
                info = "get_system_info";
1427
            }
1428
            status = Cmd(info, result_str);
1429
        }
1430 1431
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1432
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1433 1434
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1435
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1436
    }
1437

1438
    response_str = status.ok() ? result_str.c_str() : "NULL";
1439

1440 1441
    ASSIGN_RETURN_STATUS_DTO(status);
}
B
BossZou 已提交
1442

1443 1444 1445 1446 1447
StatusDto::ObjectWrapper
WebRequestHandler::SystemOp(const OString& op, const OString& body_str, OString& response_str) {
    if (nullptr == body_str.get() || body_str->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Payload is empty.");
    }
1448 1449 1450

    Status status = Status::OK();
    std::string result_str;
1451 1452 1453 1454
    try {
        nlohmann::json j = nlohmann::json::parse(body_str->c_str());
        if (op->equals("task")) {
            if (j.contains("load")) {
1455 1456 1457
                status = PreLoadTable(j["load"], result_str);
            } else if (j.contains("flush")) {
                status = Flush(j["flush"], result_str);
1458 1459
            }
            if (j.contains("compact")) {
1460
                status = Compact(j["compact"], result_str);
1461 1462
            }
        } else if (op->equals("config")) {
1463
            status = SetConfig(j, result_str);
1464 1465
        } else {
            status = Status(UNKNOWN_PATH, "Unknown path: /system/" + op->std_str());
1466 1467 1468
        }
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1469
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1470 1471
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1472
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1473 1474
    }

1475
    response_str = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1476 1477 1478 1479 1480 1481 1482

    ASSIGN_RETURN_STATUS_DTO(status);
}

}  // namespace web
}  // namespace server
}  // namespace milvus