WebRequestHandler.cpp 72.0 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>
15
#include <ctime>
B
BossZou 已提交
16
#include <string>
17
#include <unordered_map>
B
BossZou 已提交
18 19
#include <vector>

B
BossZou 已提交
20 21
#include <fiu-local.h>

W
Wang XiangYu 已提交
22
#include "config/ServerConfig.h"
B
BossZou 已提交
23
#include "metrics/SystemInfo.h"
G
groot 已提交
24
#include "query/BinaryQuery.h"
C
Cai Yudong 已提交
25
#include "server/delivery/request/BaseReq.h"
B
BossZou 已提交
26 27 28
#include "server/web_impl/Constants.h"
#include "server/web_impl/Types.h"
#include "server/web_impl/dto/PartitionDto.hpp"
29
#include "server/web_impl/utils/Util.h"
30
#include "thirdparty/nlohmann/json.hpp"
W
Wang XiangYu 已提交
31
#include "utils/ConfigUtils.h"
32
#include "utils/StringHelpFunctions.h"
B
BossZou 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

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},
G
groot 已提交
51 52 53
        {SERVER_COLLECTION_NOT_EXIST, StatusCode::COLLECTION_NOT_EXISTS},
        {SERVER_INVALID_COLLECTION_NAME, StatusCode::ILLEGAL_COLLECTION_NAME},
        {SERVER_INVALID_COLLECTION_DIMENSION, StatusCode::ILLEGAL_DIMENSION},
B
BossZou 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        {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},

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

G
groot 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
template <typename T>
void
CopyStructuredData(const nlohmann::json& json, std::vector<uint8_t>& raw) {
    std::vector<T> values;
    auto size = json.size();
    values.resize(size);
    raw.resize(size * sizeof(T));
    size_t offset = 0;
    for (auto data : json) {
        values[offset] = data.get<T>();
        ++offset;
    }
    memcpy(raw.data(), values.data(), size * sizeof(T));
}

G
groot 已提交
97 98
using FloatJson = nlohmann::basic_json<std::map, std::vector, std::string, bool, std::int64_t, std::uint64_t, float>;

99 100 101 102 103 104 105 106
/////////////////////////////////// Private methods ///////////////////////////////////////
void
WebRequestHandler::AddStatusToJson(nlohmann::json& json, int64_t code, const std::string& msg) {
    json["code"] = (int64_t)code;
    json["message"] = msg;
}

Status
B
BossZou 已提交
107
WebRequestHandler::IsBinaryCollection(const std::string& collection_name, bool& bin) {
J
Jin Hai 已提交
108
    CollectionSchema schema;
C
Cai Yudong 已提交
109
    auto status = req_handler_.GetCollectionInfo(context_ptr_, collection_name, schema);
110
    if (status.ok()) {
C
Cai Yudong 已提交
111 112 113 114
        auto metric = engine::MetricType(schema.extra_params_[engine::PARAM_INDEX_METRIC_TYPE].get<int64_t>());
        bin = (metric == engine::MetricType::HAMMING || metric == engine::MetricType::JACCARD ||
               metric == engine::MetricType::TANIMOTO || metric == engine::MetricType::SUPERSTRUCTURE ||
               metric == engine::MetricType::SUBSTRUCTURE);
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
    }

    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 已提交
151 152
///////////////////////// WebRequestHandler methods ///////////////////////////////////////
Status
B
BossZou 已提交
153
WebRequestHandler::GetCollectionMetaInfo(const std::string& collection_name, nlohmann::json& json_out) {
J
Jin Hai 已提交
154
    CollectionSchema schema;
C
Cai Yudong 已提交
155
    STATUS_CHECK(req_handler_.GetCollectionInfo(context_ptr_, collection_name, schema));
B
BossZou 已提交
156 157

    int64_t count;
C
Cai Yudong 已提交
158
    STATUS_CHECK(req_handler_.CountEntities(context_ptr_, collection_name, count));
B
BossZou 已提交
159

J
Jin Hai 已提交
160
    json_out["collection_name"] = schema.collection_name_;
C
Cai Yudong 已提交
161 162 163 164
    json_out["dimension"] = schema.extra_params_[engine::PARAM_COLLECTION_DIMENSION].get<int64_t>();
    json_out["index_file_size"] = schema.extra_params_[engine::PARAM_SEGMENT_SIZE].get<int64_t>();
    json_out["metric_type"] = schema.extra_params_[engine::PARAM_INDEX_METRIC_TYPE].get<int64_t>();
    json_out["index_params"] = schema.extra_params_[engine::PARAM_INDEX_EXTRA_PARAMS].get<std::string>();
165 166 167 168 169 170
    json_out["count"] = count;

    return Status::OK();
}

Status
B
BossZou 已提交
171
WebRequestHandler::GetCollectionStat(const std::string& collection_name, nlohmann::json& json_out) {
C
Cai Yudong 已提交
172
    std::string collection_stats;
C
Cai Yudong 已提交
173
    auto status = req_handler_.GetCollectionStats(context_ptr_, collection_name, collection_stats);
174 175

    if (status.ok()) {
176
        try {
C
Cai Yudong 已提交
177
            json_out = nlohmann::json::parse(collection_stats);
178
        } catch (std::exception& e) {
B
BossZou 已提交
179 180
            return Status(SERVER_UNEXPECTED_ERROR,
                          "Error occurred when parsing collection stat information: " + std::string(e.what()));
181 182 183 184 185 186 187
        }
    }

    return status;
}

Status
G
groot 已提交
188 189
WebRequestHandler::GetSegmentVectors(const std::string& collection_name, int64_t segment_id, int64_t page_size,
                                     int64_t offset, nlohmann::json& json_out) {
C
Cai Yudong 已提交
190
    engine::IDNumbers vector_ids;
C
Cai Yudong 已提交
191
    STATUS_CHECK(req_handler_.ListIDInSegment(context_ptr_, 0, segment_id, vector_ids));
192 193 194 195

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

C
Cai Yudong 已提交
196
    auto new_ids = std::vector<int64_t>(vector_ids.begin() + ids_begin, vector_ids.begin() + ids_end);
197
    nlohmann::json vectors_json;
C
Cai Yudong 已提交
198
    auto status = GetVectorsByIDs(collection_name, new_ids, vectors_json);
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    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
G
groot 已提交
214
WebRequestHandler::GetSegmentIds(const std::string& collection_name, int64_t segment_id, int64_t page_size,
215
                                 int64_t offset, nlohmann::json& json_out) {
C
Cai Yudong 已提交
216
    std::vector<int64_t> ids;
C
Cai Yudong 已提交
217
    auto status = req_handler_.ListIDInSegment(context_ptr_, collection_name, segment_id, ids);
218
    if (status.ok()) {
C
Cai Yudong 已提交
219 220
        auto ids_begin = std::min(ids.size(), (size_t)offset);
        auto ids_end = std::min(ids.size(), (size_t)(offset + page_size));
221 222 223 224 225

        if (ids_begin >= ids_end) {
            json_out["ids"] = std::vector<int64_t>();
        } else {
            for (size_t i = ids_begin; i < ids_end; i++) {
C
Cai Yudong 已提交
226
                json_out["ids"].push_back(std::to_string(ids.at(i)));
227 228
            }
        }
C
Cai Yudong 已提交
229
        json_out["count"] = ids.size();
230 231 232
    }

    return status;
233
}
B
BossZou 已提交
234

235 236
Status
WebRequestHandler::CommandLine(const std::string& cmd, std::string& reply) {
C
Cai Yudong 已提交
237
    return req_handler_.Cmd(context_ptr_, cmd, reply);
B
BossZou 已提交
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
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
B
BossZou 已提交
256
WebRequestHandler::PreLoadCollection(const nlohmann::json& json, std::string& result_str) {
257 258
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"load\" must contains collection_name");
259 260
    }

261
    auto collection_name = json["collection_name"];
C
Cai Yudong 已提交
262
    auto status = req_handler_.LoadCollection(context_ptr_, collection_name.get<std::string>());
263 264 265 266 267
    if (status.ok()) {
        nlohmann::json result;
        AddStatusToJson(result, status.code(), status.message());
        result_str = result.dump();
    }
B
BossZou 已提交
268

269 270 271 272 273
    return status;
}

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

278 279 280
    auto collection_names = json["collection_names"];
    if (!collection_names.is_array()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be and array");
281 282 283
    }

    std::vector<std::string> names;
284
    for (auto& name : collection_names) {
285 286 287
        names.emplace_back(name.get<std::string>());
    }

C
Cai Yudong 已提交
288
    auto status = req_handler_.Flush(context_ptr_, names);
289 290 291 292 293 294 295 296 297 298 299
    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) {
300 301
    if (!json.contains("collection_name")) {
        return Status(BODY_FIELD_LOSS, "Field \"compact\" must contains collection_names");
302 303
    }

304 305 306
    auto collection_name = json["collection_name"];
    if (!collection_name.is_string()) {
        return Status(BODY_FIELD_LOSS, "Field \"collection_names\" must be a string");
307 308
    }

309
    auto name = collection_name.get<std::string>();
310

G
groot 已提交
311
    double compact_threshold = 0.1;  // compact trigger threshold: delete_counts/segment_counts
C
Cai Yudong 已提交
312
    auto status = req_handler_.Compact(context_ptr_, name, compact_threshold);
313 314 315

    if (status.ok()) {
        nlohmann::json result;
316
        AddStatusToJson(result, status.code(), status.message());
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
        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
        bool required = false;
W
Wang XiangYu 已提交
348 349
        // TODO: Use new cofnig mgr
        // Config::GetInstance().GetServerRestartRequired(required);
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
        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;";
    }

397 398 399
    nlohmann::json result;
    AddStatusToJson(result, StatusCode::SUCCESS, msg);

400
    bool required = false;
W
Wang XiangYu 已提交
401
    // Config::GetInstance().GetServerRestartRequired(required);
402 403 404 405 406 407 408
    result["restart_required"] = required;

    result_str = result.dump();

    return Status::OK();
}

