WebRequestHandler.cpp 51.8 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 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
/////////////////////////////////// Private methods ///////////////////////////////////////
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
WebRequestHandler::IsBinaryTable(const std::string& table_name, bool& bin) {
    TableSchema schema;
    auto status = request_handler_.DescribeTable(context_ptr_, table_name, schema);
    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 已提交
156 157
///////////////////////// WebRequestHandler methods ///////////////////////////////////////
Status
158
WebRequestHandler::GetTableMetaInfo(const std::string& table_name, nlohmann::json& json_out) {
B
BossZou 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    TableSchema schema;
    auto status = request_handler_.DescribeTable(context_ptr_, table_name, schema);
    if (!status.ok()) {
        return status;
    }

    int64_t count;
    status = request_handler_.CountTable(context_ptr_, table_name, count);
    if (!status.ok()) {
        return status;
    }

    IndexParam index_param;
    status = request_handler_.DescribeIndex(context_ptr_, table_name, index_param);
    if (!status.ok()) {
        return status;
    }

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
    json_out["table_name"] = schema.table_name_;
    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_));
    json_out["nlist"] = index_param.nlist_;
    json_out["metric_type"] = MetricMap.at(engine::MetricType(schema.metric_type_));
    json_out["count"] = count;

    return Status::OK();
}

Status
WebRequestHandler::GetTableStat(const std::string& table_name, nlohmann::json& json_out) {
    struct TableInfo table_info;
    auto status = request_handler_.ShowTableInfo(context_ptr_, table_name, table_info);

    if (status.ok()) {
        json_out["count"] = table_info.total_row_num_;

        std::vector<nlohmann::json> par_stat_json;
        for (auto& par : table_info.partitions_stat_) {
            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
WebRequestHandler::GetSegmentVectors(const std::string& table_name, const std::string& segment_name, int64_t page_size,
                                     int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
    auto status = request_handler_.GetVectorIDs(context_ptr_, table_name, segment_name, vector_ids);
    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;
    status = GetVectorsByIDs(table_name, ids, vectors_json);

    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
WebRequestHandler::GetSegmentIds(const std::string& table_name, const std::string& segment_name, int64_t page_size,
                                 int64_t offset, nlohmann::json& json_out) {
    std::vector<int64_t> vector_ids;
    auto status = request_handler_.GetVectorIDs(context_ptr_, table_name, segment_name, vector_ids);
    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;
257
}
B
BossZou 已提交
258

259 260 261
Status
WebRequestHandler::CommandLine(const std::string& cmd, std::string& reply) {
    return request_handler_.Cmd(context_ptr_, cmd, reply);
B
BossZou 已提交
262 263
}

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
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) {
    if (!json.contains("table_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains table_name");
    }

    auto table_name = json["table_name"];
    auto status = request_handler_.PreloadTable(context_ptr_, table_name.get<std::string>());
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }
B
BossZou 已提交
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 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 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 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 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    return status;
}

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

    auto table_names = json["table_names"];
    if (!table_names.is_array()) {
        return Status(BODY_FIELD_LOSS, "Field \"table_names\" must be and array");
    }

    std::vector<std::string> names;
    for (auto& name : table_names) {
        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["code"] = status.code();
        //        result["message"] = status.message();
        result_str = result.dump();
    }

    return status;
}

Status
WebRequestHandler::Compact(const nlohmann::json& json, std::string& result_str) {
    if (!json.contains("table_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains table_names");
    }

    auto table_name = json["table_name"];
    if (!table_name.is_string()) {
        return Status(BODY_FIELD_LOSS, "Field \"table_names\" must be a string");
    }

    auto name = table_name.get<std::string>();

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

    if (status.ok()) {
        nlohmann::json result;
        result["code"] = status.code();
        result["message"] = status.message();
        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;";
    }

    bool required = false;
    Config& config = Config::GetInstance();
    config.GetServerRestartRequired(required);

    nlohmann::json result;
    result["code"] = StatusCode::SUCCESS;
    result["message"] = msg;
    result["restart_required"] = required;

    result_str = result.dump();

    return Status::OK();
}

Status
WebRequestHandler::Search(const std::string& table_name, const nlohmann::json& json, std::string& result_str) {
    if (!json.contains("topk")) {
        return Status(BODY_FIELD_LOSS, "Field \'topk\' is required");
    }
    int64_t topk = json["topk"];

    if (!json.contains("nprobe")) {
        return Status(BODY_FIELD_LOSS, "Field \'nprobe\' is required");
    }
    int64_t nprobe = json["nprobe"];

    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>());
        }
    }

    TopKQueryResult result;
    if (json.contains("vector_id")) {
        auto vec_id = json["vector_id"].get<int64_t>();
        auto status =
            request_handler_.SearchByID(context_ptr_, table_name, vec_id, topk, nprobe, partition_tags, result);
        if (!status.ok()) {
            return status;
        }
    } else {
        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");
            }
            for (auto& id : ids) {
                file_id_vec.emplace_back(id.get<std::string>());
            }
        }

        bool bin_flag = false;
        auto status = IsBinaryTable(table_name, bin_flag);
        if (!status.ok()) {
            return status;
        }

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

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

        status = request_handler_.Search(context_ptr_, table_name, vectors_data, topk, nprobe, partition_tags,
                                         file_id_vec, result);
        if (!status.ok()) {
            return status;
        }
    }

    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