409 410 411 412 413 414 415 416 417 418 419 420
Status
WebRequestHandler::ProcessLeafQueryJson(const nlohmann::json& json, milvus::query::BooleanQueryPtr& query) {
    if (json.contains("term")) {
        auto leaf_query = std::make_shared<query::LeafQuery>();
        auto term_json = json["term"];
        std::string field_name = term_json["field_name"];
        auto term_value_json = term_json["values"];
        if (!term_value_json.is_array()) {
            std::string msg = "Term json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

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
        //        auto term_size = term_value_json.size();
        //        auto term_query = std::make_shared<query::TermQuery>();
        //        term_query->field_name = field_name;
        //        term_query->field_value.resize(term_size * sizeof(int64_t));
        //
        //        switch (field_type_.at(field_name)) {
        //            case engine::meta::hybrid::DataType::INT8:
        //            case engine::meta::hybrid::DataType::INT16:
        //            case engine::meta::hybrid::DataType::INT32:
        //            case engine::meta::hybrid::DataType::INT64: {
        //                std::vector<int64_t> term_value(term_size, 0);
        //                for (uint64_t i = 0; i < term_size; ++i) {
        //                    term_value[i] = term_value_json[i].get<int64_t>();
        //                }
        //                memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(int64_t));
        //                break;
        //            }
        //            case engine::meta::hybrid::DataType::FLOAT:
        //            case engine::meta::hybrid::DataType::DOUBLE: {
        //                std::vector<double> term_value(term_size, 0);
        //                for (uint64_t i = 0; i < term_size; ++i) {
        //                    term_value[i] = term_value_json[i].get<double>();
        //                }
        //                memcpy(term_query->field_value.data(), term_value.data(), term_size * sizeof(double));
        //                break;
        //            }
        //            default:
        //                break;
        //        }
        //
        //        leaf_query->term_query = term_query;
        //        query->AddLeafQuery(leaf_query);
        //    } else if (json.contains("range")) {
        //        auto leaf_query = std::make_shared<query::LeafQuery>();
        //        auto range_query = std::make_shared<query::RangeQuery>();
        //
        //        auto range_json = json["range"];
        //        std::string field_name = range_json["field_name"];
        //        range_query->field_name = field_name;
        //
        //        auto range_value_json = range_json["values"];
        //        if (range_value_json.contains("lt")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::LT;
        //            compare_expr.operand = range_value_json["lt"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //        if (range_value_json.contains("lte")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::LTE;
        //            compare_expr.operand = range_value_json["lte"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //        if (range_value_json.contains("eq")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::EQ;
        //            compare_expr.operand = range_value_json["eq"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //        if (range_value_json.contains("ne")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::NE;
        //            compare_expr.operand = range_value_json["ne"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //        if (range_value_json.contains("gt")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::GT;
        //            compare_expr.operand = range_value_json["gt"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //        if (range_value_json.contains("gte")) {
        //            query::CompareExpr compare_expr;
        //            compare_expr.compare_operator = query::CompareOperator::GTE;
        //            compare_expr.operand = range_value_json["gte"].get<std::string>();
        //            range_query->compare_expr.emplace_back(compare_expr);
        //        }
        //
        //        leaf_query->range_query = range_query;
        //        query->AddLeafQuery(leaf_query);
        //    } else if (json.contains("vector")) {
        //        auto leaf_query = std::make_shared<query::LeafQuery>();
        //        auto vector_query = std::make_shared<query::VectorQuery>();
        //
        //        auto vector_json = json["vector"];
        //        std::string field_name = vector_json["field_name"];
        //        vector_query->field_name = field_name;
        //
        //        engine::VectorsData vectors;
        //        // TODO(yukun): process binary vector
        //        CopyRecordsFromJson(vector_json["values"], vectors, false);
        //
        //        vector_query->query_vector.float_data = vectors.float_data_;
        //        vector_query->query_vector.binary_data = vectors.binary_data_;
        //
        //        vector_query->topk = vector_json["topk"].get<int64_t>();
        //        vector_query->extra_params = vector_json["extra_params"];
        //
        //        // TODO(yukun): remove hardcode here
        //        std::string vector_placeholder = "placeholder_1";
        //        query_ptr_->vectors.insert(std::make_pair(vector_placeholder, vector_query));
        //        leaf_query->vector_placeholder = vector_placeholder;
        //        query->AddLeafQuery(leaf_query);
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
    }
    return Status::OK();
}

Status
WebRequestHandler::ProcessBoolQueryJson(const nlohmann::json& query_json, query::BooleanQueryPtr& boolean_query) {
    if (query_json.contains("must")) {
        boolean_query->SetOccur(query::Occur::MUST);
        auto must_json = query_json["must"];
        if (!must_json.is_array()) {
            std::string msg = "Must json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : must_json) {
            auto must_query = std::make_shared<query::BooleanQuery>();
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                ProcessBoolQueryJson(json, must_query);
                boolean_query->AddBooleanQuery(must_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else if (query_json.contains("should")) {
        boolean_query->SetOccur(query::Occur::SHOULD);
        auto should_json = query_json["should"];
        if (!should_json.is_array()) {
            std::string msg = "Should json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : should_json) {
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                auto should_query = std::make_shared<query::BooleanQuery>();
                ProcessBoolQueryJson(json, should_query);
                boolean_query->AddBooleanQuery(should_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else if (query_json.contains("must_not")) {
        boolean_query->SetOccur(query::Occur::MUST_NOT);
        auto should_json = query_json["must_not"];
        if (!should_json.is_array()) {
            std::string msg = "Must_not json string is not an array";
            return Status{BODY_PARSE_FAIL, msg};
        }

        for (auto& json : should_json) {
            if (json.contains("must") || json.contains("should") || json.contains("must_not")) {
                auto must_not_query = std::make_shared<query::BooleanQuery>();
                ProcessBoolQueryJson(json, must_not_query);
                boolean_query->AddBooleanQuery(must_not_query);
            } else {
                ProcessLeafQueryJson(json, boolean_query);
            }
        }
        return Status::OK();
    } else {
        std::string msg = "Must json string doesnot include right query";
        return Status{BODY_PARSE_FAIL, msg};
    }
}

Y
yukun 已提交
590
void
591
ConvertRowToColumnJson(const std::vector<engine::AttrsData>& row_attrs, const std::vector<std::string>& field_names,
Y
yukun 已提交
592
                       const int64_t row_num, nlohmann::json& column_attrs_json) {
593 594 595 596 597 598 599 600
    //    if (field_names.size() == 0) {
    //        if (row_attrs.size() > 0) {
    //            auto attr_it = row_attrs[0].attr_type_.begin();
    //            for (; attr_it != row_attrs[0].attr_type_.end(); attr_it++) {
    //                field_names.emplace_back(attr_it->first);
    //            }
    //        }
    //    }
Y
yukun 已提交
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692

    for (uint64_t i = 0; i < field_names.size() - 1; i++) {
        std::vector<int64_t> int_data;
        std::vector<double> double_data;
        for (auto& attr : row_attrs) {
            int64_t int_value;
            double double_value;
            auto attr_data = attr.attr_data_.at(field_names[i]);
            switch (attr.attr_type_.at(field_names[i])) {
                case engine::meta::hybrid::DataType::INT8: {
                    if (attr_data.size() == sizeof(int8_t)) {
                        int_value = attr_data[0];
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT16: {
                    if (attr_data.size() == sizeof(int16_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int16_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT32: {
                    if (attr_data.size() == sizeof(int32_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int32_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::INT64: {
                    if (attr_data.size() == sizeof(int64_t)) {
                        memcpy(&int_value, attr_data.data(), sizeof(int64_t));
                        int_data.emplace_back(int_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::FLOAT: {
                    if (attr_data.size() == sizeof(float)) {
                        float float_value;
                        memcpy(&float_value, attr_data.data(), sizeof(float));
                        double_value = float_value;
                        double_data.emplace_back(double_value);
                    }
                    break;
                }
                case engine::meta::hybrid::DataType::DOUBLE: {
                    if (attr_data.size() == sizeof(double)) {
                        memcpy(&double_value, attr_data.data(), sizeof(double));
                        double_data.emplace_back(double_value);
                    }
                    break;
                }
                default: { return; }
            }
        }
        if (int_data.size() > 0) {
            if (row_num == -1) {
                nlohmann::json int_data_json(int_data);
                column_attrs_json[field_names[i]] = int_data_json;
            } else {
                nlohmann::json topk_int_result;
                int64_t topk = int_data.size() / row_num;
                for (int64_t j = 0; j < row_num; j++) {
                    std::vector<int64_t> one_int_result(topk);
                    memcpy(one_int_result.data(), int_data.data() + j * topk, sizeof(int64_t) * topk);
                    nlohmann::json one_int_result_json(one_int_result);
                    std::string tag = "top" + std::to_string(j);
                    topk_int_result[tag] = one_int_result_json;
                }
                column_attrs_json[field_names[i]] = topk_int_result;
            }
        } else if (double_data.size() > 0) {
            if (row_num == -1) {
                nlohmann::json double_data_json(double_data);
                column_attrs_json[field_names[i]] = double_data_json;
            } else {
                nlohmann::json topk_double_result;
                int64_t topk = int_data.size() / row_num;
                for (int64_t j = 0; j < row_num; j++) {
                    std::vector<double> one_double_result(topk);
                    memcpy(one_double_result.data(), double_data.data() + j * topk, sizeof(double) * topk);
                    nlohmann::json one_double_result_json(one_double_result);
                    std::string tag = "top" + std::to_string(j);
                    topk_double_result[tag] = one_double_result_json;
                }
                column_attrs_json[field_names[i]] = topk_double_result;
            }
        }
    }
}

693
Status
G
groot 已提交
694
WebRequestHandler::Search(const std::string& collection_name, const nlohmann::json& json, std::string& result_str) {
695 696
    Status status;

C
Cai Yudong 已提交
697
    milvus::server::CollectionSchema collection_schema;
C
Cai Yudong 已提交
698
    status = req_handler_.GetCollectionInfo(context_ptr_, collection_name, collection_schema);
699 700 701
    if (!status.ok()) {
        return Status{UNEXPECTED_ERROR, "DescribeHybridCollection failed"};
    }
702
    field_type_ = collection_schema.field_types_;
703

Y
yukun 已提交
704 705 706 707 708 709 710 711
    milvus::json extra_params;
    if (json.contains("fields")) {
        if (json["fields"].is_array()) {
            extra_params["fields"] = json["fields"];
        }
    }
    auto query_json = json["query"];

712
    std::vector<std::string> partition_tags;
Y
yukun 已提交
713 714
    if (query_json.contains("partition_tags")) {
        auto tags = query_json["partition_tags"];
715 716 717 718 719 720 721 722 723
        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>());
        }
    }

Y
yukun 已提交
724 725
    if (query_json.contains("bool")) {
        auto boolean_query_json = query_json["bool"];
Y
yukun 已提交
726 727
        auto boolean_query = std::make_shared<query::BooleanQuery>();
        query_ptr_ = std::make_shared<query::Query>();
728 729 730 731 732

        status = ProcessBoolQueryJson(boolean_query_json, boolean_query);
        if (!status.ok()) {
            return status;
        }
Y
yukun 已提交
733
        auto general_query = std::make_shared<query::GeneralQuery>();
734 735
        query::GenBinaryQuery(boolean_query, general_query->bin);

736
        query_ptr_->root = general_query;
Y
yukun 已提交
737

738
        engine::QueryResultPtr result = std::make_shared<engine::QueryResult>();
C
Cai Yudong 已提交
739
        status = req_handler_.Search(context_ptr_, query_ptr_, extra_params, result);
740 741 742 743 744 745

        if (!status.ok()) {
            return status;
        }

        nlohmann::json result_json;
746 747
        result_json["num"] = result->row_num_;
        if (result->row_num_ == 0) {
748 749 750 751 752
            result_json["result"] = std::vector<int64_t>();
            result_str = result_json.dump();
            return Status::OK();
        }

753
        auto step = result->result_ids_.size() / result->row_num_;
754
        nlohmann::json search_result_json;
755
        for (int64_t i = 0; i < result->row_num_; i++) {
756 757 758
            nlohmann::json raw_result_json;
            for (size_t j = 0; j < step; j++) {
                nlohmann::json one_result_json;
759 760
                one_result_json["id"] = std::to_string(result->result_ids_.at(i * step + j));
                one_result_json["distance"] = std::to_string(result->result_distances_.at(i * step + j));
761 762 763 764
                raw_result_json.emplace_back(one_result_json);
            }
            search_result_json.emplace_back(raw_result_json);
        }
Y
yukun 已提交
765
        nlohmann::json attr_json;
766
        ConvertRowToColumnJson(result->attrs_, query_ptr_->field_names, result->row_num_, attr_json);
Y
yukun 已提交
767
        result_json["Entity"] = attr_json;
768 769 770 771 772 773 774
        result_json["result"] = search_result_json;
        result_str = result_json.dump();
    }

    return Status::OK();
}

775
Status
776 777
WebRequestHandler::DeleteByIDs(const std::string& collection_name, const nlohmann::json& json,
                               std::string& result_str) {
778 779 780 781 782 783 784 785 786 787
    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) {
788
        auto id_str = id.get<std::string>();
C
Cai Yudong 已提交
789
        if (!ValidateStringIsNumber(id_str).ok()) {
790 791 792
            return Status(ILLEGAL_BODY, "Members in \"ids\" must be integer string");
        }
        vector_ids.emplace_back(std::stol(id_str));
793 794
    }

C
Cai Yudong 已提交
795
    auto status = req_handler_.DeleteEntityByID(context_ptr_, collection_name, vector_ids);
796 797 798 799

    nlohmann::json result_json;
    AddStatusToJson(result_json, status.code(), status.message());
    result_str = result_json.dump();
800 801 802 803

    return status;
}

Y
yukun 已提交
804 805
Status
WebRequestHandler::GetEntityByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
806
                                  std::vector<std::string>& field_names, nlohmann::json& json_out) {
807
    std::vector<bool> valid_row;
808 809 810
    engine::DataChunkPtr data_chunk;
    engine::snapshot::CollectionMappings field_mappings;

Y
yukun 已提交
811
    std::vector<engine::AttrsData> attr_batch;
812
    std::vector<engine::VectorsData> vector_batch;
813 814
    auto status = req_handler_.GetEntityByID(context_ptr_, collection_name, ids, field_names, valid_row, field_mappings,
                                             data_chunk);
Y
yukun 已提交
815 816 817
    if (!status.ok()) {
        return status;
    }
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    std::vector<uint8_t> id_array = data_chunk->fixed_fields_[engine::DEFAULT_UID_NAME];

    for (const auto& it : field_mappings) {
        std::string name = it.first->GetName();
        uint64_t type = it.first->GetFtype();
        std::vector<uint8_t> data = data_chunk->fixed_fields_[name];
        if (type == engine::FieldType::VECTOR_BINARY) {
            engine::VectorsData vectors_data;
            memcpy(vectors_data.binary_data_.data(), data.data(), data.size());
            memcpy(vectors_data.id_array_.data(), id_array.data(), id_array.size());
            vector_batch.emplace_back(vectors_data);
        } else if (type == engine::FieldType::VECTOR_FLOAT) {
            engine::VectorsData vectors_data;
            memcpy(vectors_data.float_data_.data(), data.data(), data.size());
            memcpy(vectors_data.id_array_.data(), id_array.data(), id_array.size());
            vector_batch.emplace_back(vectors_data);
        } else {
            engine::AttrsData attrs_data;
            attrs_data.attr_type_[name] = static_cast<engine::meta::hybrid::DataType>(type);
            attrs_data.attr_data_[name] = data;
            memcpy(attrs_data.id_array_.data(), id_array.data(), id_array.size());
            attr_batch.emplace_back(attrs_data);
        }
    }
Y
yukun 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

    bool bin;
    status = IsBinaryCollection(collection_name, bin);
    if (!status.ok()) {
        return status;
    }

    nlohmann::json vectors_json, attrs_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]);
        vectors_json.push_back(vector_json);
    }
    ConvertRowToColumnJson(attr_batch, field_names, -1, attrs_json);
    json_out["vectors"] = vectors_json;
    json_out["attributes"] = attrs_json;
863
    return Status::OK();
Y
yukun 已提交
864 865
}

866
Status
867
WebRequestHandler::GetVectorsByIDs(const std::string& collection_name, const std::vector<int64_t>& ids,
868 869
                                   nlohmann::json& json_out) {
    std::vector<engine::VectorsData> vector_batch;
870
    auto status = Status::OK();
C
Cai Yudong 已提交
871
    //    auto status = req_handler_.GetVectorsByID(context_ptr_, collection_name, ids, vector_batch);
872 873
    if (!status.ok()) {
        return status;
874 875 876
    }

    bool bin;
B
BossZou 已提交
877
    status = IsBinaryCollection(collection_name, bin);
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
    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 已提交
898 899 900 901 902
StatusDto::ObjectWrapper
WebRequestHandler::GetDevices(DevicesDto::ObjectWrapper& devices_dto) {
    auto system_info = SystemInfo::GetInstance();

    devices_dto->cpu = devices_dto->cpu->createShared();
903
    devices_dto->cpu->memory = system_info.GetPhysicalMemory() >> 30;
B
BossZou 已提交
904 905 906 907 908

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

#ifdef MILVUS_GPU_VERSION
    size_t count = system_info.num_device();
C
Cai Yudong 已提交
909
    std::vector<int64_t> device_mems = system_info.GPUMemoryTotal();
B
BossZou 已提交
910 911

    if (count != device_mems.size()) {
912
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Can't obtain GPU info");
B
BossZou 已提交
913 914 915 916
    }

    for (size_t i = 0; i < count; i++) {
        auto device_dto = DeviceInfoDto::createShared();
917
        device_dto->memory = device_mems.at(i) >> 30;
B
BossZou 已提交
918 919 920 921 922 923 924 925 926
        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) {
W
Wang XiangYu 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    //    std::string reply;
    //    std::string cache_cmd_prefix = "get_config " + std::string(CONFIG_CACHE) + ".";
    //
    //    std::string cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CPU_CACHE_CAPACITY);
    //    auto status = CommandLine(cache_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->cpu_cache_capacity = std::stol(reply);
    //
    //    cache_cmd_string = cache_cmd_prefix + std::string(CONFIG_CACHE_CACHE_INSERT_DATA);
    //    CommandLine(cache_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->cache_insert_data = ("1" == reply || "true" == reply);
    //
    //    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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->use_blas_threshold = std::stol(reply);
    //
    //#ifdef MILVUS_GPU_VERSION
    //    engine_cmd_string = engine_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD);
    //    CommandLine(engine_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //    advanced_config->gpu_search_threshold = std::stol(reply);
    //#endif
    //
    //    ASSIGN_RETURN_STATUS_DTO(status)
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
963 964 965 966
}

StatusDto::ObjectWrapper
WebRequestHandler::SetAdvancedConfig(const AdvancedConfigDto::ObjectWrapper& advanced_config) {
W
Wang XiangYu 已提交
967 968 969 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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    //    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.");
    //    }
    //#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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //
    //#ifdef MILVUS_GPU_VERSION
    //    auto gpu_cmd_prefix = "set_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    //    auto gpu_cmd_string = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_GPU_SEARCH_THRESHOLD) + " " +
    //                          std::to_string(advanced_config->gpu_search_threshold->getValue());
    //    status = CommandLine(gpu_cmd_string, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status)
    //    }
    //#endif
    //
    //    ASSIGN_RETURN_STATUS_DTO(status)
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1023 1024 1025
}

#ifdef MILVUS_GPU_VERSION
G
groot 已提交
1026

B
BossZou 已提交
1027 1028
StatusDto::ObjectWrapper
WebRequestHandler::GetGpuConfig(GPUConfigDto::ObjectWrapper& gpu_config_dto) {
W
Wang XiangYu 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    //    std::string reply;
    //    std::string gpu_cmd_prefix = "get_config " + std::string(CONFIG_GPU_RESOURCE) + ".";
    //
    //    std::string gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_ENABLE);
    //    auto status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //    gpu_config_dto->enable = reply == "1" || reply == "true";
    //
    //    if (!gpu_config_dto->enable->getValue()) {
    //        ASSIGN_RETURN_STATUS_DTO(Status::OK());
    //    }
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_CACHE_CAPACITY);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //    gpu_config_dto->cache_capacity = std::stol(reply);
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    std::vector<std::string> gpu_entry;
    //    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
    //
    //    gpu_config_dto->search_resources = gpu_config_dto->search_resources->createShared();
    //    for (auto& device_id : gpu_entry) {
    //        gpu_config_dto->search_resources->pushBack(OString(device_id.c_str())->toUpperCase());
    //    }
    //    gpu_entry.clear();
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES);
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    StringHelpFunctions::SplitStringByDelimeter(reply, ",", gpu_entry);
    //    gpu_config_dto->build_index_resources = gpu_config_dto->build_index_resources->createShared();
    //    for (auto& device_id : gpu_entry) {
    //        gpu_config_dto->build_index_resources->pushBack(OString(device_id.c_str())->toUpperCase());
    //    }
    //
    //    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1078 1079 1080 1081 1082
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}

StatusDto::ObjectWrapper
WebRequestHandler::SetGpuConfig(const GPUConfigDto::ObjectWrapper& gpu_config_dto) {
W
Wang XiangYu 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    //    // Step 1: Check config param
    //    if (nullptr == gpu_config_dto->enable.get()) {
    //        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'enable\' miss")
    //    }
    //
    //    if (nullptr == gpu_config_dto->cache_capacity.get()) {
    //        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'cache_capacity\' miss")
    //    }
    //
    //    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");
    //    }
    //
    //    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");
    //    }
    //
    //    // 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);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    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);
    //    }
    //
    //    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);
    //    }
    //
    //    gpu_cmd_request = gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_SEARCH_RESOURCES) + " " +
    //    search_resources_value; status = CommandLine(gpu_cmd_request, reply); 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);
    //    }
    //
    //    gpu_cmd_request =
    //        gpu_cmd_prefix + std::string(CONFIG_GPU_RESOURCE_BUILD_INDEX_RESOURCES) + " " + build_resources_value;
    //    status = CommandLine(gpu_cmd_request, reply);
    //    if (!status.ok()) {
    //        ASSIGN_RETURN_STATUS_DTO(status);
    //    }
    //
    //    ASSIGN_RETURN_STATUS_DTO(Status::OK());
B
BossZou 已提交
1163 1164
    ASSIGN_RETURN_STATUS_DTO(Status::OK());
}
G
groot 已提交
1165

B
BossZou 已提交
1166 1167
#endif

1168 1169
/*************
 *
J
Jin Hai 已提交
1170
 * Collection {
1171
 */
B
BossZou 已提交
1172
StatusDto::ObjectWrapper
B
BossZou 已提交
1173
WebRequestHandler::CreateCollection(const CollectionRequestDto::ObjectWrapper& collection_schema) {
1174 1175
    if (nullptr == collection_schema->collection_name.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'collection_name\' is missing")
B
BossZou 已提交
1176 1177
    }

1178
    if (nullptr == collection_schema->dimension.get()) {
B
BossZou 已提交
1179 1180 1181
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'dimension\' is missing")
    }

1182
    if (nullptr == collection_schema->index_file_size.get()) {
B
BossZou 已提交
1183 1184 1185
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_file_size\' is missing")
    }

1186
    if (nullptr == collection_schema->metric_type.get()) {
B
BossZou 已提交
1187 1188 1189
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'metric_type\' is missing")
    }

1190
    auto status = Status::OK();
C
Cai Yudong 已提交
1191
    //    auto status = req_handler_.CreateCollection(
1192 1193 1194
    //        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 已提交
1195 1196 1197 1198

    ASSIGN_RETURN_STATUS_DTO(status)
}

1199 1200 1201 1202 1203 1204
StatusDto::ObjectWrapper
WebRequestHandler::CreateHybridCollection(const milvus::server::web::OString& body) {
    auto json_str = nlohmann::json::parse(body->c_str());
    std::string collection_name = json_str["collection_name"];

    // TODO(yukun): do checking
1205 1206 1207
    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
    std::unordered_map<std::string, milvus::json> field_index_params;
    std::unordered_map<std::string, std::string> field_extra_params;
1208 1209 1210 1211 1212
    for (auto& field : json_str["fields"]) {
        std::string field_name = field["field_name"];
        std::string field_type = field["field_type"];
        auto extra_params = field["extra_params"];
        if (field_type == "int8") {
1213
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT8));
1214
        } else if (field_type == "int16") {
1215
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT16));
1216
        } else if (field_type == "int32") {
1217
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT32));
1218
        } else if (field_type == "int64") {
1219
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::INT64));
1220
        } else if (field_type == "float") {
1221
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::FLOAT));
1222
        } else if (field_type == "double") {
1223
            field_types.insert(std::make_pair(field_name, engine::meta::hybrid::DataType::DOUBLE));
1224 1225 1226 1227 1228 1229
        } else if (field_type == "vector") {
        } else {
            std::string msg = field_name + " has wrong field_type";
            RETURN_STATUS_DTO(BODY_PARSE_FAIL, msg.c_str());
        }

1230
        field_extra_params.insert(std::make_pair(field_name, extra_params.dump()));
1231 1232
    }

1233 1234
    milvus::json json_params;

C
Cai Yudong 已提交
1235 1236
    auto status = req_handler_.CreateCollection(context_ptr_, collection_name, field_types, field_index_params,
                                                field_extra_params, json_params);
1237 1238 1239 1240

    ASSIGN_RETURN_STATUS_DTO(status)
}

B
BossZou 已提交
1241
StatusDto::ObjectWrapper
B
BossZou 已提交
1242
WebRequestHandler::ShowCollections(const OQueryParams& query_params, OString& result) {
1243 1244 1245 1246
    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 已提交
1247 1248
    }

1249 1250 1251 1252
    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());
1253 1254
    }

1255
    if (offset < 0 || page_size < 0) {
1256
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
B
BossZou 已提交
1257
    }
1258

1259
    bool all_required = false;
1260 1261 1262
    ParseQueryBool(query_params, "all_required", all_required);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1263 1264
    }

1265
    std::vector<std::string> collections;
C
Cai Yudong 已提交
1266
    status = req_handler_.ListCollections(context_ptr_, collections);
1267 1268 1269
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1270

1271
    if (all_required) {
1272
        offset = 0;
1273
        page_size = collections.size();
1274
    } else {
1275 1276
        offset = std::min((size_t)offset, collections.size());
        page_size = std::min(collections.size() - offset, (size_t)page_size);
1277 1278
    }

1279
    nlohmann::json collections_json;
1280
    for (int64_t i = offset; i < page_size + offset; i++) {
1281
        nlohmann::json collection_json;
B
BossZou 已提交
1282
        status = GetCollectionMetaInfo(collections.at(i), collection_json);
B
BossZou 已提交
1283
        if (!status.ok()) {
1284
            ASSIGN_RETURN_STATUS_DTO(status)
B
BossZou 已提交
1285
        }
1286
        collections_json.push_back(collection_json);
1287
    }
1288

1289
    nlohmann::json result_json;