WebRequestHandler::DeleteByIDs(const std::string& table_name, const nlohmann::json& json, std::string& result_str) {
    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) {
        vector_ids.emplace_back(id.get<int64_t>());
    }

    auto status = request_handler_.DeleteByID(context_ptr_, table_name, vector_ids);
    if (status.ok()) {
        nlohmann::json result_json;
        result_json["code"] = status.code();
        result_json["message"] = status.message();
        result_str = result_json.dump();
    }

    return status;
}

Status
WebRequestHandler::GetVectorsByIDs(const std::string& table_name, const std::vector<int64_t>& ids,
                                   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;
        auto status = request_handler_.GetVectorByID(context_ptr_, table_name, ids, vectors_data);
        if (!status.ok()) {
            return status;
        }
        vector_batch.push_back(vectors_data);
    }

    bool bin;
    auto status = IsBinaryTable(table_name, bin);
    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 ////////////////////////////////////////////

/************
 * Device {
 *
 */
B
BossZou 已提交
597 598 599 600 601
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
602
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
603 604 605 606 607 608 609 610

    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()) {
611
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
612 613 614 615
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
616
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
617 618 619 620 621 622 623 624 625 626
        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();
627 628
    std::string reply;
    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
B
BossZou 已提交
629

630 631
    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY);
    auto status = CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
632
    if (!status.ok()) {
633
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
634
    }
635
    advanced_config->cpu_cache_capacity = std::stol(reply);
B
BossZou 已提交
636

637 638
    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA);
    CommandLine(cache_cmd_string, reply);
B
BossZou 已提交
639 640 641
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
642
    advanced_config->cache_insert_data = ("1" == reply || "true" == reply);
B
BossZou 已提交
643

644 645 646 647
    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 已提交
648 649 650
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
651
    advanced_config->use_blas_threshold = std::stol(reply);
B
BossZou 已提交
652 653

#ifdef MILVUS_GPU_VERSION
654 655
    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_ENGINE_GPU_SEARCH_THRESHOLD);
    CommandLine(engine_cmd_string, reply);
B
BossZou 已提交
656 657 658
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
659
    advanced_config->gpu_search_threshold = std::stol(reply);
B
BossZou 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
#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.");
    }
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
#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 已提交
707 708 709 710
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

711 712 713 714 715 716 717
#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());
    CommandLine(engine_cmd_string, reply);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