1290 1291 1292
    result_json["count"] = collections.size();
    if (collections_json.empty()) {
        result_json["collections"] = std::vector<int64_t>();
1293
    } else {
1294
        result_json["collections"] = collections_json;
B
BossZou 已提交
1295 1296
    }

1297 1298
    result = result_json.dump().c_str();

B
BossZou 已提交
1299 1300 1301
    ASSIGN_RETURN_STATUS_DTO(status)
}

1302
StatusDto::ObjectWrapper
B
BossZou 已提交
1303
WebRequestHandler::GetCollection(const OString& collection_name, const OQueryParams& query_params, OString& result) {
1304 1305
    if (nullptr == collection_name.get()) {
        RETURN_STATUS_DTO(PATH_PARAM_LOSS, "Path param \'collection_name\' is required!");
1306 1307
    }

1308 1309 1310 1311 1312
    std::string stat;
    auto status = ParseQueryStr(query_params, "info", stat);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
    }
1313

1314
    if (!stat.empty() && stat == "stat") {
1315
        nlohmann::json json;
B
BossZou 已提交
1316
        status = GetCollectionStat(collection_name->std_str(), json);
1317
        result = status.ok() ? json.dump().c_str() : "NULL";
1318 1319
    } else {
        nlohmann::json json;
B
BossZou 已提交
1320
        status = GetCollectionMetaInfo(collection_name->std_str(), json);
1321
        result = status.ok() ? json.dump().c_str() : "NULL";
1322 1323 1324 1325 1326
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

B
BossZou 已提交
1327
StatusDto::ObjectWrapper
B
BossZou 已提交
1328
WebRequestHandler::DropCollection(const OString& collection_name) {
C
Cai Yudong 已提交
1329
    auto status = req_handler_.DropCollection(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1330 1331 1332 1333

    ASSIGN_RETURN_STATUS_DTO(status)
}

1334 1335 1336 1337 1338
/***********
 *
 * Index {
 */

B
BossZou 已提交
1339
StatusDto::ObjectWrapper
J
Jin Hai 已提交
1340
WebRequestHandler::CreateIndex(const OString& collection_name, const OString& body) {
1341 1342
    try {
        auto request_json = nlohmann::json::parse(body->std_str());
1343
        std::string field_name, index_name;
1344 1345 1346
        if (!request_json.contains("index_type")) {
            RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'index_type\' is required");
        }
B
BossZou 已提交
1347

1348 1349
        auto status = Status::OK();
        //        auto status =
C
Cai Yudong 已提交
1350
        //            req_handler_.CreateIndex(context_ptr_, collection_name->std_str(), index,
1351
        //            request_json["params"]);
1352 1353
        ASSIGN_RETURN_STATUS_DTO(status);
    } catch (nlohmann::detail::parse_error& e) {
Y
Yhz 已提交
1354
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
1355
    } catch (nlohmann::detail::type_error& e) {
Y
Yhz 已提交
1356
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, e.what())
B
BossZou 已提交
1357 1358
    }

1359
    ASSIGN_RETURN_STATUS_DTO(Status::OK())
B
BossZou 已提交
1360 1361 1362
}

StatusDto::ObjectWrapper
1363
WebRequestHandler::DropIndex(const OString& collection_name) {
1364
    auto status = Status::OK();
C
Cai Yudong 已提交
1365
    //    auto status = req_handler_.DropIndex(context_ptr_, collection_name->std_str());
B
BossZou 已提交
1366 1367 1368 1369 1370

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1371
WebRequestHandler::CreatePartition(const OString& collection_name, const PartitionRequestDto::ObjectWrapper& param) {
B
BossZou 已提交
1372 1373 1374 1375
    if (nullptr == param->partition_tag.get()) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Field \'partition_tag\' is required")
    }

1376
    auto status =
C
Cai Yudong 已提交
1377
        req_handler_.CreatePartition(context_ptr_, collection_name->std_str(), param->partition_tag->std_str());
B
BossZou 已提交
1378 1379 1380 1381 1382

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
B
BossZou 已提交
1383
WebRequestHandler::ShowPartitions(const OString& collection_name, const OQueryParams& query_params,
B
BossZou 已提交
1384
                                  PartitionListDto::ObjectWrapper& partition_list_dto) {
1385 1386 1387 1388
    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 已提交
1389 1390
    }

1391 1392 1393 1394
    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());
1395 1396
    }

1397
    if (offset < 0 || page_size < 0) {
1398 1399
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
B
BossZou 已提交
1400 1401
    }

1402 1403 1404 1405
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1406
        if (!ValidateStringIsBool(required_str).ok()) {
1407 1408 1409 1410 1411
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

1412
    std::vector<std::string> partition_names;
C
Cai Yudong 已提交
1413
    status = req_handler_.ListPartitions(context_ptr_, collection_name->std_str(), partition_names);
1414 1415 1416
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }
B
BossZou 已提交
1417

1418
    if (all_required) {
1419
        offset = 0;
1420
        page_size = partition_names.size();
1421
    } else {
1422 1423
        offset = std::min((size_t)offset, partition_names.size());
        page_size = std::min(partition_names.size() - offset, (size_t)page_size);
1424 1425
    }

1426
    partition_list_dto->count = partition_names.size();
1427 1428
    partition_list_dto->partitions = partition_list_dto->partitions->createShared();

1429
    if (offset < (int64_t)(partition_names.size())) {
1430
        for (int64_t i = offset; i < page_size + offset; i++) {
1431
            auto partition_dto = PartitionFieldsDto::createShared();
1432
            partition_dto->partition_tag = partition_names.at(i).c_str();
1433
            partition_list_dto->partitions->pushBack(partition_dto);
B
BossZou 已提交
1434 1435 1436 1437 1438 1439 1440
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1441
WebRequestHandler::DropPartition(const OString& collection_name, const OString& body) {
1442 1443 1444 1445 1446 1447 1448 1449 1450
    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())
    }
C
Cai Yudong 已提交
1451
    auto status = req_handler_.DropPartition(context_ptr_, collection_name->std_str(), tag);
B
BossZou 已提交
1452 1453 1454 1455

    ASSIGN_RETURN_STATUS_DTO(status)
}