718 719 720 721 722 723 724 725
#endif

    ASSIGN_RETURN_STATUS_DTO(status)
}

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

729 730
    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE);
    auto status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
731 732 733
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
734
    gpu_config_dto->enable = reply == "1" || reply == "true";
B
BossZou 已提交
735

736
    if (!gpu_config_dto->enable->getValue()) {
B
BossZou 已提交
737 738 739
        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    }

740 741
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
742 743 744
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }
745
    gpu_config_dto->cache_capacity = std::stol(reply);
B
BossZou 已提交
746

747 748
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
749 750 751 752
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

753 754 755
    std::vector<std::string> gpu_entry;
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);

B
BossZou 已提交
756
    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
757 758
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
759
    }
760
    gpu_entry.clear();
B
BossZou 已提交
761

762 763
    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
764 765 766 767
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

768
    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
B
BossZou 已提交
769
    gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
770 771
    for (auto& device_id : gpu_entry) {
        gpu_config_dto->build_index_resources->pushBack(OString(device_id.c_str())->toUpperCase());
B
BossZou 已提交
772 773 774 775 776 777 778
    }

    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::SetGpuConfig(const GPUConfigDto::ObjectWrapper& gpu_config_dto) {
779
    // Step 1: Check config param
B
BossZou 已提交
780 781 782
    if (nullptr == gpu_config_dto->enable.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'enable\' miss")
    }
783 784 785

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

788 789 790
    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 已提交
791 792
    }

793 794 795
    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 已提交
796
    }
797 798 799 800 801 802 803

    // 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 已提交
804 805 806 807
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

808 809 810 811 812 813 814 815 816
    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 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830
    }

    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);
    }
831 832 833

    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " + search_resources_value;
    status = CommandLine(gpu_cmd_request, reply);
B
BossZou 已提交
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    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);
    }

851 852 853
    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 已提交
854 855 856 857 858 859 860 861
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status);
    }

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

862 863 864 865
/*************
 *
 * Table {
 */