1456 1457 1458 1459
/***********
 *
 * Segment {
 */
B
BossZou 已提交
1460
StatusDto::ObjectWrapper
1461
WebRequestHandler::ShowSegments(const OString& collection_name, const OQueryParams& query_params, OString& response) {
1462 1463 1464 1465
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1466 1467
    }

1468 1469 1470 1471
    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());
1472 1473
    }

1474
    if (offset < 0 || page_size < 0) {
1475 1476 1477
        RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param 'offset' or 'page_size' should equal or bigger than 0");
    }

1478 1479 1480 1481
    bool all_required = false;
    auto required = query_params.get("all_required");
    if (nullptr != required.get()) {
        auto required_str = required->std_str();
C
Cai Yudong 已提交
1482
        if (!ValidateStringIsBool(required_str).ok()) {
1483 1484 1485 1486 1487
            RETURN_STATUS_DTO(ILLEGAL_QUERY_PARAM, "Query param \'all_required\' must be a bool")
        }
        all_required = required_str == "True" || required_str == "true";
    }

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

C
Cai Yudong 已提交
1493
    std::string stats;
C
Cai Yudong 已提交
1494
    status = req_handler_.GetCollectionStats(context_ptr_, collection_name->std_str(), stats);
1495 1496 1497 1498
    if (!status.ok()) {
        ASSIGN_RETURN_STATUS_DTO(status)
    }

C
Cai Yudong 已提交
1499
    nlohmann::json info_json = nlohmann::json::parse(stats);
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    nlohmann::json segments_json = nlohmann::json::array();
    for (auto& par : info_json["partitions"]) {
        if (!(all_required || tag.empty() || tag == par["tag"])) {
            continue;
        }

        auto segments = par["segments"];
        if (!segments.is_null()) {
            for (auto& seg : segments) {
                seg["partition_tag"] = par["tag"];
                segments_json.push_back(seg);
            }
        }
    }
    nlohmann::json result_json;
    if (!all_required) {
        int64_t size = segments_json.size();
        int iter_begin = std::min(size, offset);
        int iter_end = std::min(size, offset + page_size);

        nlohmann::json segments_slice_json = nlohmann::json::array();
        segments_slice_json.insert(segments_slice_json.begin(), segments_json.begin() + iter_begin,
                                   segments_json.begin() + iter_end);
        result_json["segments"] = segments_slice_json;  // segments_json;
    } else {
        result_json["segments"] = segments_json;
    }
    result_json["count"] = segments_json.size();
1528 1529 1530
    AddStatusToJson(result_json, status.code(), status.message());
    response = result_json.dump().c_str();

B
BossZou 已提交
1531 1532 1533 1534
    ASSIGN_RETURN_STATUS_DTO(status)
}

StatusDto::ObjectWrapper
1535
WebRequestHandler::GetSegmentInfo(const OString& collection_name, const OString& segment_name, const OString& info,
1536
                                  const OQueryParams& query_params, OString& result) {
1537 1538 1539 1540
    int64_t offset = 0;
    auto status = ParseQueryInteger(query_params, "offset", offset);
    if (!status.ok()) {
        RETURN_STATUS_DTO(status.code(), status.message().c_str());
1541 1542
    }

1543 1544 1545 1546
    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 已提交
1547 1548
    }

1549
    if (offset < 0 || page_size < 0) {
1550 1551 1552 1553
        ASSIGN_RETURN_STATUS_DTO(
            Status(SERVER_UNEXPECTED_ERROR, "Query param 'offset' or 'page_size' should equal or bigger than 0"));
    }

G
groot 已提交
1554 1555
    std::string id_str = segment_name->std_str();
    int64_t segment_id = atol(id_str.c_str());
1556
    std::string re = info->std_str();
1557
    status = Status::OK();
1558 1559 1560
    nlohmann::json json;
    // Get vectors
    if (re == "vectors") {
G
groot 已提交
1561
        status = GetSegmentVectors(collection_name->std_str(), segment_id, page_size, offset, json);
1562 1563
        // Get vector ids
    } else if (re == "ids") {
G
groot 已提交
1564
        status = GetSegmentIds(collection_name->std_str(), segment_id, page_size, offset, json);
B
BossZou 已提交
1565 1566
    }

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

1569 1570 1571
    ASSIGN_RETURN_STATUS_DTO(status)
}

G
groot 已提交
1572
/**
1573
 *
G
groot 已提交
1574
 * Vector
1575
 */
1576 1577 1578 1579 1580 1581 1582 1583
StatusDto::ObjectWrapper
WebRequestHandler::InsertEntity(const OString& collection_name, const milvus::server::web::OString& body,
                                VectorIdsDto::ObjectWrapper& ids_dto) {
    if (nullptr == body.get() || body->getSize() == 0) {
        RETURN_STATUS_DTO(BODY_FIELD_LOSS, "Request payload is required.")
    }

    auto body_json = nlohmann::json::parse(body->c_str());
G
groot 已提交
1584
    std::string partition_name = body_json["partition_tag"];
1585
    int32_t row_num = body_json["row_num"];
1586 1587

    std::unordered_map<std::string, engine::meta::hybrid::DataType> field_types;
1588
    auto status = Status::OK();
C
Cai Yudong 已提交
1589
    // auto status = req_handler_.DescribeHybridCollection(context_ptr_, collection_name->c_str(), field_types);
1590 1591 1592 1593 1594 1595

    auto entities = body_json["entity"];
    if (!entities.is_array()) {
        RETURN_STATUS_DTO(ILLEGAL_BODY, "An entity must be an array");
    }

G
groot 已提交
1596 1597
    std::unordered_map<std::string, std::vector<uint8_t>> chunk_data;

1598 1599 1600
    for (auto& entity : entities) {
        std::string field_name = entity["field_name"];
        auto field_value = entity["field_value"];
G
groot 已提交
1601 1602 1603 1604 1605 1606
        auto size = field_value.size();
        if (size != row_num) {
            RETURN_STATUS_DTO(ILLEGAL_ROWRECORD, "Field row count inconsist");
        }

        std::vector<uint8_t> temp_data;
1607
        switch (field_types.at(field_name)) {
G
groot 已提交
1608 1609 1610 1611
            case engine::meta::hybrid::DataType::INT32: {
                CopyStructuredData<int32_t>(field_value, temp_data);
                break;
            }
1612
            case engine::meta::hybrid::DataType::INT64: {
G
groot 已提交
1613 1614 1615 1616 1617
                CopyStructuredData<int64_t>(field_value, temp_data);
                break;
            }
            case engine::meta::hybrid::DataType::FLOAT: {
                CopyStructuredData<float>(field_value, temp_data);
1618 1619 1620
                break;
            }
            case engine::meta::hybrid::DataType::DOUBLE: {
G
groot 已提交
1621
                CopyStructuredData<double>(field_value, temp_data);
1622 1623
                break;
            }
1624
            case engine::meta::hybrid::DataType::VECTOR_FLOAT: {
1625
                bool bin_flag;
B
BossZou 已提交
1626
                status = IsBinaryCollection(collection_name->c_str(), bin_flag);
1627 1628 1629 1630
                if (!status.ok()) {
                    ASSIGN_RETURN_STATUS_DTO(status)
                }

C
Cai Yudong 已提交
1631 1632 1633
                // engine::VectorsData vectors;
                // CopyRecordsFromJson(field_value, vectors, bin_flag);
                // vector_datas.insert(std::make_pair(field_name, vectors));
1634 1635 1636 1637
            }
            default: {}
        }

G
groot 已提交
1638
        chunk_data.insert(std::make_pair(field_name, temp_data));
1639 1640
    }

C
Cai Yudong 已提交
1641
    status = req_handler_.Insert(context_ptr_, collection_name->c_str(), partition_name, row_num, chunk_data);
G
groot 已提交
1642 1643 1644
    if (!status.ok()) {
        RETURN_STATUS_DTO(UNEXPECTED_ERROR, "Failed to insert data");
    }
1645

G
groot 已提交
1646 1647 1648 1649 1650 1651 1652
    // return generated ids
    auto pair = chunk_data.find(engine::DEFAULT_UID_NAME);
    if (pair != chunk_data.end()) {
        int64_t count = pair->second.size() / 8;
        int64_t* pdata = reinterpret_cast<int64_t*>(pair->second.data());
        for (int64_t i = 0; i < count; ++i) {
            ids_dto->ids->pushBack(std::to_string(pdata[i]).c_str());
1653 1654 1655 1656 1657 1658
        }
    }

    ASSIGN_RETURN_STATUS_DTO(status)
}