B
BossZou 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
StatusDto::ObjectWrapper
WebRequestHandler::CreateTable(const TableRequestDto::ObjectWrapper& table_schema) {
    if (nullptr == table_schema->table_name.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'table_name\' is missing")
    }

    if (nullptr == table_schema->dimension.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'dimension\' is missing")
    }

    if (nullptr == table_schema->index_file_size.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_file_size\' is missing")
    }

    if (nullptr == table_schema->metric_type.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

    if (MetricNameMap.find(table_schema->metric_type->std_str()) == MetricNameMap.end()) {
        RETURN_STATUS_DTO(ILLEGAL_METRIC_TYPE, "metric_type is illegal")
    }

    auto status = request_handler_.CreateTable(
        context_ptr_, table_schema->table_name->std_str(), table_schema->dimension, table_schema->index_file_size,
        static_cast<int64_t>(MetricNameMap.at(table_schema->metric_type->std_str())));

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
896
WebRequestHandler::ShowTables(const OQueryParams& query_params, OString& result) {
897
    int64_t offset_value = 0;
898 899
    auto offset = query_params.get("offset");
    if (nullptr != offset.get() && offset->getSize() > 0) {
B
BossZou 已提交
900 901 902 903
        std::string offset_str = offset->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(offset_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'offset\' is illegal, only non-negative integer supported");
904
        }
B
BossZou 已提交
905
        offset_value = std::stol(offset_str);
B
BossZou 已提交
906 907
    }

908 909 910
    int64_t page_size_value = 10;
    auto page_size = query_params.get("page_size");
    if (nullptr != page_size.get() && page_size->getSize() > 0) {
B
BossZou 已提交
911 912
        std::string page_size_str = page_size->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(page_size_str).ok()) {
913
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
B
BossZou 已提交
914
                              "Query param \'page_size\' is illegal, only non-negative integer supported");
915
        }
B
BossZou 已提交
916
        page_size_value = std::stol(page_size_str);
917 918 919 920
    }

    if (offset_value < 0 || page_size_value < 0) {
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
B
BossZou 已提交
921
    }
922

923 924 925 926 927 928 929 930 931 932
    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 已提交
933
    std::vector<std::string> tables;
934 935 936 937
    auto status = request_handler_.ShowTables(context_ptr_, tables);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
938

939 940 941 942 943 944
    if (all_required) {
        offset_value = 0;
        page_size_value = tables.size();
    } else {
        offset_value = std::min((size_t)offset_value, tables.size());
        page_size_value = std::min(tables.size() - offset_value, (size_t)page_size_value);
945 946
    }

947 948 949 950
    nlohmann::json tables_json;
    for (int64_t i = offset_value; i < page_size_value + offset_value; i++) {
        nlohmann::json table_json;
        status = GetTableMetaInfo(tables.at(i), table_json);
B
BossZou 已提交
951
        if (!status.ok()) {
952
            ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
953
        }
954 955
        tables_json.push_back(table_json);
    }
956

957 958 959 960 961 962
    nlohmann::json result_json;
    result_json["count"] = tables.size();
    if (tables_json.empty()) {
        result_json["tables"] = std::vector<int64_t>();
    } else {
        result_json["tables"] = tables_json;
B
BossZou 已提交
963 964
    }

965 966
    result = result_json.dump().c_str();

B
BossZou 已提交
967 968 969
    ASSIGN_RETURN_STATUS_DTO(status)
}

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
StatusDto::ObjectWrapper
WebRequestHandler::GetTable(const OString& table_name, const OQueryParams& query_params, OString& result) {
    if (nullptr == table_name.get()) {
        RETURN_STATUS_DTO(PATH_PARAM_LOSS, "Path param \'table_name\' is required!");
    }

    auto status = Status::OK();

    auto stat = query_params.get("info");
    if (nullptr != stat.get() && stat->std_str() == "stat") {
        nlohmann::json json;
        status = GetTableStat(table_name->std_str(), json);
        if (status.ok()) {
            result = json.dump().c_str();
        }
    } else {
        nlohmann::json json;
        status = GetTableMetaInfo(table_name->std_str(), json);
        if (status.ok()) {
            result = json.dump().c_str();
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

B
BossZou 已提交
996 997 998 999 1000 1001 1002
StatusDto::ObjectWrapper
WebRequestHandler::DropTable(const OString& table_name) {
    auto status = request_handler_.DropTable(context_ptr_, table_name->std_str());

    ASSIGN_RETURN_STATUS_DTO(status)
}

1003 1004 1005 1006 1007
/***********
 *
 * Index {
 */

B
BossZou 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
StatusDto::ObjectWrapper
WebRequestHandler::CreateIndex(const OString& table_name, const IndexRequestDto::ObjectWrapper& index_param) {
    if (nullptr == index_param->index_type.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_type\' is required")
    }
    std::string index_type = index_param->index_type->std_str();
    if (IndexNameMap.find(index_type) == IndexNameMap.end()) {
        RETURN_STATUS_DTO(ILLEGAL_INDEX_TYPE, "The index type is invalid.")
    }

    if (nullptr == index_param->nlist.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'nlist\' is required")
    }

    auto status =
        request_handler_.CreateIndex(context_ptr_, table_name->std_str(),
                                     static_cast<int64_t>(IndexNameMap.at(index_type)), index_param->nlist->getValue());
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
WebRequestHandler::GetIndex(const OString& table_name, IndexDto::ObjectWrapper& index_dto) {
    IndexParam param;
    auto status = request_handler_.DescribeIndex(context_ptr_, table_name->std_str(), param);

    if (status.ok()) {
        index_dto->index_type = IndexMap.at(engine::EngineType(param.index_type_)).c_str();
        index_dto->nlist = param.nlist_;
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
WebRequestHandler::DropIndex(const OString& table_name) {
    auto status = request_handler_.DropIndex(context_ptr_, table_name->std_str());

    ASSIGN_RETURN_STATUS_DTO(status)
}

1048 1049 1050 1051
/***********
 *
 * Partition {
 */
B
BossZou 已提交
1052 1053 1054 1055 1056 1057
StatusDto::ObjectWrapper
WebRequestHandler::CreatePartition(const OString& table_name, const PartitionRequestDto::ObjectWrapper& param) {
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1058 1059
    auto status =
        request_handler_.CreatePartition(context_ptr_, table_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1060 1061 1062 1063 1064

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1065
WebRequestHandler::ShowPartitions(const OString& table_name, const OQueryParams& query_params,
B
BossZou 已提交
1066
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1067
    int64_t offset_value = 0;
1068 1069
    auto offset = query_params.get("offset");
    if (nullptr != offset.get() && offset->getSize() > 0) {
B
BossZou 已提交
1070 1071 1072 1073
        std::string offset_str = offset->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(offset_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'offset\' is illegal, only non-negative integer supported");
1074
        }
B
BossZou 已提交
1075
        offset_value = std::stol(offset_str);
B
BossZou 已提交
1076 1077
    }

1078 1079 1080
    int64_t page_size_value = 10;
    auto page_size = query_params.get("page_size");
    if (nullptr != page_size.get() && page_size->getSize() > 0) {
B
BossZou 已提交
1081 1082 1083 1084
        std::string page_size_str = page_size->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(page_size_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'page_size\' is illegal, only non-negative integer supported");
1085
        }
B
BossZou 已提交
1086
        page_size_value = std::stol(page_size_str);
1087 1088 1089 1090 1091
    }

    if (offset_value < 0 || page_size_value < 0) {
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1092 1093
    }

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    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 已提交
1104 1105
    std::vector<PartitionParam> partitions;
    auto status = request_handler_.ShowPartitions(context_ptr_, table_name->std_str(), partitions);
1106 1107 1108
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1109

1110 1111 1112 1113 1114 1115 1116 1117
    if (all_required) {
        offset_value = 0;
        page_size_value = partitions.size();
    } else {
        offset_value = std::min((size_t)offset_value, partitions.size());
        page_size_value = std::min(partitions.size() - offset_value, (size_t)page_size_value);
    }

1118
    partition_list_dto->count = partitions.size();
1119 1120 1121
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

    if (offset_value < partitions.size()) {
1122
        for (int64_t i = offset_value; i < page_size_value + offset_value; i++) {
1123 1124 1125
            auto partition_dto = PartitionFieldsDto::createShared();
            partition_dto->partition_tag = partitions.at(i).tag_.c_str();
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1126 1127 1128 1129 1130 1131 1132
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
WebRequestHandler::DropPartition(const OString& table_name, const OString& body) {
    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())
    }
    auto status = request_handler_.DropPartition(context_ptr_, table_name->std_str(), tag);
B
BossZou 已提交
1144 1145 1146 1147

    ASSIGN_RETURN_STATUS_DTO(status)
}

1148 1149 1150 1151
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1152
StatusDto::ObjectWrapper
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
WebRequestHandler::ShowSegments(const OString& table_name, const OQueryParams& query_params, OString& response) {
    int64_t offset_value = 0;
    auto offset = query_params.get("offset");
    if (nullptr != offset.get() && offset->getSize() > 0) {
        std::string offset_str = offset->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(offset_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'offset\' is illegal, only non-negative integer supported");
        }
        offset_value = std::stol(offset_str);
1163 1164
    }

1165 1166 1167 1168 1169 1170 1171
    int64_t page_size_value = 10;
    auto page_size = query_params.get("page_size");
    if (nullptr != page_size.get() && page_size->getSize() > 0) {
        std::string page_size_str = page_size->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(page_size_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'page_size\' is illegal, only non-negative integer supported");
1172
        }
1173
        page_size_value = std::stol(page_size_str);
1174 1175
    }

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    if (offset_value < 0 || page_size_value < 0) {
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

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

    struct TableInfo info;
    auto status = request_handler_.ShowTableInfo(context_ptr_, table_name->std_str(), info);
1187 1188 1189 1190
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    typedef std::pair<std::string, SegmentStat> Pair;
    std::vector<Pair> segments;
    for (auto& par_stat : info.partitions_stat_) {
        if (!tag.empty() && tag != par_stat.tag_) {
            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 已提交
1201 1202
    }

1203 1204 1205
    int64_t size = segments.size();
    auto iter_begin = std::min(size, offset_value);
    auto iter_end = std::min(size, offset_value + page_size_value);
B
BossZou 已提交
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    auto segments_out = std::vector<Pair>(segments.begin() + iter_begin, segments.begin() + iter_end);

    // sort with segment name
    auto compare = [](Pair& a, Pair& b) -> bool { return a.second.name_ >= b.second.name_; };
    std::sort(segments_out.begin(), segments_out.end(), compare);

    nlohmann::json result_json;
    if (segments_out.empty()) {
        result_json["segments"] = std::vector<int64_t>();
    } else {
        nlohmann::json segs_json;
        for (auto& s : segments_out) {
            nlohmann::json seg_json;
            ParseSegmentStat(s.second, seg_json);
            seg_json["partition_tag"] = s.first;
            segs_json.push_back(seg_json);
B
BossZou 已提交
1223
        }
1224
        result_json["segments"] = segs_json;
B
BossZou 已提交
1225 1226
    }

1227 1228 1229 1230 1231
    result_json["count"] = size;
    AddStatusToJson(result_json, status.code(), status.message());

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

B
BossZou 已提交
1232 1233 1234 1235
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
WebRequestHandler::GetSegmentInfo(const OString& table_name, const OString& segment_name, const OString& info,
                                  const OQueryParams& query_params, OString& result) {
    int64_t offset_value = 0;
    auto offset = query_params.get("offset");
    if (nullptr != offset.get()) {
        std::string offset_str = offset->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(offset_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'offset\' is illegal, only non-negative integer supported");
        }
        offset_value = std::stol(offset_str);
    }

    int64_t page_size_value = 10;
    auto page_size = query_params.get("page_size");
    if (nullptr != page_size.get()) {
        std::string page_size_str = page_size->std_str();
        if (!ValidationUtil::ValidateStringIsNumber(page_size_str).ok()) {
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM,
                              "Query param \'page_size\' is illegal, only non-negative integer supported");
        }
        page_size_value = std::stol(page_size_str);
B
BossZou 已提交
1258 1259
    }

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
    if (offset_value < 0 || page_size_value < 0) {
        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();
    auto status = Status::OK();
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
        status = GetSegmentVectors(table_name->std_str(), segment_name->std_str(), page_size_value, offset_value, json);
        // Get vector ids
    } else if (re == "ids") {
        status = GetSegmentIds(table_name->std_str(), segment_name->std_str(), page_size_value, offset_value, json);
B
BossZou 已提交
1274 1275
    }

1276 1277 1278 1279
    if (status.ok()) {
        result = json.dump().c_str();
    } else {
        result = "NULL";
B
BossZou 已提交
1280 1281
    }

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    ASSIGN_RETURN_STATUS_DTO(status)
}

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

1295 1296 1297
    // step 1: copy vectors
    bool bin_flag;
    auto status = IsBinaryTable(table_name->std_str(), bin_flag);
1298 1299
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1300 1301
    }

1302 1303 1304 1305
    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 已提交
1306
    engine::VectorsData vectors;
1307 1308 1309 1310
    CopyRecordsFromJson(body_json["vectors"], vectors, bin_flag);
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
1311

1312 1313 1314 1315 1316
    // 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");
1317
        }
1318 1319 1320 1321
        auto& id_array = vectors.id_array_;
        id_array.clear();
        for (auto& id : ids_json) {
            id_array.emplace_back(id.get<int64_t>());
1322
        }
G
groot 已提交
1323
    }
B
BossZou 已提交
1324

1325 1326 1327 1328
    // step 3: copy partition tag
    std::string tag;
    if (body_json.contains("partition_tag")) {
        tag = body_json["partition_tag"];
1329
    }
B
BossZou 已提交
1330

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    // step 4: construct result
    status = request_handler_.Insert(context_ptr_, table_name->std_str(), vectors, tag);
    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
WebRequestHandler::GetVector(const OString& table_name, const OQueryParams& query_params, OString& response) {
    auto id_str = query_params.get("id");
    if (id_str.get() == nullptr) {
        RETURN_STATUS_DTO(QUERY_PARAM_LOSS, "Need to specify vector id in query string")
    }
    if (!ValidationUtil::ValidateStringIsNumber(id_str->std_str()).ok()) {
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'id\' is illegal, only non-negative integer supported");
    }

    auto id = std::stol(id_str->c_str());

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

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

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    response = json.dump().c_str();

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
WebRequestHandler::VectorsOp(const OString& table_name, const OString& payload, OString& response) {
    auto status = Status::OK();
    std::string result_str;

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

        if (payload_json.contains("delete")) {
            status = DeleteByIDs(table_name->std_str(), payload_json["delete"], result_str);
        } else if (payload_json.contains("search")) {
            status = Search(table_name->std_str(), payload_json["search"], result_str);
        } else {
            status = Status(ILLEGAL_BODY, "Unknown body");
B
BossZou 已提交
1392
        }
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    } 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());
    }

    if (status.ok()) {
        response = result_str.c_str();
    } else {
        response = "NULL";
B
BossZou 已提交
1407 1408 1409 1410 1411
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

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

1420 1421
    auto status = Status::OK();
    std::string result_str;
1422

1423 1424 1425 1426 1427 1428
    try {
        if (info == "config") {
            status = GetConfig(result_str);
        } else {
            if ("info" == info) {
                info = "get_system_info";
1429
            }
1430
            status = Cmd(info, result_str);
1431
        }
1432 1433 1434 1435 1436 1437 1438
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(ILLEGAL_BODY, 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(ILLEGAL_BODY, emsg.c_str());
    }
1439

1440 1441 1442 1443
    if (status.ok()) {
        response_str = result_str.c_str();
    } else {
        response_str = "NULL";
1444 1445
    }

1446 1447
    ASSIGN_RETURN_STATUS_DTO(status);
}
B
BossZou 已提交
1448

1449 1450 1451 1452 1453
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.");
    }
1454 1455 1456

    Status status = Status::OK();
    std::string result_str;
1457 1458 1459 1460
    try {
        nlohmann::json j = nlohmann::json::parse(body_str->c_str());
        if (op->equals("task")) {
            if (j.contains("load")) {
1461 1462 1463
                status = PreLoadTable(j["load"], result_str);
            } else if (j.contains("flush")) {
                status = Flush(j["flush"], result_str);
1464 1465
            }
            if (j.contains("compact")) {
1466
                status = Compact(j["compact"], result_str);
1467 1468
            }
        } else if (op->equals("config")) {
1469 1470 1471
            SetConfig(j, result_str);
        } else {
            status = Status(UNKNOWN_PATH, "Unknown path: /system/" + op->std_str());
1472 1473 1474 1475 1476 1477 1478 1479 1480
        }
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
        RETURN_STATUS_DTO(ILLEGAL_BODY, 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(ILLEGAL_BODY, emsg.c_str());
    }

1481 1482 1483 1484
    if (status.ok()) {
        response_str = result_str.c_str();
    } else {
        response_str = "NULL";
1485
    }
B
BossZou 已提交
1486 1487 1488 1489 1490 1491 1492

    ASSIGN_RETURN_STATUS_DTO(status);
}

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