Y
yukun 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
StatusDto::ObjectWrapper
WebRequestHandler::GetEntity(const milvus::server::web::OString& collection_name,
                             const milvus::server::web::OQueryParams& query_params,
                             milvus::server::web::OString& response) {
    auto status = Status::OK();
    try {
        auto query_ids = query_params.get("ids");
        if (query_ids == nullptr || query_ids.get() == nullptr) {
            RETURN_STATUS_DTO(QUERY_PARAM_LOSS, "Query param ids is required.");
        }

        std::vector<std::string> ids;
        StringHelpFunctions::SplitStringByDelimeter(query_ids->c_str(), ",", ids);
        std::vector<int64_t> entity_ids;
        for (auto& id : ids) {
            entity_ids.push_back(std::stol(id));
        }
1676 1677 1678 1679 1680 1681 1682

        std::vector<std::string> field_names;
        auto query_fields = query_params.get("fields");
        if (query_fields != nullptr && query_fields.get() != nullptr) {
            StringHelpFunctions::SplitStringByDelimeter(query_fields->c_str(), ",", field_names);
        }

1683
        std::vector<bool> valid_row;
Y
yukun 已提交
1684
        nlohmann::json entity_result_json;
1685
        status = GetEntityByIDs(collection_name->std_str(), entity_ids, field_names, entity_result_json);
Y
yukun 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
        if (!status.ok()) {
            response = "NULL";
            ASSIGN_RETURN_STATUS_DTO(status)
        }

        nlohmann::json json;
        AddStatusToJson(json, status.code(), status.message());
        if (entity_result_json.empty()) {
            json["entities"] = std::vector<int64_t>();
        } else {
            json["entities"] = entity_result_json;
        }
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
    }

    ASSIGN_RETURN_STATUS_DTO(status);
}

1705
StatusDto::ObjectWrapper
1706
WebRequestHandler::GetVector(const OString& collection_name, const OQueryParams& query_params, OString& response) {
B
BossZou 已提交
1707 1708
    auto status = Status::OK();
    try {
1709 1710 1711
        auto query_ids = query_params.get("ids");
        if (query_ids == nullptr || query_ids.get() == nullptr) {
            RETURN_STATUS_DTO(QUERY_PARAM_LOSS, "Query param ids is required.");
B
BossZou 已提交
1712
        }
1713

1714 1715 1716
        std::vector<std::string> ids;
        StringHelpFunctions::SplitStringByDelimeter(query_ids->c_str(), ",", ids);

B
BossZou 已提交
1717 1718
        std::vector<int64_t> vector_ids;
        for (auto& id : ids) {
1719
            vector_ids.push_back(std::stol(id));
B
BossZou 已提交
1720 1721 1722 1723 1724 1725 1726 1727
        }
        engine::VectorsData vectors;
        nlohmann::json vectors_json;
        status = GetVectorsByIDs(collection_name->std_str(), vector_ids, vectors_json);
        if (!status.ok()) {
            response = "NULL";
            ASSIGN_RETURN_STATUS_DTO(status)
        }
B
BossZou 已提交
1728

G
groot 已提交
1729 1730 1731
        FloatJson json;
        json["code"] = (int64_t)status.code();
        json["message"] = status.message();
B
BossZou 已提交
1732 1733 1734 1735 1736 1737 1738 1739
        if (vectors_json.empty()) {
            json["vectors"] = std::vector<int64_t>();
        } else {
            json["vectors"] = vectors_json;
        }
        response = json.dump().c_str();
    } catch (std::exception& e) {
        RETURN_STATUS_DTO(SERVER_UNEXPECTED_ERROR, e.what());
B
BossZou 已提交
1740 1741
    }

B
BossZou 已提交
1742
    ASSIGN_RETURN_STATUS_DTO(status);
1743 1744 1745
}

StatusDto::ObjectWrapper
1746
WebRequestHandler::VectorsOp(const OString& collection_name, const OString& payload, OString& response) {
1747 1748 1749 1750 1751 1752 1753
    auto status = Status::OK();
    std::string result_str;

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

        if (payload_json.contains("delete")) {
1754
            status = DeleteByIDs(collection_name->std_str(), payload_json["delete"], result_str);
1755
        } else if (payload_json.contains("query")) {
G
groot 已提交
1756
            status = Search(collection_name->c_str(), payload_json, result_str);
1757 1758
        } else {
            status = Status(ILLEGAL_BODY, "Unknown body");
B
BossZou 已提交
1759
        }
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    } 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());
    }

1770
    response = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1771 1772 1773 1774

    ASSIGN_RETURN_STATUS_DTO(status)
}

1775 1776 1777 1778
/**********
 *
 * System {
 */
B
BossZou 已提交
1779
StatusDto::ObjectWrapper
1780
WebRequestHandler::SystemInfo(const OString& cmd, const OQueryParams& query_params, OString& response_str) {
1781
    std::string info = cmd->std_str();
1782

1783 1784
    auto status = Status::OK();
    std::string result_str;
1785

1786 1787 1788 1789 1790 1791
    try {
        if (info == "config") {
            status = GetConfig(result_str);
        } else {
            if ("info" == info) {
                info = "get_system_info";
1792
            }
1793
            status = Cmd(info, result_str);
1794
        }
1795 1796
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1797
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1798 1799
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1800
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1801
    }
1802

1803
    response_str = status.ok() ? result_str.c_str() : "NULL";
1804

1805 1806
    ASSIGN_RETURN_STATUS_DTO(status);
}
B
BossZou 已提交
1807

1808 1809 1810 1811 1812
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.");
    }
1813 1814 1815

    Status status = Status::OK();
    std::string result_str;
1816
    try {
B
BossZou 已提交
1817 1818 1819
        fiu_do_on("WebRequestHandler.SystemOp.raise_parse_error",
                  throw nlohmann::detail::parse_error::create(0, 0, ""));
        fiu_do_on("WebRequestHandler.SystemOp.raise_type_error", throw nlohmann::detail::type_error::create(0, ""));
1820 1821 1822
        nlohmann::json j = nlohmann::json::parse(body_str->c_str());
        if (op->equals("task")) {
            if (j.contains("load")) {
B
BossZou 已提交
1823
                status = PreLoadCollection(j["load"], result_str);
1824 1825
            } else if (j.contains("flush")) {
                status = Flush(j["flush"], result_str);
1826 1827
            }
            if (j.contains("compact")) {
1828
                status = Compact(j["compact"], result_str);
1829
            }
W
Wang XiangYu 已提交
1830 1831
            //        } else if (op->equals("config")) {
            //            status = SetConfig(j, result_str);
1832 1833
        } else {
            status = Status(UNKNOWN_PATH, "Unknown path: /system/" + op->std_str());
1834 1835 1836
        }
    } catch (nlohmann::detail::parse_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1837
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1838 1839
    } catch (nlohmann::detail::type_error& e) {
        std::string emsg = "json error: code=" + std::to_string(e.id) + ", reason=" + e.what();
1840
        RETURN_STATUS_DTO(BODY_PARSE_FAIL, emsg.c_str());
1841 1842
    }

1843
    response_str = status.ok() ? result_str.c_str() : "NULL";
B
BossZou 已提交
1844 1845 1846 1847 1848 1849 1850

    ASSIGN_RETURN_STATUS_DTO(status);
}

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