DBImpl.cpp 128.4 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
2
//
3 4
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
J
jinhai 已提交
5
//
6 7 8 9 10
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.
J
jinhai 已提交
11

S
starlord 已提交
12
#include "db/DBImpl.h"
Z
Zhiru Zhu 已提交
13 14

#include <assert.h>
15
#include <fiu-local.h>
Z
Zhiru Zhu 已提交
16

Y
yukun 已提交
17
#include <knowhere/index/structured_index/StructuredIndexSort.h>
Z
Zhiru Zhu 已提交
18 19 20 21
#include <algorithm>
#include <boost/filesystem.hpp>
#include <chrono>
#include <cstring>
22
#include <functional>
Z
Zhiru Zhu 已提交
23
#include <iostream>
24
#include <limits>
25
#include <map>
26
#include <mutex>
27
#include <queue>
Z
Zhiru Zhu 已提交
28 29
#include <set>
#include <thread>
30
#include <unordered_map>
Z
Zhiru Zhu 已提交
31 32
#include <utility>

S
starlord 已提交
33
#include "Utils.h"
S
starlord 已提交
34 35
#include "cache/CpuCacheMgr.h"
#include "cache/GpuCacheMgr.h"
W
Wang XiangYu 已提交
36
#include "config/ServerConfig.h"
37
#include "db/IDGenerator.h"
G
groot 已提交
38
#include "db/merge/MergeManagerFactory.h"
S
starlord 已提交
39
#include "engine/EngineFactory.h"
40
#include "index/knowhere/knowhere/index/vector_index/helpers/BuilderSuspend.h"
41
#include "index/thirdparty/faiss/utils/distances.h"
42
#include "insert/MemManagerFactory.h"
S
starlord 已提交
43
#include "meta/MetaConsts.h"
S
starlord 已提交
44 45
#include "meta/MetaFactory.h"
#include "meta/SqliteMetaImpl.h"
G
groot 已提交
46
#include "metrics/Metrics.h"
G
groot 已提交
47
#include "scheduler/Definition.h"
S
starlord 已提交
48
#include "scheduler/SchedInst.h"
Y
Yu Kun 已提交
49
#include "scheduler/job/BuildIndexJob.h"
S
starlord 已提交
50 51
#include "scheduler/job/DeleteJob.h"
#include "scheduler/job/SearchJob.h"
52 53 54
#include "segment/SegmentReader.h"
#include "segment/SegmentWriter.h"
#include "utils/Exception.h"
S
starlord 已提交
55
#include "utils/Log.h"
G
groot 已提交
56
#include "utils/StringHelpFunctions.h"
S
starlord 已提交
57
#include "utils/TimeRecorder.h"
58
#include "wal/WalDefinations.h"
X
Xu Peng 已提交
59

60 61
#include "search/TaskInst.h"

J
jinhai 已提交
62
namespace milvus {
X
Xu Peng 已提交
63
namespace engine {
X
Xu Peng 已提交
64

G
groot 已提交
65
namespace {
G
groot 已提交
66 67
constexpr uint64_t BACKGROUND_METRIC_INTERVAL = 1;
constexpr uint64_t BACKGROUND_INDEX_INTERVAL = 1;
G
groot 已提交
68
constexpr uint64_t WAIT_BUILD_INDEX_INTERVAL = 5;
G
groot 已提交
69

70 71 72 73 74 75 76 77
constexpr const char* JSON_ROW_COUNT = "row_count";
constexpr const char* JSON_PARTITIONS = "partitions";
constexpr const char* JSON_PARTITION_TAG = "tag";
constexpr const char* JSON_SEGMENTS = "segments";
constexpr const char* JSON_SEGMENT_NAME = "name";
constexpr const char* JSON_INDEX_NAME = "index_name";
constexpr const char* JSON_DATA_SIZE = "data_size";

G
groot 已提交
78
static const Status SHUTDOWN_ERROR = Status(DB_ERROR, "Milvus server is shutdown!");
G
groot 已提交
79

S
starlord 已提交
80
}  // namespace
G
groot 已提交
81

Y
Yu Kun 已提交
82
DBImpl::DBImpl(const DBOptions& options)
83
    : options_(options), initialized_(false), merge_thread_pool_(1, 1), index_thread_pool_(1, 1) {
S
starlord 已提交
84
    meta_ptr_ = MetaFactory::Build(options.meta_, options.mode_);
Z
zhiru 已提交
85
    mem_mgr_ = MemManagerFactory::Build(meta_ptr_, options_);
G
groot 已提交
86
    merge_mgr_ptr_ = MergeManagerFactory::Build(meta_ptr_, options_);
87 88 89 90 91 92 93 94 95 96

    if (options_.wal_enable_) {
        wal::MXLogConfiguration mxlog_config;
        mxlog_config.recovery_error_ignore = options_.recovery_error_ignore_;
        // 2 buffers in the WAL
        mxlog_config.buffer_size = options_.buffer_size_ / 2;
        mxlog_config.mxlog_path = options_.mxlog_path_;
        wal_mgr_ = std::make_shared<wal::WalManager>(mxlog_config);
    }

S
starlord 已提交
97
    Start();
W
Wang XiangYu 已提交
98 99
    ConfigMgr::GetInstance().Attach("cache.cache_insert_data", this);
    ConfigMgr::GetInstance().Attach("engine.use_blas_threshold", this);
S
starlord 已提交
100 101 102
}

DBImpl::~DBImpl() {
W
Wang XiangYu 已提交
103 104
    ConfigMgr::GetInstance().Detach("engine.use_blas_threshold", this);
    ConfigMgr::GetInstance().Detach("cache.cache_insert_data", this);
S
starlord 已提交
105 106 107
    Stop();
}

S
starlord 已提交
108
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
109
// external api
S
starlord 已提交
110
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
111 112
Status
DBImpl::Start() {
113
    if (initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
114 115 116
        return Status::OK();
    }

117
    // LOG_ENGINE_TRACE_ << "DB service start";
118
    initialized_.store(true, std::memory_order_release);
S
starlord 已提交
119

G
groot 已提交
120 121 122 123 124 125 126 127 128 129
    // server may be closed unexpected, these un-merge files need to be merged when server restart
    // and soft-delete files need to be deleted when server restart
    std::set<std::string> merge_collection_ids;
    std::vector<meta::CollectionSchema> collection_schema_array;
    meta_ptr_->AllCollections(collection_schema_array);
    for (auto& schema : collection_schema_array) {
        merge_collection_ids.insert(schema.collection_id_);
    }
    StartMergeTask(merge_collection_ids, true);

130 131 132 133 134 135 136 137 138 139 140 141 142
    // wal
    if (options_.wal_enable_) {
        auto error_code = DB_ERROR;
        if (wal_mgr_ != nullptr) {
            error_code = wal_mgr_->Init(meta_ptr_);
        }
        if (error_code != WAL_SUCCESS) {
            throw Exception(error_code, "Wal init error!");
        }

        // recovery
        while (1) {
            wal::MXLogRecord record;
143
            auto error_code = wal_mgr_->GetNextEntityRecovery(record);
144 145 146 147 148 149 150 151 152 153 154
            if (error_code != WAL_SUCCESS) {
                throw Exception(error_code, "Wal recovery error!");
            }
            if (record.type == wal::MXLogType::None) {
                break;
            }
            ExecWalRecord(record);
        }

        // for distribute version, some nodes are read only
        if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
G
groot 已提交
155 156
            // background wal thread
            bg_wal_thread_ = std::thread(&DBImpl::BackgroundWalThread, this);
157 158 159 160
        }
    } else {
        // for distribute version, some nodes are read only
        if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
G
groot 已提交
161 162
            // background flush thread
            bg_flush_thread_ = std::thread(&DBImpl::BackgroundFlushThread, this);
163
        }
Z
update  
zhiru 已提交
164
    }
S
starlord 已提交
165

G
groot 已提交
166 167 168 169 170 171 172
    // for distribute version, some nodes are read only
    if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        // background build index thread
        bg_index_thread_ = std::thread(&DBImpl::BackgroundIndexThread, this);
    }

    // background metric thread
Y
yukun 已提交
173
    fiu_do_on("options_metric_enable", options_.metric_enable_ = true);
G
groot 已提交
174 175 176
    if (options_.metric_enable_) {
        bg_metric_thread_ = std::thread(&DBImpl::BackgroundMetricThread, this);
    }
G
groot 已提交
177

S
starlord 已提交
178 179 180
    return Status::OK();
}

S
starlord 已提交
181 182
Status
DBImpl::Stop() {
183
    if (!initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
184 185
        return Status::OK();
    }
186

187
    initialized_.store(false, std::memory_order_release);
S
starlord 已提交
188

189 190
    if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        if (options_.wal_enable_) {
G
groot 已提交
191 192
            // wait wal thread finish
            swn_wal_.Notify();
193 194
            bg_wal_thread_.join();
        } else {
G
groot 已提交
195
            // flush all without merge
196 197 198 199
            wal::MXLogRecord record;
            record.type = wal::MXLogType::Flush;
            ExecWalRecord(record);

G
groot 已提交
200 201 202
            // wait flush thread finish
            swn_flush_.Notify();
            bg_flush_thread_.join();
203
        }
S
starlord 已提交
204

205 206
        WaitMergeFileFinish();

G
groot 已提交
207 208 209
        swn_index_.Notify();
        bg_index_thread_.join();

210
        meta_ptr_->CleanUpShadowFiles();
S
starlord 已提交
211 212
    }

G
groot 已提交
213
    // wait metric thread exit
G
groot 已提交
214 215 216 217
    if (options_.metric_enable_) {
        swn_metric_.Notify();
        bg_metric_thread_.join();
    }
G
groot 已提交
218

219
    // LOG_ENGINE_TRACE_ << "DB service stop";
S
starlord 已提交
220
    return Status::OK();
X
Xu Peng 已提交
221 222
}

S
starlord 已提交
223 224
Status
DBImpl::DropAll() {
S
starlord 已提交
225 226 227
    return meta_ptr_->DropAll();
}

S
starlord 已提交
228
Status
229
DBImpl::CreateCollection(meta::CollectionSchema& collection_schema) {
230
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
231
        return SHUTDOWN_ERROR;
S
starlord 已提交
232 233
    }

234
    meta::CollectionSchema temp_schema = collection_schema;
B
bigbraver 已提交
235
    temp_schema.index_file_size_ *= MB;  // store as MB
236
    if (options_.wal_enable_) {
237
        temp_schema.flush_lsn_ = wal_mgr_->CreateCollection(collection_schema.collection_id_);
238 239
    }

240
    return meta_ptr_->CreateCollection(temp_schema);
241 242
}

243 244 245 246 247 248 249
Status
DBImpl::CreateHybridCollection(meta::CollectionSchema& collection_schema, meta::hybrid::FieldsSchema& fields_schema) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    meta::CollectionSchema temp_schema = collection_schema;
Y
yukun 已提交
250
    temp_schema.index_file_size_ *= MB;
251
    if (options_.wal_enable_) {
Y
yukun 已提交
252
        temp_schema.flush_lsn_ = wal_mgr_->CreateHybridCollection(collection_schema.collection_id_);
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    }

    return meta_ptr_->CreateHybridCollection(temp_schema, fields_schema);
}

Status
DBImpl::DescribeHybridCollection(meta::CollectionSchema& collection_schema,
                                 milvus::engine::meta::hybrid::FieldsSchema& fields_schema) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    auto stat = meta_ptr_->DescribeHybridCollection(collection_schema, fields_schema);
    return stat;
}

S
starlord 已提交
269
Status
270
DBImpl::DropCollection(const std::string& collection_id) {
271
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
272
        return SHUTDOWN_ERROR;
S
starlord 已提交
273 274
    }

275 276 277 278
    // dates partly delete files of the collection but currently we don't support
    LOG_ENGINE_DEBUG_ << "Prepare to delete collection " << collection_id;

    Status status;
279
    if (options_.wal_enable_) {
280
        wal_mgr_->DropCollection(collection_id);
281 282
    }

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    status = mem_mgr_->EraseMemVector(collection_id);      // not allow insert
    status = meta_ptr_->DropCollections({collection_id});  // soft delete collection
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);

    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
    std::vector<std::string> partition_id_array;
    for (auto& schema : partition_array) {
        if (options_.wal_enable_) {
            wal_mgr_->DropCollection(schema.collection_id_);
        }
        status = mem_mgr_->EraseMemVector(schema.collection_id_);
        index_failed_checker_.CleanFailedIndexFileOfCollection(schema.collection_id_);
        partition_id_array.push_back(schema.collection_id_);
    }

    status = meta_ptr_->DropCollections(partition_id_array);
    fiu_do_on("DBImpl.DropCollection.failed", status = Status(DB_ERROR, ""));
    if (!status.ok()) {
        return status;
    }

    return Status::OK();
G
groot 已提交
306 307
}

S
starlord 已提交
308
Status
309
DBImpl::DescribeCollection(meta::CollectionSchema& collection_schema) {
310
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
311
        return SHUTDOWN_ERROR;
S
starlord 已提交
312 313
    }

314
    auto stat = meta_ptr_->DescribeCollection(collection_schema);
B
bigbraver 已提交
315
    collection_schema.index_file_size_ /= MB;  // return as MB
S
starlord 已提交
316
    return stat;
317 318
}

S
starlord 已提交
319
Status
320
DBImpl::HasCollection(const std::string& collection_id, bool& has_or_not) {
321
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
322
        return SHUTDOWN_ERROR;
S
starlord 已提交
323 324
    }

G
groot 已提交
325
    return meta_ptr_->HasCollection(collection_id, has_or_not, false);
326 327
}

328
Status
G
groot 已提交
329
DBImpl::HasNativeCollection(const std::string& collection_id, bool& has_or_not) {
330 331 332 333
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
334
    return meta_ptr_->HasCollection(collection_id, has_or_not, true);
335 336
}

S
starlord 已提交
337
Status
338
DBImpl::AllCollections(std::vector<std::string>& names) {
339
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
340
        return SHUTDOWN_ERROR;
S
starlord 已提交
341 342
    }

343 344
    names.clear();

345 346
    std::vector<meta::CollectionSchema> all_collections;
    auto status = meta_ptr_->AllCollections(all_collections);
347

348 349 350
    // only return real collections, dont return partition collections
    for (auto& schema : all_collections) {
        if (schema.owner_collection_.empty()) {
351
            names.push_back(schema.collection_id_);
352 353 354 355
        }
    }

    return status;
G
groot 已提交
356 357
}

358
Status
359
DBImpl::GetCollectionInfo(const std::string& collection_id, std::string& collection_info) {
360 361 362 363 364
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // step1: get all partition ids
J
Jin Hai 已提交
365 366
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
367

J
Jin Hai 已提交
368 369
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::INDEX};
370

371 372 373
    milvus::json json_info;
    milvus::json json_partitions;
    size_t total_row_count = 0;
374

375
    auto get_info = [&](const std::string& col_id, const std::string& tag) {
G
groot 已提交
376 377
        meta::FilesHolder files_holder;
        status = meta_ptr_->FilesByType(col_id, file_types, files_holder);
378
        if (!status.ok()) {
J
Jin Hai 已提交
379
            std::string err_msg = "Failed to get collection info: " + status.ToString();
380
            LOG_ENGINE_ERROR_ << err_msg;
381 382 383
            return Status(DB_ERROR, err_msg);
        }

384 385 386 387 388
        milvus::json json_partition;
        json_partition[JSON_PARTITION_TAG] = tag;

        milvus::json json_segments;
        size_t row_count = 0;
G
groot 已提交
389
        milvus::engine::meta::SegmentsSchema& collection_files = files_holder.HoldFiles();
390
        for (auto& file : collection_files) {
391 392 393 394 395 396 397 398 399
            milvus::json json_segment;
            json_segment[JSON_SEGMENT_NAME] = file.segment_id_;
            json_segment[JSON_ROW_COUNT] = file.row_count_;
            json_segment[JSON_INDEX_NAME] = utils::GetIndexName(file.engine_type_);
            json_segment[JSON_DATA_SIZE] = (int64_t)file.file_size_;
            json_segments.push_back(json_segment);

            row_count += file.row_count_;
            total_row_count += file.row_count_;
400 401
        }

402 403 404 405 406 407 408
        json_partition[JSON_ROW_COUNT] = row_count;
        json_partition[JSON_SEGMENTS] = json_segments;

        json_partitions.push_back(json_partition);

        return Status::OK();
    };
409

410 411 412 413
    // step2: get default partition info
    status = get_info(collection_id, milvus::engine::DEFAULT_PARTITON_TAG);
    if (!status.ok()) {
        return status;
414 415
    }

416 417 418 419 420 421 422 423 424 425 426 427 428
    // step3: get partitions info
    for (auto& schema : partition_array) {
        status = get_info(schema.collection_id_, schema.partition_tag_);
        if (!status.ok()) {
            return status;
        }
    }

    json_info[JSON_ROW_COUNT] = total_row_count;
    json_info[JSON_PARTITIONS] = json_partitions;

    collection_info = json_info.dump();

429 430 431
    return Status::OK();
}

S
starlord 已提交
432
Status
G
groot 已提交
433 434
DBImpl::PreloadCollection(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
                          bool force) {
435
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
436
        return SHUTDOWN_ERROR;
S
starlord 已提交
437 438
    }

J
Jin Hai 已提交
439
    // step 1: get all collection files from parent collection
G
groot 已提交
440
    meta::FilesHolder files_holder;
G
groot 已提交
441
#if 0
G
groot 已提交
442
    auto status = meta_ptr_->FilesToSearch(collection_id, files_holder);
Y
Yu Kun 已提交
443 444 445
    if (!status.ok()) {
        return status;
    }
Y
Yu Kun 已提交
446

447
    // step 2: get files from partition collections
J
Jin Hai 已提交
448 449
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
450
    for (auto& schema : partition_array) {
G
groot 已提交
451
        status = meta_ptr_->FilesToSearch(schema.collection_id_, files_holder);
G
groot 已提交
452
    }
G
groot 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
#else
    auto status = meta_ptr_->FilesToSearch(collection_id, files_holder);
    if (!status.ok()) {
        return status;
    }

    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);

    std::set<std::string> partition_ids;
    for (auto& schema : partition_array) {
        partition_ids.insert(schema.collection_id_);
    }

    status = meta_ptr_->FilesToSearchEx(collection_id, partition_ids, files_holder);
    if (!status.ok()) {
        return status;
    }
#endif
G
groot 已提交
472

Y
Yu Kun 已提交
473 474
    int64_t size = 0;
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
Y
Yu Kun 已提交
475 476
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t available_size = cache_total - cache_usage;
Y
Yu Kun 已提交
477

478
    // step 3: load file one by one
G
groot 已提交
479
    milvus::engine::meta::SegmentsSchema& files_array = files_holder.HoldFiles();
480 481
    LOG_ENGINE_DEBUG_ << "Begin pre-load collection:" + collection_id + ", totally " << files_array.size()
                      << " files need to be pre-loaded";
J
Jin Hai 已提交
482
    TimeRecorderAuto rc("Pre-load collection:" + collection_id);
G
groot 已提交
483
    for (auto& file : files_array) {
G
groot 已提交
484 485 486 487 488 489
        // client break the connection, no need to continue
        if (context && context->IsConnectionBroken()) {
            LOG_ENGINE_DEBUG_ << "Client connection broken, stop load collection";
            break;
        }

490
        EngineType engine_type;
J
Jin Hai 已提交
491 492 493
        if (file.file_type_ == meta::SegmentSchema::FILE_TYPE::RAW ||
            file.file_type_ == meta::SegmentSchema::FILE_TYPE::TO_INDEX ||
            file.file_type_ == meta::SegmentSchema::FILE_TYPE::BACKUP) {
494 495
            engine_type =
                utils::IsBinaryMetricType(file.metric_type_) ? EngineType::FAISS_BIN_IDMAP : EngineType::FAISS_IDMAP;
496 497 498
        } else {
            engine_type = (EngineType)file.engine_type_;
        }
499 500 501 502

        auto json = milvus::json::parse(file.index_params_);
        ExecutionEnginePtr engine =
            EngineFactory::Build(file.dimension_, file.location_, engine_type, (MetricType)file.metric_type_, json);
503
        fiu_do_on("DBImpl.PreloadCollection.null_engine", engine = nullptr);
G
groot 已提交
504
        if (engine == nullptr) {
505
            LOG_ENGINE_ERROR_ << "Invalid engine type";
G
groot 已提交
506 507
            return Status(DB_ERROR, "Invalid engine type");
        }
Y
Yu Kun 已提交
508

509
        fiu_do_on("DBImpl.PreloadCollection.exceed_cache", size = available_size + 1);
510 511

        try {
512
            fiu_do_on("DBImpl.PreloadCollection.engine_throw_exception", throw std::exception());
513 514
            std::string msg = "Pre-loaded file: " + file.file_id_ + " size: " + std::to_string(file.file_size_);
            TimeRecorderAuto rc_1(msg);
515 516 517 518
            status = engine->Load(true);
            if (!status.ok()) {
                return status;
            }
519 520

            size += engine->Size();
G
groot 已提交
521
            if (!force && size > available_size) {
522
                LOG_ENGINE_DEBUG_ << "Pre-load cancelled since cache is almost full";
523
                return Status(SERVER_CACHE_FULL, "Cache is full");
Y
Yu Kun 已提交
524
            }
525
        } catch (std::exception& ex) {
J
Jin Hai 已提交
526
            std::string msg = "Pre-load collection encounter exception: " + std::string(ex.what());
527
            LOG_ENGINE_ERROR_ << msg;
528
            return Status(DB_ERROR, msg);
Y
Yu Kun 已提交
529 530
        }
    }
G
groot 已提交
531

Y
Yu Kun 已提交
532
    return Status::OK();
Y
Yu Kun 已提交
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
Status
DBImpl::ReLoadSegmentsDeletedDocs(const std::string& collection_id, const std::vector<int64_t>& segment_ids) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    meta::FilesHolder files_holder;
    std::vector<size_t> file_ids;
    for (auto& id : segment_ids) {
        file_ids.emplace_back(id);
    }

    auto status = meta_ptr_->FilesByID(file_ids, files_holder);
    if (!status.ok()) {
        std::string err_msg = "Failed get file holders by ids: " + status.ToString();
        LOG_ENGINE_ERROR_ << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    milvus::engine::meta::SegmentsSchema hold_files = files_holder.HoldFiles();

    for (auto& file : hold_files) {
        std::string segment_dir;
        utils::GetParentPath(file.location_, segment_dir);

        auto data_obj_ptr = cache::CpuCacheMgr::GetInstance()->GetIndex(file.location_);
        auto index = std::static_pointer_cast<knowhere::VecIndex>(data_obj_ptr);
        if (nullptr == index) {
            LOG_ENGINE_WARNING_ << "Index " << file.location_ << " not found";
            continue;
        }

        segment::SegmentReader segment_reader(segment_dir);

        segment::DeletedDocsPtr delete_docs = std::make_shared<segment::DeletedDocs>();
        segment_reader.LoadDeletedDocs(delete_docs);
        auto& docs_offsets = delete_docs->GetDeletedDocs();

        faiss::ConcurrentBitsetPtr blacklist = index->GetBlacklist();
        if (nullptr == blacklist) {
            LOG_ENGINE_WARNING_ << "Index " << file.location_ << " is empty";
            faiss::ConcurrentBitsetPtr concurrent_bitset_ptr =
                std::make_shared<faiss::ConcurrentBitset>(index->Count());
            index->SetBlacklist(concurrent_bitset_ptr);
            blacklist = concurrent_bitset_ptr;
        }

        for (auto& i : docs_offsets) {
            if (!blacklist->test(i)) {
                blacklist->set(i);
            }
        }
    }

    return Status::OK();
}

S
starlord 已提交
592
Status
593
DBImpl::UpdateCollectionFlag(const std::string& collection_id, int64_t flag) {
594
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
595
        return SHUTDOWN_ERROR;
S
starlord 已提交
596 597
    }

598
    return meta_ptr_->UpdateCollectionFlag(collection_id, flag);
S
starlord 已提交
599 600
}

S
starlord 已提交
601
Status
602
DBImpl::GetCollectionRowCount(const std::string& collection_id, uint64_t& row_count) {
603
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
604 605 606
        return SHUTDOWN_ERROR;
    }

607
    return GetCollectionRowCountRecursively(collection_id, row_count);
G
groot 已提交
608 609 610
}

Status
J
Jin Hai 已提交
611
DBImpl::CreatePartition(const std::string& collection_id, const std::string& partition_name,
G
groot 已提交
612
                        const std::string& partition_tag) {
613
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
614 615 616
        return SHUTDOWN_ERROR;
    }

617
    uint64_t lsn = 0;
G
groot 已提交
618 619 620 621 622
    if (options_.wal_enable_) {
        lsn = wal_mgr_->CreatePartition(collection_id, partition_tag);
    } else {
        meta_ptr_->GetCollectionFlushLSN(collection_id, lsn);
    }
J
Jin Hai 已提交
623
    return meta_ptr_->CreatePartition(collection_id, partition_name, partition_tag, lsn);
G
groot 已提交
624 625
}

G
groot 已提交
626 627 628 629 630 631 632 633 634
Status
DBImpl::HasPartition(const std::string& collection_id, const std::string& tag, bool& has_or_not) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // trim side-blank of tag, only compare valid characters
    // for example: " ab cd " is treated as "ab cd"
    std::string valid_tag = tag;
635
    StringHelpFunctions::TrimStringBlank(valid_tag);
G
groot 已提交
636 637 638 639 640 641 642 643 644

    if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
        has_or_not = true;
        return Status::OK();
    }

    return meta_ptr_->HasPartition(collection_id, valid_tag, has_or_not);
}

G
groot 已提交
645 646
Status
DBImpl::DropPartition(const std::string& partition_name) {
647
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
648
        return SHUTDOWN_ERROR;
S
starlord 已提交
649 650
    }

651
    mem_mgr_->EraseMemVector(partition_name);                // not allow insert
J
Jin Hai 已提交
652
    auto status = meta_ptr_->DropPartition(partition_name);  // soft delete collection
653
    if (!status.ok()) {
654
        LOG_ENGINE_ERROR_ << status.message();
655 656
        return status;
    }
G
groot 已提交
657

J
Jin Hai 已提交
658
    // scheduler will determine when to delete collection files
G
groot 已提交
659 660 661 662 663 664
    auto nres = scheduler::ResMgrInst::GetInstance()->GetNumOfComputeResource();
    scheduler::DeleteJobPtr job = std::make_shared<scheduler::DeleteJob>(partition_name, meta_ptr_, nres);
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitAndDelete();

    return Status::OK();
G
groot 已提交
665 666
}

S
starlord 已提交
667
Status
J
Jin Hai 已提交
668
DBImpl::DropPartitionByTag(const std::string& collection_id, const std::string& partition_tag) {
669
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
670 671 672 673
        return SHUTDOWN_ERROR;
    }

    std::string partition_name;
J
Jin Hai 已提交
674
    auto status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
675
    if (!status.ok()) {
676
        LOG_ENGINE_ERROR_ << status.message();
677 678 679
        return status;
    }

G
groot 已提交
680 681 682 683
    if (options_.wal_enable_) {
        wal_mgr_->DropPartition(collection_id, partition_tag);
    }

G
groot 已提交
684 685 686 687
    return DropPartition(partition_name);
}

Status
J
Jin Hai 已提交
688
DBImpl::ShowPartitions(const std::string& collection_id, std::vector<meta::CollectionSchema>& partition_schema_array) {
689
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
690 691 692
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
693
    return meta_ptr_->ShowPartitions(collection_id, partition_schema_array);
G
groot 已提交
694 695 696
}

Status
J
Jin Hai 已提交
697
DBImpl::InsertVectors(const std::string& collection_id, const std::string& partition_tag, VectorsData& vectors) {
698
    //    LOG_ENGINE_DEBUG_ << "Insert " << n << " vectors to cache";
699
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
700
        return SHUTDOWN_ERROR;
S
starlord 已提交
701
    }
Y
yu yunfeng 已提交
702

J
Jin Hai 已提交
703
    // insert vectors into target collection
704 705
    // (zhiru): generate ids
    if (vectors.id_array_.empty()) {
J
Jin Hai 已提交
706 707 708
        SafeIDGenerator& id_generator = SafeIDGenerator::GetInstance();
        Status status = id_generator.GetNextIDNumbers(vectors.vector_count_, vectors.id_array_);
        if (!status.ok()) {
709
            LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] Get next id number fail: %s", "insert", 0, status.message().c_str());
J
Jin Hai 已提交
710 711
            return status;
        }
712 713
    }

714
    Status status;
715
    if (options_.wal_enable_) {
716 717
        std::string target_collection_name;
        status = GetPartitionByTag(collection_id, partition_tag, target_collection_name);
G
groot 已提交
718
        if (!status.ok()) {
719
            LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] Get partition fail: %s", "insert", 0, status.message().c_str());
G
groot 已提交
720 721
            return status;
        }
722 723

        if (!vectors.float_data_.empty()) {
J
Jin Hai 已提交
724
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.float_data_);
725
        } else if (!vectors.binary_data_.empty()) {
J
Jin Hai 已提交
726
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.binary_data_);
727
        }
G
groot 已提交
728
        swn_wal_.Notify();
729 730 731
    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
J
Jin Hai 已提交
732
        record.collection_id = collection_id;
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        record.partition_tag = partition_tag;
        record.ids = vectors.id_array_.data();
        record.length = vectors.vector_count_;
        if (vectors.binary_data_.empty()) {
            record.type = wal::MXLogType::InsertVector;
            record.data = vectors.float_data_.data();
            record.data_size = vectors.float_data_.size() * sizeof(float);
        } else {
            record.type = wal::MXLogType::InsertBinary;
            record.ids = vectors.id_array_.data();
            record.length = vectors.vector_count_;
            record.data = vectors.binary_data_.data();
            record.data_size = vectors.binary_data_.size() * sizeof(uint8_t);
        }

        status = ExecWalRecord(record);
G
groot 已提交
749 750
    }

751 752 753
    return status;
}

754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
// template <typename T>
// Status
// ConstructAttr(const uint8_t* record, int64_t row_num, const std::string& field_name,
//              std::unordered_map<std::string, std::vector<uint8_t>>& attr_datas,
//              std::unordered_map<std::string, uint64_t>& attr_nbytes,
//              std::unordered_map<std::string, uint64_t>& attr_data_size) {
//    std::vector<uint8_t> data;
//    data.resize(row_num * sizeof(int8_t));
//
//    std::vector<int64_t> attr_value(row_num, 0);
//    memcpy(attr_value.data(), record, row_num * sizeof(int64_t));
//
//    std::vector<T> raw_value(row_num, 0);
//    for (int64_t i = 0; i < row_num; ++i) {
//        raw_value[i] = attr_value[i];
//    }
//
//    memcpy(data.data(), raw_value.data(), row_num * sizeof(T));
//    attr_datas.insert(std::make_pair(field_name, data));
//
//    attr_nbytes.insert(std::make_pair(field_name, sizeof(T)));
//    attr_data_size.insert(std::make_pair(field_name, row_num * sizeof(T)));
//}

778
Status
779
CopyToAttr(const std::vector<uint8_t>& record, int64_t row_num, const std::vector<std::string>& field_names,
Y
yukun 已提交
780 781 782 783
           std::unordered_map<std::string, meta::hybrid::DataType>& attr_types,
           std::unordered_map<std::string, std::vector<uint8_t>>& attr_datas,
           std::unordered_map<std::string, uint64_t>& attr_nbytes,
           std::unordered_map<std::string, uint64_t>& attr_data_size) {
784
    int64_t offset = 0;
Y
yukun 已提交
785 786
    for (auto name : field_names) {
        switch (attr_types.at(name)) {
787
            case meta::hybrid::DataType::INT8: {
788 789
                //                ConstructAttr<int8_t>(record, row_num, name, attr_datas, attr_nbytes, attr_data_size);
                //                offset += row_num * sizeof(int64_t);
790
                std::vector<uint8_t> data;
Y
yukun 已提交
791
                data.resize(row_num * sizeof(int8_t));
792

793 794
                std::vector<int32_t> attr_value(row_num, 0);
                memcpy(attr_value.data(), record.data() + offset, row_num * sizeof(int32_t));
795

Y
yukun 已提交
796 797
                std::vector<int8_t> raw_value(row_num, 0);
                for (uint64_t i = 0; i < row_num; ++i) {
798 799 800
                    raw_value[i] = attr_value[i];
                }

Y
yukun 已提交
801 802
                memcpy(data.data(), raw_value.data(), row_num * sizeof(int8_t));
                attr_datas.insert(std::make_pair(name, data));
803

Y
yukun 已提交
804 805
                attr_nbytes.insert(std::make_pair(name, sizeof(int8_t)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(int8_t)));
806
                offset += row_num * sizeof(int32_t);
807 808 809 810
                break;
            }
            case meta::hybrid::DataType::INT16: {
                std::vector<uint8_t> data;
Y
yukun 已提交
811
                data.resize(row_num * sizeof(int16_t));
812

813 814
                std::vector<int32_t> attr_value(row_num, 0);
                memcpy(attr_value.data(), record.data() + offset, row_num * sizeof(int32_t));
815

Y
yukun 已提交
816 817
                std::vector<int16_t> raw_value(row_num, 0);
                for (uint64_t i = 0; i < row_num; ++i) {
818 819 820
                    raw_value[i] = attr_value[i];
                }

Y
yukun 已提交
821 822
                memcpy(data.data(), raw_value.data(), row_num * sizeof(int16_t));
                attr_datas.insert(std::make_pair(name, data));
823

Y
yukun 已提交
824 825
                attr_nbytes.insert(std::make_pair(name, sizeof(int16_t)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(int16_t)));
826
                offset += row_num * sizeof(int32_t);
827 828 829 830
                break;
            }
            case meta::hybrid::DataType::INT32: {
                std::vector<uint8_t> data;
Y
yukun 已提交
831
                data.resize(row_num * sizeof(int32_t));
832

833 834
                std::vector<int32_t> attr_value(row_num, 0);
                memcpy(attr_value.data(), record.data() + offset, row_num * sizeof(int32_t));
835

836
                memcpy(data.data(), attr_value.data(), row_num * sizeof(int32_t));
Y
yukun 已提交
837
                attr_datas.insert(std::make_pair(name, data));
838

Y
yukun 已提交
839 840
                attr_nbytes.insert(std::make_pair(name, sizeof(int32_t)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(int32_t)));
841
                offset += row_num * sizeof(int32_t);
842 843 844 845
                break;
            }
            case meta::hybrid::DataType::INT64: {
                std::vector<uint8_t> data;
Y
yukun 已提交
846 847 848 849 850 851
                data.resize(row_num * sizeof(int64_t));
                memcpy(data.data(), record.data() + offset, row_num * sizeof(int64_t));
                attr_datas.insert(std::make_pair(name, data));

                std::vector<int64_t> test_data(row_num);
                memcpy(test_data.data(), record.data(), row_num * sizeof(int64_t));
852

Y
yukun 已提交
853 854 855
                attr_nbytes.insert(std::make_pair(name, sizeof(int64_t)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(int64_t)));
                offset += row_num * sizeof(int64_t);
856 857 858 859
                break;
            }
            case meta::hybrid::DataType::FLOAT: {
                std::vector<uint8_t> data;
Y
yukun 已提交
860
                data.resize(row_num * sizeof(float));
861

862 863
                std::vector<float> attr_value(row_num, 0);
                memcpy(attr_value.data(), record.data() + offset, row_num * sizeof(float));
864

865
                memcpy(data.data(), attr_value.data(), row_num * sizeof(float));
Y
yukun 已提交
866
                attr_datas.insert(std::make_pair(name, data));
867

Y
yukun 已提交
868 869
                attr_nbytes.insert(std::make_pair(name, sizeof(float)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(float)));
870
                offset += row_num * sizeof(float);
871 872 873 874
                break;
            }
            case meta::hybrid::DataType::DOUBLE: {
                std::vector<uint8_t> data;
Y
yukun 已提交
875 876 877
                data.resize(row_num * sizeof(double));
                memcpy(data.data(), record.data() + offset, row_num * sizeof(double));
                attr_datas.insert(std::make_pair(name, data));
878

Y
yukun 已提交
879 880 881
                attr_nbytes.insert(std::make_pair(name, sizeof(double)));
                attr_data_size.insert(std::make_pair(name, row_num * sizeof(double)));
                offset += row_num * sizeof(double);
882 883
                break;
            }
884 885
            default:
                break;
886 887
        }
    }
Y
yukun 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    return Status::OK();
}

Status
DBImpl::InsertEntities(const std::string& collection_id, const std::string& partition_tag,
                       const std::vector<std::string>& field_names, Entity& entity,
                       std::unordered_map<std::string, meta::hybrid::DataType>& attr_types) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // Generate id
    if (entity.id_array_.empty()) {
        SafeIDGenerator& id_generator = SafeIDGenerator::GetInstance();
        Status status = id_generator.GetNextIDNumbers(entity.entity_count_, entity.id_array_);
        if (!status.ok()) {
            return status;
        }
    }

    Status status;
    std::unordered_map<std::string, std::vector<uint8_t>> attr_data;
    std::unordered_map<std::string, uint64_t> attr_nbytes;
    std::unordered_map<std::string, uint64_t> attr_data_size;
    status = CopyToAttr(entity.attr_value_, entity.entity_count_, field_names, attr_types, attr_data, attr_nbytes,
                        attr_data_size);
    if (!status.ok()) {
        return status;
    }

918
#if 0
Y
yukun 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    wal::MXLogRecord record;
    record.lsn = 0;
    record.collection_id = collection_id;
    record.partition_tag = partition_tag;
    record.ids = entity.id_array_.data();
    record.length = entity.entity_count_;

    auto vector_it = entity.vector_data_.begin();
    if (vector_it->second.binary_data_.empty()) {
        record.type = wal::MXLogType::Entity;
        record.data = vector_it->second.float_data_.data();
        record.data_size = vector_it->second.float_data_.size() * sizeof(float);
        record.attr_data = attr_data;
        record.attr_nbytes = attr_nbytes;
        record.attr_data_size = attr_data_size;
    } else {
        //        record.type = wal::MXLogType::InsertBinary;
        //        record.data = entities.vector_data_[0].binary_data_.data();
        //        record.length = entities.vector_data_[0].binary_data_.size() * sizeof(uint8_t);
    }
939 940

    status = ExecWalRecord(record);
941
#endif
Y
yukun 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

    if (options_.wal_enable_) {
        std::string target_collection_name;
        status = GetPartitionByTag(collection_id, partition_tag, target_collection_name);
        if (!status.ok()) {
            LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] Get partition fail: %s", "insert", 0, status.message().c_str());
            return status;
        }

        auto vector_it = entity.vector_data_.begin();
        if (!vector_it->second.binary_data_.empty()) {
            wal_mgr_->InsertEntities(collection_id, partition_tag, entity.id_array_, vector_it->second.binary_data_,
                                     attr_nbytes, attr_data);
        } else if (!vector_it->second.float_data_.empty()) {
            wal_mgr_->InsertEntities(collection_id, partition_tag, entity.id_array_, vector_it->second.float_data_,
                                     attr_nbytes, attr_data);
        }
        swn_wal_.Notify();
    } else {
        // insert entities: collection_name is field id
        wal::MXLogRecord record;
        record.lsn = 0;
        record.collection_id = collection_id;
        record.partition_tag = partition_tag;
        record.ids = entity.id_array_.data();
        record.length = entity.entity_count_;
968 969 970
        record.attr_data = attr_data;
        record.attr_nbytes = attr_nbytes;
        record.attr_data_size = attr_data_size;
Y
yukun 已提交
971 972 973

        auto vector_it = entity.vector_data_.begin();
        if (vector_it->second.binary_data_.empty()) {
974
            record.type = wal::MXLogType::InsertVector;
Y
yukun 已提交
975 976 977
            record.data = vector_it->second.float_data_.data();
            record.data_size = vector_it->second.float_data_.size() * sizeof(float);
        } else {
978 979 980
            record.type = wal::MXLogType::InsertBinary;
            record.data = vector_it->second.binary_data_.data();
            record.data_size = vector_it->second.binary_data_.size() * sizeof(uint8_t);
Y
yukun 已提交
981 982 983 984
        }

        status = ExecWalRecord(record);
    }
985 986 987
    return status;
}

988
Status
989
DBImpl::DeleteEntities(const std::string& collection_id, milvus::engine::IDNumbers entity_ids) {
990 991 992 993 994 995
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    if (options_.wal_enable_) {
996
        wal_mgr_->DeleteById(collection_id, entity_ids);
G
groot 已提交
997
        swn_wal_.Notify();
998 999 1000 1001
    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
        record.type = wal::MXLogType::Delete;
J
Jin Hai 已提交
1002
        record.collection_id = collection_id;
1003 1004
        record.ids = entity_ids.data();
        record.length = entity_ids.size();
1005 1006 1007 1008 1009 1010 1011 1012

        status = ExecWalRecord(record);
    }

    return status;
}

Status
J
Jin Hai 已提交
1013
DBImpl::Flush(const std::string& collection_id) {
1014 1015 1016 1017 1018
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
1019 1020
    bool has_collection;
    status = HasCollection(collection_id, has_collection);
1021 1022 1023
    if (!status.ok()) {
        return status;
    }
1024
    if (!has_collection) {
1025
        LOG_ENGINE_ERROR_ << "Collection to flush does not exist: " << collection_id;
J
Jin Hai 已提交
1026
        return Status(DB_NOT_FOUND, "Collection to flush does not exist");
1027 1028
    }

1029
    LOG_ENGINE_DEBUG_ << "Begin flush collection: " << collection_id;
1030 1031

    if (options_.wal_enable_) {
1032
        LOG_ENGINE_DEBUG_ << "WAL flush";
J
Jin Hai 已提交
1033
        auto lsn = wal_mgr_->Flush(collection_id);
1034
        if (lsn != 0) {
G
groot 已提交
1035 1036
            swn_wal_.Notify();
            flush_req_swn_.Wait();
G
groot 已提交
1037 1038 1039 1040
        } else {
            // no collection flushed, call merge task to cleanup files
            std::set<std::string> merge_collection_ids;
            StartMergeTask(merge_collection_ids);
1041 1042
        }
    } else {
1043
        LOG_ENGINE_DEBUG_ << "MemTable flush";
G
groot 已提交
1044
        InternalFlush(collection_id);
1045 1046
    }

1047
    LOG_ENGINE_DEBUG_ << "End flush collection: " << collection_id;
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

    return status;
}

Status
DBImpl::Flush() {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

1058
    LOG_ENGINE_DEBUG_ << "Begin flush all collections";
1059 1060

    Status status;
Y
yukun 已提交
1061
    fiu_do_on("options_wal_enable_false", options_.wal_enable_ = false);
1062
    if (options_.wal_enable_) {
1063
        LOG_ENGINE_DEBUG_ << "WAL flush";
1064 1065
        auto lsn = wal_mgr_->Flush();
        if (lsn != 0) {
G
groot 已提交
1066 1067
            swn_wal_.Notify();
            flush_req_swn_.Wait();
G
groot 已提交
1068 1069 1070 1071
        } else {
            // no collection flushed, call merge task to cleanup files
            std::set<std::string> merge_collection_ids;
            StartMergeTask(merge_collection_ids);
1072 1073
        }
    } else {
1074
        LOG_ENGINE_DEBUG_ << "MemTable flush";
G
groot 已提交
1075
        InternalFlush();
1076 1077
    }

1078
    LOG_ENGINE_DEBUG_ << "End flush all collections";
1079 1080 1081 1082 1083

    return status;
}

Status
G
groot 已提交
1084
DBImpl::Compact(const std::shared_ptr<server::Context>& context, const std::string& collection_id, double threshold) {
1085 1086 1087 1088
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

1089 1090 1091
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
1092 1093
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
1094
            LOG_ENGINE_ERROR_ << "Collection to compact does not exist: " << collection_id;
J
Jin Hai 已提交
1095
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
1096 1097 1098 1099
        } else {
            return status;
        }
    } else {
1100
        if (!collection_schema.owner_collection_.empty()) {
1101
            LOG_ENGINE_ERROR_ << "Collection to compact does not exist: " << collection_id;
J
Jin Hai 已提交
1102
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
1103 1104 1105
        }
    }

1106
    LOG_ENGINE_DEBUG_ << "Before compacting, wait for build index thread to finish...";
1107

G
groot 已提交
1108 1109 1110
    std::vector<meta::CollectionSchema> collection_array;
    status = meta_ptr_->ShowPartitions(collection_id, collection_array);
    collection_array.push_back(collection_schema);
1111

Z
update  
Zhiru Zhu 已提交
1112
    const std::lock_guard<std::mutex> index_lock(build_index_mutex_);
Z
Zhiru Zhu 已提交
1113
    const std::lock_guard<std::mutex> merge_lock(flush_merge_compact_mutex_);
Z
Zhiru Zhu 已提交
1114

1115
    LOG_ENGINE_DEBUG_ << "Compacting collection: " << collection_id;
Z
Zhiru Zhu 已提交
1116

1117
    // Get files to compact from meta.
J
Jin Hai 已提交
1118 1119
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
G
groot 已提交
1120
    meta::FilesHolder files_holder;
G
groot 已提交
1121
    status = meta_ptr_->FilesByTypeEx(collection_array, file_types, files_holder);
1122 1123
    if (!status.ok()) {
        std::string err_msg = "Failed to get files to compact: " + status.message();
1124
        LOG_ENGINE_ERROR_ << err_msg;
1125 1126 1127
        return Status(DB_ERROR, err_msg);
    }

G
groot 已提交
1128
    LOG_ENGINE_DEBUG_ << "Found " << files_holder.HoldFiles().size() << " segment to compact";
Z
Zhiru Zhu 已提交
1129 1130

    Status compact_status;
G
groot 已提交
1131 1132
    // attention: here is a copy, not reference, since files_holder.UnmarkFile will change the array internal
    milvus::engine::meta::SegmentsSchema files_to_compact = files_holder.HoldFiles();
Z
Zhiru Zhu 已提交
1133
    for (auto iter = files_to_compact.begin(); iter != files_to_compact.end();) {
G
groot 已提交
1134 1135 1136 1137 1138 1139
        // client break the connection, no need to continue
        if (context && context->IsConnectionBroken()) {
            LOG_ENGINE_DEBUG_ << "Client connection broken, stop compact operation";
            break;
        }

J
Jin Hai 已提交
1140
        meta::SegmentSchema file = *iter;
G
groot 已提交
1141 1142
        iter = files_to_compact.erase(iter);

Z
Zhiru Zhu 已提交
1143 1144 1145
        // Check if the segment needs compacting
        std::string segment_dir;
        utils::GetParentPath(file.location_, segment_dir);
1146

Z
Zhiru Zhu 已提交
1147
        segment::SegmentReader segment_reader(segment_dir);
Z
Zhiru Zhu 已提交
1148 1149
        size_t deleted_docs_size;
        status = segment_reader.ReadDeletedDocsSize(deleted_docs_size);
Z
Zhiru Zhu 已提交
1150
        if (!status.ok()) {
G
groot 已提交
1151
            files_holder.UnmarkFile(file);
G
groot 已提交
1152
            continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
1153 1154
        }

J
Jin Hai 已提交
1155
        meta::SegmentsSchema files_to_update;
Z
Zhiru Zhu 已提交
1156
        if (deleted_docs_size != 0) {
G
groot 已提交
1157
            compact_status = CompactFile(file, threshold, files_to_update);
Z
Zhiru Zhu 已提交
1158 1159

            if (!compact_status.ok()) {
1160 1161
                LOG_ENGINE_ERROR_ << "Compact failed for segment " << file.segment_id_ << ": "
                                  << compact_status.message();
G
groot 已提交
1162
                files_holder.UnmarkFile(file);
G
groot 已提交
1163
                continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
1164 1165
            }
        } else {
G
groot 已提交
1166
            files_holder.UnmarkFile(file);
1167
            LOG_ENGINE_DEBUG_ << "Segment " << file.segment_id_ << " has no deleted data. No need to compact";
G
groot 已提交
1168
            continue;  // skip this file and try compact next one
1169
        }
Z
Zhiru Zhu 已提交
1170

1171
        LOG_ENGINE_DEBUG_ << "Updating meta after compaction...";
1172
        status = meta_ptr_->UpdateCollectionFiles(files_to_update);
G
groot 已提交
1173
        files_holder.UnmarkFile(file);
G
groot 已提交
1174 1175 1176 1177
        if (!status.ok()) {
            compact_status = status;
            break;  // meta error, could not go on
        }
Z
Zhiru Zhu 已提交
1178 1179
    }

G
groot 已提交
1180
    if (compact_status.ok()) {
1181
        LOG_ENGINE_DEBUG_ << "Finished compacting collection: " << collection_id;
G
groot 已提交
1182
    }
1183

G
groot 已提交
1184
    return compact_status;
1185 1186 1187
}

Status
G
groot 已提交
1188 1189
DBImpl::CompactFile(const meta::SegmentSchema& file, double threshold, meta::SegmentsSchema& files_to_update) {
    LOG_ENGINE_DEBUG_ << "Compacting segment " << file.segment_id_ << " for collection: " << file.collection_id_;
1190

G
groot 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    std::string segment_dir_to_merge;
    utils::GetParentPath(file.location_, segment_dir_to_merge);

    // no need to compact if deleted vectors are too few(less than threashold)
    if (file.row_count_ > 0 && threshold > 0.0) {
        segment::SegmentReader segment_reader_to_merge(segment_dir_to_merge);
        segment::DeletedDocsPtr deleted_docs_ptr;
        auto status = segment_reader_to_merge.LoadDeletedDocs(deleted_docs_ptr);
        if (status.ok()) {
            auto delete_items = deleted_docs_ptr->GetDeletedDocs();
G
groot 已提交
1201
            double delete_rate = (double)delete_items.size() / (double)(delete_items.size() + file.row_count_);
G
groot 已提交
1202 1203 1204 1205 1206 1207 1208 1209
            if (delete_rate < threshold) {
                LOG_ENGINE_DEBUG_ << "Delete rate less than " << threshold << ", no need to compact for"
                                  << segment_dir_to_merge;
                return Status::OK();
            }
        }
    }

J
Jin Hai 已提交
1210 1211
    // Create new collection file
    meta::SegmentSchema compacted_file;
G
groot 已提交
1212
    compacted_file.collection_id_ = file.collection_id_;
J
Jin Hai 已提交
1213
    compacted_file.file_type_ = meta::SegmentSchema::NEW_MERGE;  // TODO: use NEW_MERGE for now
G
groot 已提交
1214
    auto status = meta_ptr_->CreateCollectionFile(compacted_file);
1215 1216

    if (!status.ok()) {
1217
        LOG_ENGINE_ERROR_ << "Failed to create collection file: " << status.message();
1218 1219 1220
        return status;
    }

J
Jin Hai 已提交
1221
    // Compact (merge) file to the newly created collection file
1222 1223 1224 1225
    std::string new_segment_dir;
    utils::GetParentPath(compacted_file.location_, new_segment_dir);
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);

1226
    LOG_ENGINE_DEBUG_ << "Compacting begin...";
1227 1228 1229
    segment_writer_ptr->Merge(segment_dir_to_merge, compacted_file.file_id_);

    // Serialize
1230
    LOG_ENGINE_DEBUG_ << "Serializing compacted segment...";
1231 1232
    status = segment_writer_ptr->Serialize();
    if (!status.ok()) {
1233
        LOG_ENGINE_ERROR_ << "Failed to serialize compacted segment: " << status.message();
J
Jin Hai 已提交
1234
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
1235
        auto mark_status = meta_ptr_->UpdateCollectionFile(compacted_file);
1236
        if (mark_status.ok()) {
1237
            LOG_ENGINE_DEBUG_ << "Mark file: " << compacted_file.file_id_ << " to to_delete";
1238
        }
G
groot 已提交
1239

1240 1241 1242
        return status;
    }

G
groot 已提交
1243
    // Update compacted file state, if origin file is backup or to_index, set compacted file to to_index
1244 1245 1246 1247 1248 1249
    compacted_file.file_size_ = segment_writer_ptr->Size();
    compacted_file.row_count_ = segment_writer_ptr->VectorCount();
    if ((file.file_type_ == (int32_t)meta::SegmentSchema::BACKUP ||
         file.file_type_ == (int32_t)meta::SegmentSchema::TO_INDEX) &&
        (compacted_file.row_count_ > meta::BUILD_INDEX_THRESHOLD)) {
        compacted_file.file_type_ = meta::SegmentSchema::TO_INDEX;
1250
    } else {
J
Jin Hai 已提交
1251
        compacted_file.file_type_ = meta::SegmentSchema::RAW;
1252 1253 1254
    }

    if (compacted_file.row_count_ == 0) {
1255
        LOG_ENGINE_DEBUG_ << "Compacted segment is empty. Mark it as TO_DELETE";
J
Jin Hai 已提交
1256
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
1257 1258
    }

Z
Zhiru Zhu 已提交
1259
    files_to_update.emplace_back(compacted_file);
Z
Zhiru Zhu 已提交
1260

Z
Zhiru Zhu 已提交
1261 1262
    // Set all files in segment to TO_DELETE
    auto& segment_id = file.segment_id_;
G
groot 已提交
1263 1264
    meta::FilesHolder files_holder;
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, files_holder);
Z
Zhiru Zhu 已提交
1265 1266 1267
    if (!status.ok()) {
        return status;
    }
G
groot 已提交
1268 1269

    milvus::engine::meta::SegmentsSchema& segment_files = files_holder.HoldFiles();
Z
Zhiru Zhu 已提交
1270
    for (auto& f : segment_files) {
J
Jin Hai 已提交
1271
        f.file_type_ = meta::SegmentSchema::FILE_TYPE::TO_DELETE;
Z
Zhiru Zhu 已提交
1272 1273
        files_to_update.emplace_back(f);
    }
G
groot 已提交
1274
    files_holder.ReleaseFiles();
1275

1276 1277 1278
    LOG_ENGINE_DEBUG_ << "Compacted segment " << compacted_file.segment_id_ << " from "
                      << std::to_string(file.file_size_) << " bytes to " << std::to_string(compacted_file.file_size_)
                      << " bytes";
1279 1280 1281 1282 1283 1284 1285 1286 1287

    if (options_.insert_cache_immediately_) {
        segment_writer_ptr->Cache();
    }

    return status;
}

Status
G
groot 已提交
1288
DBImpl::GetVectorsByID(const engine::meta::CollectionSchema& collection, const IDNumbers& id_array,
1289
                       std::vector<engine::VectorsData>& vectors) {
1290 1291 1292 1293
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
1294
    meta::FilesHolder files_holder;
J
Jin Hai 已提交
1295 1296
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
1297

G
groot 已提交
1298 1299 1300 1301 1302
    std::vector<meta::CollectionSchema> collection_array;
    auto status = meta_ptr_->ShowPartitions(collection.collection_id_, collection_array);

    collection_array.push_back(collection);
    status = meta_ptr_->FilesByTypeEx(collection_array, file_types, files_holder);
1303
    if (!status.ok()) {
G
groot 已提交
1304
        std::string err_msg = "Failed to get files for GetVectorByID: " + status.message();
1305
        LOG_ENGINE_ERROR_ << err_msg;
1306 1307 1308
        return status;
    }

G
groot 已提交
1309
    if (files_holder.HoldFiles().empty()) {
1310
        LOG_ENGINE_DEBUG_ << "No files to get vector by id from";
J
Jin Hai 已提交
1311
        return Status(DB_NOT_FOUND, "Collection is empty");
1312 1313 1314
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();
G
groot 已提交
1315
    status = GetVectorsByIdHelper(id_array, vectors, files_holder);
1316 1317
    cache::CpuCacheMgr::GetInstance()->PrintInfo();

G
groot 已提交
1318 1319 1320 1321 1322
    if (vectors.empty()) {
        std::string msg = "Vectors not found in collection " + collection.collection_id_;
        LOG_ENGINE_DEBUG_ << msg;
    }

1323 1324 1325
    return status;
}

Y
yukun 已提交
1326 1327
Status
DBImpl::GetEntitiesByID(const std::string& collection_id, const milvus::engine::IDNumbers& id_array,
1328 1329
                        const std::vector<std::string>& field_names, std::vector<engine::VectorsData>& vectors,
                        std::vector<engine::AttrsData>& attrs) {
Y
yukun 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
        LOG_ENGINE_ERROR_ << "Collection " << collection_id << " does not exist: ";
        return Status(DB_NOT_FOUND, "Collection does not exist");
    }
    if (!status.ok()) {
        return status;
    }

1344 1345 1346 1347
    if (field_names.empty()) {
        return Status::OK();
    }

Y
yukun 已提交
1348 1349 1350 1351 1352 1353 1354 1355
    engine::meta::CollectionSchema collection_schema;
    engine::meta::hybrid::FieldsSchema fields_schema;
    collection_schema.collection_id_ = collection_id;
    status = meta_ptr_->DescribeHybridCollection(collection_schema, fields_schema);
    if (!status.ok()) {
        return status;
    }
    std::unordered_map<std::string, engine::meta::hybrid::DataType> attr_type;
1356 1357 1358
    for (const auto& schema : fields_schema.fields_schema_) {
        if (schema.field_type_ == (int32_t)engine::meta::hybrid::DataType::VECTOR_FLOAT ||
            schema.field_type_ == (int32_t)engine::meta::hybrid::DataType::VECTOR_BINARY) {
Y
yukun 已提交
1359 1360
            continue;
        }
1361 1362 1363 1364 1365 1366
        for (const auto& name : field_names) {
            if (name == schema.field_name_) {
                attr_type.insert(
                    std::make_pair(schema.field_name_, (engine::meta::hybrid::DataType)schema.field_type_));
            }
        }
Y
yukun 已提交
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    }

    meta::FilesHolder files_holder;
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};

    status = meta_ptr_->FilesByType(collection_id, file_types, files_holder);
    if (!status.ok()) {
        std::string err_msg = "Failed to get files for GetEntitiesByID: " + status.message();
        LOG_ENGINE_ERROR_ << err_msg;
        return status;
    }

    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
    if (!status.ok()) {
        std::string err_msg = "Failed to get partitions for GetEntitiesByID: " + status.message();
        LOG_ENGINE_ERROR_ << err_msg;
        return status;
    }
    for (auto& schema : partition_array) {
        status = meta_ptr_->FilesByType(schema.collection_id_, file_types, files_holder);
        if (!status.ok()) {
            std::string err_msg = "Failed to get files for GetEntitiesByID: " + status.message();
            LOG_ENGINE_ERROR_ << err_msg;
            return status;
        }
    }

    if (files_holder.HoldFiles().empty()) {
        LOG_ENGINE_DEBUG_ << "No files to get vector by id from";
        return Status(DB_NOT_FOUND, "Collection is empty");
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();
1402
    status = GetEntitiesByIdHelper(collection_id, id_array, field_names, attr_type, vectors, attrs, files_holder);
Y
yukun 已提交
1403 1404 1405 1406 1407
    cache::CpuCacheMgr::GetInstance()->PrintInfo();

    return status;
}

1408
Status
J
Jin Hai 已提交
1409
DBImpl::GetVectorIDs(const std::string& collection_id, const std::string& segment_id, IDNumbers& vector_ids) {
1410 1411 1412 1413
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
1414
    // step 1: check collection existence
1415 1416 1417
    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
1418
        LOG_ENGINE_ERROR_ << "Collection " << collection_id << " does not exist: ";
J
Jin Hai 已提交
1419
        return Status(DB_NOT_FOUND, "Collection does not exist");
1420 1421 1422 1423 1424 1425
    }
    if (!status.ok()) {
        return status;
    }

    //  step 2: find segment
G
groot 已提交
1426 1427
    meta::FilesHolder files_holder;
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, files_holder);
1428 1429 1430 1431
    if (!status.ok()) {
        return status;
    }

G
groot 已提交
1432
    milvus::engine::meta::SegmentsSchema& collection_files = files_holder.HoldFiles();
1433
    if (collection_files.empty()) {
1434 1435 1436
        return Status(DB_NOT_FOUND, "Segment does not exist");
    }

J
Jin Hai 已提交
1437
    // check the segment is belong to this collection
1438
    if (collection_files[0].collection_id_ != collection_id) {
J
Jin Hai 已提交
1439
        // the segment could be in a partition under this collection
1440 1441 1442 1443
        meta::CollectionSchema collection_schema;
        collection_schema.collection_id_ = collection_files[0].collection_id_;
        status = DescribeCollection(collection_schema);
        if (collection_schema.owner_collection_ != collection_id) {
J
Jin Hai 已提交
1444
            return Status(DB_NOT_FOUND, "Segment does not belong to this collection");
1445 1446 1447 1448 1449
        }
    }

    // step 3: load segment ids and delete offset
    std::string segment_dir;
1450
    engine::utils::GetParentPath(collection_files[0].location_, segment_dir);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    segment::SegmentReader segment_reader(segment_dir);

    std::vector<segment::doc_id_t> uids;
    status = segment_reader.LoadUids(uids);
    if (!status.ok()) {
        return status;
    }

    segment::DeletedDocsPtr deleted_docs_ptr;
    status = segment_reader.LoadDeletedDocs(deleted_docs_ptr);
    if (!status.ok()) {
        return status;
    }

    // step 4: construct id array
    // avoid duplicate offset and erase from max offset to min offset
    auto& deleted_offset = deleted_docs_ptr->GetDeletedDocs();
    std::set<segment::offset_t, std::greater<segment::offset_t>> ordered_offset;
    for (segment::offset_t offset : deleted_offset) {
        ordered_offset.insert(offset);
    }
    for (segment::offset_t offset : ordered_offset) {
        uids.erase(uids.begin() + offset);
    }
    vector_ids.swap(uids);
S
starlord 已提交
1476

G
groot 已提交
1477
    return status;
X
Xu Peng 已提交
1478 1479
}

1480
Status
G
groot 已提交
1481 1482
DBImpl::GetVectorsByIdHelper(const IDNumbers& id_array, std::vector<engine::VectorsData>& vectors,
                             meta::FilesHolder& files_holder) {
G
groot 已提交
1483 1484
    // attention: this is a copy, not a reference, since the files_holder.UnMarkFile will change the array internal
    milvus::engine::meta::SegmentsSchema files = files_holder.HoldFiles();
1485
    LOG_ENGINE_DEBUG_ << "Getting vector by id in " << files.size() << " files, id count = " << id_array.size();
J
Jin Hai 已提交
1486

1487 1488 1489 1490 1491 1492 1493
    // sometimes not all of id_array can be found, we need to return empty vector for id not found
    // for example:
    // id_array = [1, -1, 2, -1, 3]
    // vectors should return [valid_vector, empty_vector, valid_vector, empty_vector, valid_vector]
    // the ID2RAW is to ensure returned vector sequence is consist with id_array
    using ID2VECTOR = std::map<int64_t, VectorsData>;
    ID2VECTOR map_id2vector;
1494

1495 1496 1497
    vectors.clear();

    IDNumbers temp_ids = id_array;
1498
    for (auto& file : files) {
G
groot 已提交
1499 1500 1501
        if (temp_ids.empty()) {
            break;  // all vectors found, no need to continue
        }
1502 1503 1504 1505 1506
        // Load bloom filter
        std::string segment_dir;
        engine::utils::GetParentPath(file.location_, segment_dir);
        segment::SegmentReader segment_reader(segment_dir);
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
Y
yukun 已提交
1507 1508 1509 1510
        auto status = segment_reader.LoadBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            return status;
        }
1511

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
        for (IDNumbers::iterator it = temp_ids.begin(); it != temp_ids.end();) {
            int64_t vector_id = *it;
            // each id must has a VectorsData
            // if vector not found for an id, its VectorsData's vector_count = 0, else 1
            VectorsData& vector_ref = map_id2vector[vector_id];

            // Check if the id is present in bloom filter.
            if (id_bloom_filter_ptr->Check(vector_id)) {
                // Load uids and check if the id is indeed present. If yes, find its offset.
                std::vector<segment::doc_id_t> uids;
                auto status = segment_reader.LoadUids(uids);
1523 1524 1525
                if (!status.ok()) {
                    return status;
                }
1526 1527 1528 1529 1530 1531 1532 1533

                auto found = std::find(uids.begin(), uids.end(), vector_id);
                if (found != uids.end()) {
                    auto offset = std::distance(uids.begin(), found);

                    // Check whether the id has been deleted
                    segment::DeletedDocsPtr deleted_docs_ptr;
                    status = segment_reader.LoadDeletedDocs(deleted_docs_ptr);
1534
                    if (!status.ok()) {
J
Jin Hai 已提交
1535
                        LOG_ENGINE_ERROR_ << status.message();
1536 1537
                        return status;
                    }
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
                    auto& deleted_docs = deleted_docs_ptr->GetDeletedDocs();

                    auto deleted = std::find(deleted_docs.begin(), deleted_docs.end(), offset);
                    if (deleted == deleted_docs.end()) {
                        // Load raw vector
                        bool is_binary = utils::IsBinaryMetricType(file.metric_type_);
                        size_t single_vector_bytes = is_binary ? file.dimension_ / 8 : file.dimension_ * sizeof(float);
                        std::vector<uint8_t> raw_vector;
                        status =
                            segment_reader.LoadVectors(offset * single_vector_bytes, single_vector_bytes, raw_vector);
                        if (!status.ok()) {
                            LOG_ENGINE_ERROR_ << status.message();
                            return status;
                        }

                        vector_ref.vector_count_ = 1;
                        if (is_binary) {
                            vector_ref.binary_data_.swap(raw_vector);
                        } else {
                            std::vector<float> float_vector;
                            float_vector.resize(file.dimension_);
                            memcpy(float_vector.data(), raw_vector.data(), single_vector_bytes);
                            vector_ref.float_data_.swap(float_vector);
                        }
                        temp_ids.erase(it);
                        continue;
1564 1565 1566
                    }
                }
            }
1567 1568 1569

            it++;
        }
G
groot 已提交
1570 1571 1572

        // unmark file, allow the file to be deleted
        files_holder.UnmarkFile(file);
1573 1574 1575 1576 1577 1578 1579 1580
    }

    for (auto id : id_array) {
        VectorsData& vector_ref = map_id2vector[id];

        VectorsData data;
        data.vector_count_ = vector_ref.vector_count_;
        if (data.vector_count_ > 0) {
G
groot 已提交
1581 1582
            data.float_data_ = vector_ref.float_data_;    // copy data since there could be duplicated id
            data.binary_data_ = vector_ref.binary_data_;  // copy data since there could be duplicated id
1583
        }
1584
        vectors.emplace_back(data);
1585 1586 1587 1588 1589
    }

    return Status::OK();
}

Y
yukun 已提交
1590 1591
Status
DBImpl::GetEntitiesByIdHelper(const std::string& collection_id, const milvus::engine::IDNumbers& id_array,
1592
                              const std::vector<std::string>& field_names,
Y
yukun 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
                              std::unordered_map<std::string, engine::meta::hybrid::DataType>& attr_type,
                              std::vector<engine::VectorsData>& vectors, std::vector<engine::AttrsData>& attrs,
                              milvus::engine::meta::FilesHolder& files_holder) {
    // attention: this is a copy, not a reference, since the files_holder.UnMarkFile will change the array internal
    milvus::engine::meta::SegmentsSchema files = files_holder.HoldFiles();
    LOG_ENGINE_DEBUG_ << "Getting vector by id in " << files.size() << " files, id count = " << id_array.size();

    // sometimes not all of id_array can be found, we need to return empty vector for id not found
    // for example:
    // id_array = [1, -1, 2, -1, 3]
    // vectors should return [valid_vector, empty_vector, valid_vector, empty_vector, valid_vector]
    // the ID2RAW is to ensure returned vector sequence is consist with id_array
    using ID2ATTR = std::map<int64_t, engine::AttrsData>;
    using ID2VECTOR = std::map<int64_t, engine::VectorsData>;
    ID2ATTR map_id2attr;
    ID2VECTOR map_id2vector;

    IDNumbers temp_ids = id_array;
    for (auto& file : files) {
        // Load bloom filter
        std::string segment_dir;
        engine::utils::GetParentPath(file.location_, segment_dir);
        segment::SegmentReader segment_reader(segment_dir);
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        segment_reader.LoadBloomFilter(id_bloom_filter_ptr);

        for (IDNumbers::iterator it = temp_ids.begin(); it != temp_ids.end();) {
1620
            int64_t entity_id = *it;
Y
yukun 已提交
1621 1622
            // each id must has a VectorsData
            // if vector not found for an id, its VectorsData's vector_count = 0, else 1
1623 1624 1625 1626
            AttrsData& attr_ref = map_id2attr[entity_id];
            VectorsData& vector_ref = map_id2vector[entity_id];
            attr_ref.attr_type_ = attr_type;
            attr_ref.attr_count_ = 0;
Y
yukun 已提交
1627 1628

            // Check if the id is present in bloom filter.
1629
            if (id_bloom_filter_ptr->Check(entity_id)) {
Y
yukun 已提交
1630 1631 1632 1633 1634 1635 1636
                // Load uids and check if the id is indeed present. If yes, find its offset.
                std::vector<segment::doc_id_t> uids;
                auto status = segment_reader.LoadUids(uids);
                if (!status.ok()) {
                    return status;
                }

1637
                auto found = std::find(uids.begin(), uids.end(), entity_id);
Y
yukun 已提交
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
                if (found != uids.end()) {
                    auto offset = std::distance(uids.begin(), found);

                    // Check whether the id has been deleted
                    segment::DeletedDocsPtr deleted_docs_ptr;
                    status = segment_reader.LoadDeletedDocs(deleted_docs_ptr);
                    if (!status.ok()) {
                        LOG_ENGINE_ERROR_ << status.message();
                        return status;
                    }
                    auto& deleted_docs = deleted_docs_ptr->GetDeletedDocs();

                    auto deleted = std::find(deleted_docs.begin(), deleted_docs.end(), offset);
                    if (deleted == deleted_docs.end()) {
                        std::unordered_map<std::string, std::vector<uint8_t>> raw_attrs;
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

                        for (const auto& field_name : field_names) {
                            if (attr_type.find(field_name) == attr_type.end()) {
                                // Load raw vector
                                bool is_binary = utils::IsBinaryMetricType(file.metric_type_);
                                size_t single_vector_bytes =
                                    is_binary ? file.dimension_ / 8 : file.dimension_ * sizeof(float);
                                std::vector<uint8_t> raw_vector;
                                status = segment_reader.LoadVectors(offset * single_vector_bytes, single_vector_bytes,
                                                                    raw_vector);
                                if (!status.ok()) {
                                    LOG_ENGINE_ERROR_ << status.message();
                                    return status;
Y
yukun 已提交
1666
                                }
1667 1668 1669 1670 1671 1672 1673 1674
                                vector_ref.vector_count_ = 1;
                                if (is_binary) {
                                    vector_ref.binary_data_.swap(raw_vector);
                                } else {
                                    std::vector<float> float_vector;
                                    float_vector.resize(file.dimension_);
                                    memcpy(float_vector.data(), raw_vector.data(), single_vector_bytes);
                                    vector_ref.float_data_.swap(float_vector);
Y
yukun 已提交
1675
                                }
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
                            } else {
                                size_t num_bytes;
                                switch (attr_type.at(field_name)) {
                                    case engine::meta::hybrid::DataType::INT8: {
                                        num_bytes = sizeof(int8_t);
                                        break;
                                    }
                                    case engine::meta::hybrid::DataType::INT16: {
                                        num_bytes = sizeof(int16_t);
                                        break;
                                    }
                                    case engine::meta::hybrid::DataType::INT32: {
                                        num_bytes = sizeof(int32_t);
                                        break;
                                    }
                                    case engine::meta::hybrid::DataType::INT64: {
                                        num_bytes = sizeof(int64_t);
                                        break;
                                    }
                                    case engine::meta::hybrid::DataType::FLOAT: {
                                        num_bytes = sizeof(float);
                                        break;
                                    }
                                    case engine::meta::hybrid::DataType::DOUBLE: {
                                        num_bytes = sizeof(double);
                                        break;
                                    }
                                    default: {
                                        std::string msg = "Field type of " + field_name + " is wrong";
                                        return Status{DB_ERROR, msg};
                                    }
Y
yukun 已提交
1707
                                }
1708 1709 1710 1711 1712
                                std::vector<uint8_t> raw_attr;
                                status = segment_reader.LoadAttrs(field_name, offset * num_bytes, num_bytes, raw_attr);
                                if (!status.ok()) {
                                    LOG_ENGINE_ERROR_ << status.message();
                                    return status;
Y
yukun 已提交
1713
                                }
1714
                                raw_attrs.insert(std::make_pair(field_name, raw_attr));
Y
yukun 已提交
1715 1716 1717
                            }
                        }

1718 1719 1720 1721
                        if (!raw_attrs.empty()) {
                            attr_ref.attr_count_ = 1;
                            attr_ref.attr_data_ = raw_attrs;
                            attr_ref.id_array_.emplace_back(entity_id);
Y
yukun 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
                        }
                        temp_ids.erase(it);
                        continue;
                    }
                }
            }
            it++;
        }

        // unmark file, allow the file to be deleted
        files_holder.UnmarkFile(file);
    }

    for (auto id : id_array) {
        VectorsData& vector_ref = map_id2vector[id];

        VectorsData data;
        data.vector_count_ = vector_ref.vector_count_;
        if (data.vector_count_ > 0) {
            data.float_data_ = vector_ref.float_data_;    // copy data since there could be duplicated id
            data.binary_data_ = vector_ref.binary_data_;  // copy data since there could be duplicated id
        }
1744
        data.id_array_.emplace_back(id);
Y
yukun 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
        vectors.emplace_back(data);
        attrs.emplace_back(map_id2attr[id]);
    }

    if (vectors.empty()) {
        std::string msg = "Vectors not found in collection " + collection_id;
        LOG_ENGINE_DEBUG_ << msg;
    }

    return Status::OK();
}

S
starlord 已提交
1757
Status
G
groot 已提交
1758 1759
DBImpl::CreateIndex(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
                    const CollectionIndex& index) {
1760
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1761 1762 1763
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
1764
    // step 1: wait merge file thread finished to avoid duplicate data bug
1765
    auto status = Flush();
G
groot 已提交
1766
    WaitMergeFileFinish();  // let merge file thread finish
G
groot 已提交
1767 1768 1769 1770 1771 1772 1773 1774

    // merge all files for this collection, including its partitions
    std::set<std::string> merge_collection_ids = {collection_id};
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
    for (auto& schema : partition_array) {
        merge_collection_ids.insert(schema.collection_id_);
    }
G
groot 已提交
1775 1776
    StartMergeTask(merge_collection_ids, true);  // start force-merge task
    WaitMergeFileFinish();                       // let force-merge file thread finish
G
groot 已提交
1777

S
starlord 已提交
1778 1779 1780
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);

G
groot 已提交
1781
        // step 2: check index difference
1782
        CollectionIndex old_index;
J
Jin Hai 已提交
1783
        status = DescribeIndex(collection_id, old_index);
S
starlord 已提交
1784
        if (!status.ok()) {
1785
            LOG_ENGINE_ERROR_ << "Failed to get collection index info for collection: " << collection_id;
S
starlord 已提交
1786 1787 1788
            return status;
        }

G
groot 已提交
1789
        // step 3: update index info
1790
        CollectionIndex new_index = index;
1791
        json new_index_json = new_index.extra_params_;
G
groot 已提交
1792 1793
        //        new_index.metric_type_ = old_index.metric_type_;
        // dont change metric type, it was defined by CreateCollection
S
starlord 已提交
1794
        if (!utils::IsSameIndex(old_index, new_index)) {
1795
            status = UpdateCollectionIndexRecursively(collection_id, new_index);
S
starlord 已提交
1796 1797 1798 1799 1800 1801
            if (!status.ok()) {
                return status;
            }
        }
    }

S
starlord 已提交
1802
    // step 4: wait and build index
1803
    status = index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
G
groot 已提交
1804
    status = WaitCollectionIndexRecursively(context, collection_id, index);
S
starlord 已提交
1805

G
groot 已提交
1806
    return status;
S
starlord 已提交
1807 1808
}

Y
yukun 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
Status
DBImpl::SerializeStructuredIndex(const meta::SegmentSchema& segment_schema,
                                 const std::unordered_map<std::string, knowhere::IndexPtr>& attr_indexes,
                                 const std::unordered_map<std::string, int64_t>& attr_sizes,
                                 const std::unordered_map<std::string, meta::hybrid::DataType>& attr_types) {
    auto status = Status::OK();

    std::string segment_dir;
    utils::GetParentPath(segment_schema.location_, segment_dir);
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(segment_dir);
    status = segment_writer_ptr->SetAttrsIndex(attr_indexes, attr_sizes, attr_types);
    if (!status.ok()) {
        return status;
    }
    status = segment_writer_ptr->WriteAttrsIndex();
    if (!status.ok()) {
        return status;
    }

    return status;
}

Status
DBImpl::FlushAttrsIndex(const std::string& collection_id) {
    std::vector<int> file_types = {
        milvus::engine::meta::SegmentSchema::RAW,
        milvus::engine::meta::SegmentSchema::TO_INDEX,
    };
    meta::FilesHolder files_holder;
    auto status = meta_ptr_->FilesByType(collection_id, file_types, files_holder);
    if (!status.ok()) {
        return status;
    }

    meta::CollectionSchema collection_schema;
    meta::hybrid::FieldsSchema fields_schema;
    collection_schema.collection_id_ = collection_id;
    status = meta_ptr_->DescribeHybridCollection(collection_schema, fields_schema);
    if (!status.ok()) {
        return Status::OK();
    }

    std::unordered_map<std::string, std::vector<uint8_t>> attr_datas;
    std::unordered_map<std::string, int64_t> attr_sizes;
    std::unordered_map<std::string, meta::hybrid::DataType> attr_types;
    std::vector<std::string> field_names;

    for (auto& segment_schema : files_holder.HoldFiles()) {
        std::string segment_dir;
        utils::GetParentPath(segment_schema.location_, segment_dir);
        auto segment_reader_ptr = std::make_shared<segment::SegmentReader>(segment_dir);
        segment::SegmentPtr segment_ptr;
        segment_reader_ptr->GetSegment(segment_ptr);
        status = segment_reader_ptr->Load();

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

        for (auto& field_schema : fields_schema.fields_schema_) {
1869
            if (field_schema.field_type_ != (int32_t)meta::hybrid::DataType::VECTOR_FLOAT) {
Y
yukun 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
                attr_types.insert(
                    std::make_pair(field_schema.field_name_, (meta::hybrid::DataType)field_schema.field_type_));
                field_names.emplace_back(field_schema.field_name_);
            }
        }

        auto attrs = segment_ptr->attrs_ptr_->attrs;

        auto attr_it = attrs.begin();
        for (; attr_it != attrs.end(); attr_it++) {
            attr_datas.insert(std::make_pair(attr_it->first, attr_it->second->GetMutableData()));
            attr_sizes.insert(std::make_pair(attr_it->first, attr_it->second->GetCount()));
        }

        std::unordered_map<std::string, knowhere::IndexPtr> attr_indexes;
        status = CreateStructuredIndex(collection_id, field_names, attr_types, attr_datas, attr_sizes, attr_indexes);
        if (!status.ok()) {
            return status;
        }

        status = SerializeStructuredIndex(segment_schema, attr_indexes, attr_sizes, attr_types);
        if (!status.ok()) {
            return status;
        }
    }
}

Status
DBImpl::CreateStructuredIndex(const std::string& collection_id, const std::vector<std::string>& field_names,
                              const std::unordered_map<std::string, meta::hybrid::DataType>& attr_types,
                              const std::unordered_map<std::string, std::vector<uint8_t>>& attr_datas,
                              std::unordered_map<std::string, int64_t>& attr_sizes,
                              std::unordered_map<std::string, knowhere::IndexPtr>& attr_indexes) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    for (auto& field_name : field_names) {
        knowhere::IndexPtr index_ptr = nullptr;
        switch (attr_types.at(field_name)) {
            case engine::meta::hybrid::DataType::INT8: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<int8_t> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto int8_index_ptr = std::make_shared<knowhere::StructuredIndexSort<int8_t>>(
                    (size_t)attr_size, reinterpret_cast<const signed char*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(int8_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(int8_t);
                break;
            }
            case engine::meta::hybrid::DataType::INT16: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<int16_t> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto int16_index_ptr = std::make_shared<knowhere::StructuredIndexSort<int16_t>>(
                    (size_t)attr_size, reinterpret_cast<const int16_t*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(int16_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(int16_t);
                break;
            }
            case engine::meta::hybrid::DataType::INT32: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<int32_t> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto int32_index_ptr = std::make_shared<knowhere::StructuredIndexSort<int32_t>>(
                    (size_t)attr_size, reinterpret_cast<const int32_t*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(int32_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(int32_t);
                break;
            }
            case engine::meta::hybrid::DataType::INT64: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<int64_t> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto int64_index_ptr = std::make_shared<knowhere::StructuredIndexSort<int64_t>>(
                    (size_t)attr_size, reinterpret_cast<const int64_t*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(int64_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(int64_t);
                break;
            }
            case engine::meta::hybrid::DataType::FLOAT: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<float> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto float_index_ptr = std::make_shared<knowhere::StructuredIndexSort<float>>(
                    (size_t)attr_size, reinterpret_cast<const float*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(float_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(float);
                break;
            }
            case engine::meta::hybrid::DataType::DOUBLE: {
                auto attr_size = attr_sizes.at(field_name);
                std::vector<double> attr_data(attr_size);
                memcpy(attr_data.data(), attr_datas.at(field_name).data(), attr_size);

                auto double_index_ptr = std::make_shared<knowhere::StructuredIndexSort<double>>(
                    (size_t)attr_size, reinterpret_cast<const double*>(attr_data.data()));
                index_ptr = std::static_pointer_cast<knowhere::Index>(double_index_ptr);

                attr_indexes.insert(std::make_pair(field_name, index_ptr));
                attr_sizes.at(field_name) *= sizeof(double);
                break;
            }
            default: {}
        }
    }

#if 0
    {
        std::unordered_map<std::string, engine::meta::hybrid::DataType> attr_type;
        engine::meta::CollectionSchema collection_schema;
        engine::meta::hybrid::FieldsSchema fields_schema;
        collection_schema.collection_id_ = collection_id;
        status = meta_ptr_->DescribeHybridCollection(collection_schema, fields_schema);
        if (!status.ok()) {
            return status;
        }

        if (field_names.empty()) {
            for (auto& schema : fields_schema.fields_schema_) {
                field_names.emplace_back(schema.collection_id_);
            }
        }

        for (auto& schema : fields_schema.fields_schema_) {
            attr_type.insert(std::make_pair(schema.field_name_, (engine::meta::hybrid::DataType)schema.field_type_));
        }

        meta::FilesHolder files_holder;
        meta_ptr_->FilesToIndex(files_holder);

        milvus::engine::meta::SegmentsSchema& to_index_files = files_holder.HoldFiles();
        status = index_failed_checker_.IgnoreFailedIndexFiles(to_index_files);
        if (!status.ok()) {
            return status;
        }

        status = SerializeStructuredIndex(to_index_files, attr_type, field_names);
        if (!status.ok()) {
            return status;
        }
    }
#endif
    return Status::OK();
}

S
starlord 已提交
2031
Status
2032
DBImpl::DescribeIndex(const std::string& collection_id, CollectionIndex& index) {
2033
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2034 2035 2036
        return SHUTDOWN_ERROR;
    }

2037
    return meta_ptr_->DescribeCollectionIndex(collection_id, index);
S
starlord 已提交
2038 2039
}

S
starlord 已提交
2040
Status
J
Jin Hai 已提交
2041
DBImpl::DropIndex(const std::string& collection_id) {
2042
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2043 2044 2045
        return SHUTDOWN_ERROR;
    }

2046
    LOG_ENGINE_DEBUG_ << "Drop index for collection: " << collection_id;
G
groot 已提交
2047
    auto status = DropCollectionIndexRecursively(collection_id);
G
groot 已提交
2048 2049
    std::set<std::string> merge_collection_ids = {collection_id};
    StartMergeTask(merge_collection_ids, true);  // merge small files after drop index
G
groot 已提交
2050
    return status;
S
starlord 已提交
2051 2052
}

S
starlord 已提交
2053
Status
2054 2055 2056
DBImpl::QueryByIDs(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
                   const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
                   const IDNumbers& id_array, ResultIds& result_ids, ResultDistances& result_distances) {
2057
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2058
        return SHUTDOWN_ERROR;
S
starlord 已提交
2059 2060
    }

2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
    if (id_array.empty()) {
        return Status(DB_ERROR, "Empty id array during query by id");
    }

    TimeRecorder rc("Query by id in collection:" + collection_id);

    // get collection schema
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
            std::string msg = "Collection to search does not exist: " + collection_id;
            LOG_ENGINE_ERROR_ << msg;
            return Status(DB_NOT_FOUND, msg);
        } else {
            return status;
        }
    } else {
        if (!collection_schema.owner_collection_.empty()) {
            std::string msg = "Collection to search does not exist: " + collection_id;
            LOG_ENGINE_ERROR_ << msg;
            return Status(DB_NOT_FOUND, msg);
        }
    }

    rc.RecordSection("get collection schema");

    // get target vectors data
    std::vector<milvus::engine::VectorsData> vectors;
G
groot 已提交
2091
    status = GetVectorsByID(collection_schema, id_array, vectors);
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    if (!status.ok()) {
        std::string msg = "Failed to get vector data for collection: " + collection_id;
        LOG_ENGINE_ERROR_ << msg;
        return status;
    }

    // some vectors could not be found, no need to search them
    uint64_t valid_count = 0;
    bool is_binary = utils::IsBinaryMetricType(collection_schema.metric_type_);
    for (auto& vector : vectors) {
        if (vector.vector_count_ > 0) {
            valid_count++;
        }
    }

    // copy valid vectors data for search input
    uint64_t dimension = collection_schema.dimension_;
    VectorsData valid_vectors;
    valid_vectors.vector_count_ = valid_count;
    if (is_binary) {
        valid_vectors.binary_data_.resize(valid_count * dimension / 8);
    } else {
        valid_vectors.float_data_.resize(valid_count * dimension * sizeof(float));
    }

    int64_t valid_index = 0;
    for (size_t i = 0; i < vectors.size(); i++) {
        if (vectors[i].vector_count_ == 0) {
            continue;
        }
        if (is_binary) {
            memcpy(valid_vectors.binary_data_.data() + valid_index * dimension / 8, vectors[i].binary_data_.data(),
                   vectors[i].binary_data_.size());
        } else {
            memcpy(valid_vectors.float_data_.data() + valid_index * dimension, vectors[i].float_data_.data(),
                   vectors[i].float_data_.size() * sizeof(float));
        }
        valid_index++;
    }

    rc.RecordSection("construct query input");

    // search valid vectors
    ResultIds valid_result_ids;
    ResultDistances valid_result_distances;
    status = Query(context, collection_id, partition_tags, k, extra_params, valid_vectors, valid_result_ids,
                   valid_result_distances);
    if (!status.ok()) {
        std::string msg = "Failed to query by id in collection " + collection_id + ", error: " + status.message();
        LOG_ENGINE_ERROR_ << msg;
        return status;
    }

    if (valid_result_ids.size() != valid_count * k || valid_result_distances.size() != valid_count * k) {
        std::string msg = "Failed to query by id in collection " + collection_id + ", result doesn't match id count";
        return Status(DB_ERROR, msg);
    }

    rc.RecordSection("query vealid vectors");

    // construct result
    if (valid_count == id_array.size()) {
        result_ids.swap(valid_result_ids);
        result_distances.swap(valid_result_distances);
    } else {
        result_ids.resize(vectors.size() * k);
        result_distances.resize(vectors.size() * k);
        int64_t valid_index = 0;
        for (uint64_t i = 0; i < vectors.size(); i++) {
            if (vectors[i].vector_count_ > 0) {
                memcpy(result_ids.data() + i * k, valid_result_ids.data() + valid_index * k, k * sizeof(int64_t));
                memcpy(result_distances.data() + i * k, valid_result_distances.data() + valid_index * k,
                       k * sizeof(float));
                valid_index++;
            } else {
                memset(result_ids.data() + i * k, -1, k * sizeof(int64_t));
                for (uint64_t j = i * k; j < i * k + k; j++) {
                    result_distances[j] = std::numeric_limits<float>::max();
                }
            }
        }
    }

    rc.RecordSection("construct result");

    return status;
X
Xu Peng 已提交
2178 2179
}

2180 2181
Status
DBImpl::HybridQuery(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
Y
yukun 已提交
2182 2183
                    const std::vector<std::string>& partition_tags, query::GeneralQueryPtr general_query,
                    query::QueryPtr query_ptr, std::vector<std::string>& field_names,
Y
yukun 已提交
2184 2185
                    std::unordered_map<std::string, engine::meta::hybrid::DataType>& attr_type,
                    engine::QueryResult& result) {
2186 2187 2188 2189 2190 2191 2192
    auto query_ctx = context->Child("Query");

    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
G
groot 已提交
2193
    meta::FilesHolder files_holder;
2194 2195 2196
    if (partition_tags.empty()) {
        // no partition tag specified, means search in whole table
        // get all table files from parent table
G
groot 已提交
2197
        status = meta_ptr_->FilesToSearch(collection_id, files_holder);
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
        if (!status.ok()) {
            return status;
        }

        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
        if (!status.ok()) {
            return status;
        }
        for (auto& schema : partition_array) {
G
groot 已提交
2208
            status = meta_ptr_->FilesToSearch(schema.collection_id_, files_holder);
2209
            if (!status.ok()) {
G
groot 已提交
2210
                return Status(DB_ERROR, "get files to search failed in HybridQuery");
2211 2212 2213
            }
        }

G
groot 已提交
2214 2215
        if (files_holder.HoldFiles().empty()) {
            return Status::OK();  // no files to search
2216 2217 2218 2219 2220 2221 2222
        }
    } else {
        // get files from specified partitions
        std::set<std::string> partition_name_array;
        GetPartitionsByTags(collection_id, partition_tags, partition_name_array);

        for (auto& partition_name : partition_name_array) {
G
groot 已提交
2223
            status = meta_ptr_->FilesToSearch(partition_name, files_holder);
2224
            if (!status.ok()) {
G
groot 已提交
2225
                return Status(DB_ERROR, "get files to search failed in HybridQuery");
2226 2227 2228
            }
        }

G
groot 已提交
2229
        if (files_holder.HoldFiles().empty()) {
2230 2231 2232 2233 2234
            return Status::OK();
        }
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
Y
yukun 已提交
2235 2236
    status = HybridQueryAsync(query_ctx, collection_id, files_holder, general_query, query_ptr, field_names, attr_type,
                              result);
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
    if (!status.ok()) {
        return status;
    }
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query

    query_ctx->GetTraceContext()->GetSpan()->Finish();

    return status;
}

S
starlord 已提交
2247
Status
J
Jin Hai 已提交
2248
DBImpl::Query(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
2249
              const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
Y
yukun 已提交
2250
              VectorsData& vectors, ResultIds& result_ids, ResultDistances& result_distances) {
2251
    milvus::server::ContextChild tracer(context, "Query");
Z
Zhiru Zhu 已提交
2252

2253
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2254
        return SHUTDOWN_ERROR;
S
starlord 已提交
2255 2256
    }

G
groot 已提交
2257
    Status status;
G
groot 已提交
2258
    meta::FilesHolder files_holder;
G
groot 已提交
2259
    if (partition_tags.empty()) {
G
groot 已提交
2260
#if 0
J
Jin Hai 已提交
2261 2262
        // no partition tag specified, means search in whole collection
        // get all collection files from parent collection
G
groot 已提交
2263
        status = meta_ptr_->FilesToSearch(collection_id, files_holder);
G
groot 已提交
2264 2265 2266 2267
        if (!status.ok()) {
            return status;
        }

J
Jin Hai 已提交
2268 2269
        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2270
        for (auto& schema : partition_array) {
G
groot 已提交
2271
            status = meta_ptr_->FilesToSearch(schema.collection_id_, files_holder);
2272
        }
G
groot 已提交
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
#else
        // no partition tag specified, means search in whole collection
        // get files from root collection
        status = meta_ptr_->FilesToSearch(collection_id, files_holder);
        if (!status.ok()) {
            return status;
        }

        // get files from partitions
        std::set<std::string> partition_ids;
        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
        for (auto& id : partition_array) {
            partition_ids.insert(id.collection_id_);
        }

        status = meta_ptr_->FilesToSearchEx(collection_id, partition_ids, files_holder);
        if (!status.ok()) {
            return status;
        }
#endif
2294

G
groot 已提交
2295 2296
        if (files_holder.HoldFiles().empty()) {
            return Status::OK();  // no files to search
G
groot 已提交
2297 2298
        }
    } else {
G
groot 已提交
2299
#if 0
G
groot 已提交
2300 2301
        // get files from specified partitions
        std::set<std::string> partition_name_array;
J
Jin Hai 已提交
2302
        status = GetPartitionsByTags(collection_id, partition_tags, partition_name_array);
T
Tinkerrr 已提交
2303 2304 2305
        if (!status.ok()) {
            return status;  // didn't match any partition.
        }
G
groot 已提交
2306 2307

        for (auto& partition_name : partition_name_array) {
G
groot 已提交
2308
            status = meta_ptr_->FilesToSearch(partition_name, files_holder);
2309
        }
G
groot 已提交
2310 2311 2312 2313 2314 2315
#else
        std::set<std::string> partition_name_array;
        status = GetPartitionsByTags(collection_id, partition_tags, partition_name_array);
        if (!status.ok()) {
            return status;  // didn't match any partition.
        }
2316

G
groot 已提交
2317 2318 2319 2320 2321 2322 2323
        std::set<std::string> partition_ids;
        for (auto& partition_name : partition_name_array) {
            partition_ids.insert(partition_name);
        }

        status = meta_ptr_->FilesToSearchEx(collection_id, partition_ids, files_holder);
#endif
G
groot 已提交
2324 2325
        if (files_holder.HoldFiles().empty()) {
            return Status::OK();  // no files to search
2326 2327 2328
        }
    }

S
starlord 已提交
2329
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
G
groot 已提交
2330
    status = QueryAsync(tracer.Context(), files_holder, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
2331
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
2332

S
starlord 已提交
2333
    return status;
G
groot 已提交
2334
}
X
Xu Peng 已提交
2335

S
starlord 已提交
2336
Status
2337
DBImpl::QueryByFileID(const std::shared_ptr<server::Context>& context, const std::vector<std::string>& file_ids,
Y
yukun 已提交
2338
                      uint64_t k, const milvus::json& extra_params, VectorsData& vectors, ResultIds& result_ids,
2339
                      ResultDistances& result_distances) {
2340
    milvus::server::ContextChild tracer(context, "Query by file id");
Z
Zhiru Zhu 已提交
2341

2342
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2343
        return SHUTDOWN_ERROR;
S
starlord 已提交
2344 2345
    }

S
starlord 已提交
2346
    // get specified files
2347
    std::vector<size_t> ids;
Y
Yu Kun 已提交
2348
    for (auto& id : file_ids) {
2349
        std::string::size_type sz;
J
jinhai 已提交
2350
        ids.push_back(std::stoul(id, &sz));
2351 2352
    }

G
groot 已提交
2353 2354
    meta::FilesHolder files_holder;
    auto status = meta_ptr_->FilesByID(ids, files_holder);
2355 2356
    if (!status.ok()) {
        return status;
2357 2358
    }

G
groot 已提交
2359
    milvus::engine::meta::SegmentsSchema& search_files = files_holder.HoldFiles();
2360
    if (search_files.empty()) {
S
starlord 已提交
2361
        return Status(DB_ERROR, "Invalid file id");
G
groot 已提交
2362 2363
    }

S
starlord 已提交
2364
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
G
groot 已提交
2365
    status = QueryAsync(tracer.Context(), files_holder, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
2366
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
2367

S
starlord 已提交
2368
    return status;
2369 2370
}

S
starlord 已提交
2371
Status
Y
Yu Kun 已提交
2372
DBImpl::Size(uint64_t& result) {
2373
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2374
        return SHUTDOWN_ERROR;
S
starlord 已提交
2375 2376
    }

S
starlord 已提交
2377
    return meta_ptr_->Size(result);
S
starlord 已提交
2378 2379 2380
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
2381
// internal methods
S
starlord 已提交
2382
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
2383
Status
G
groot 已提交
2384
DBImpl::QueryAsync(const std::shared_ptr<server::Context>& context, meta::FilesHolder& files_holder, uint64_t k,
Y
yukun 已提交
2385
                   const milvus::json& extra_params, VectorsData& vectors, ResultIds& result_ids,
2386
                   ResultDistances& result_distances) {
2387
    milvus::server::ContextChild tracer(context, "Query Async");
G
groot 已提交
2388
    server::CollectQueryMetrics metrics(vectors.vector_count_);
Y
Yu Kun 已提交
2389

G
groot 已提交
2390
    milvus::engine::meta::SegmentsSchema& files = files_holder.HoldFiles();
G
groot 已提交
2391 2392 2393
    if (files.size() > milvus::scheduler::TASK_TABLE_MAX_COUNT) {
        std::string msg =
            "Search files count exceed scheduler limit: " + std::to_string(milvus::scheduler::TASK_TABLE_MAX_COUNT);
2394
        LOG_ENGINE_ERROR_ << msg;
G
groot 已提交
2395 2396 2397
        return Status(DB_ERROR, msg);
    }

S
starlord 已提交
2398
    TimeRecorder rc("");
G
groot 已提交
2399

2400
    // step 1: construct search job
2401
    LOG_ENGINE_DEBUG_ << LogOut("Engine query begin, index file count: %ld", files.size());
2402
    scheduler::SearchJobPtr job = std::make_shared<scheduler::SearchJob>(tracer.Context(), k, extra_params, vectors);
Y
Yu Kun 已提交
2403
    for (auto& file : files) {
J
Jin Hai 已提交
2404
        scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
W
wxyu 已提交
2405
        job->AddIndexFile(file_ptr);
G
groot 已提交
2406 2407
    }

2408 2409 2410
    // Suspend builder
    SuspendIfFirst();

2411
    // step 2: put search job to scheduler and wait result
S
starlord 已提交
2412
    scheduler::JobMgrInst::GetInstance()->Put(job);
W
wxyu 已提交
2413
    job->WaitResult();
2414

2415 2416 2417
    // Resume builder
    ResumeIfLast();

G
groot 已提交
2418
    files_holder.ReleaseFiles();
W
wxyu 已提交
2419 2420
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
2421
    }
G
groot 已提交
2422

2423
    // step 3: construct results
G
groot 已提交
2424 2425
    result_ids = job->GetResultIds();
    result_distances = job->GetResultDistances();
S
starlord 已提交
2426
    rc.ElapseFromBegin("Engine query totally cost");
G
groot 已提交
2427 2428 2429 2430

    return Status::OK();
}

2431
Status
Y
yukun 已提交
2432
DBImpl::HybridQueryAsync(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
Y
yukun 已提交
2433 2434
                         meta::FilesHolder& files_holder, query::GeneralQueryPtr general_query,
                         query::QueryPtr query_ptr, std::vector<std::string>& field_names,
Y
yukun 已提交
2435 2436
                         std::unordered_map<std::string, engine::meta::hybrid::DataType>& attr_type,
                         engine::QueryResult& result) {
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
    auto query_async_ctx = context->Child("Query Async");

#if 0
    // Construct tasks
    for (auto file : files) {
        std::unordered_map<std::string, engine::DataType> types;
        auto it = attr_type.begin();
        for (; it != attr_type.end(); it++) {
            types.insert(std::make_pair(it->first, (engine::DataType)it->second));
        }

        auto file_ptr = std::make_shared<meta::TableFileSchema>(file);
        search::TaskPtr
            task = std::make_shared<search::Task>(context, file_ptr, general_query, types, hybrid_search_context);
        search::TaskInst::GetInstance().load_queue().push(task);
        search::TaskInst::GetInstance().load_cv().notify_one();
        hybrid_search_context->tasks_.emplace_back(task);
    }
#endif

    TimeRecorder rc("");

    // step 1: construct search job
    VectorsData vectors;
G
groot 已提交
2461 2462
    milvus::engine::meta::SegmentsSchema& files = files_holder.HoldFiles();
    LOG_ENGINE_DEBUG_ << LogOut("Engine query begin, index file count: %ld", files_holder.HoldFiles().size());
2463
    scheduler::SearchJobPtr job =
Y
yukun 已提交
2464
        std::make_shared<scheduler::SearchJob>(query_async_ctx, general_query, query_ptr, attr_type, vectors);
2465 2466 2467 2468 2469 2470 2471 2472 2473
    for (auto& file : files) {
        scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
        job->AddIndexFile(file_ptr);
    }

    // step 2: put search job to scheduler and wait result
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitResult();

G
groot 已提交
2474
    files_holder.ReleaseFiles();
2475 2476 2477 2478 2479
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
    }

    // step 3: construct results
Y
yukun 已提交
2480 2481 2482 2483 2484
    result.row_num_ = job->vector_count();
    result.result_ids_ = job->GetResultIds();
    result.result_distances_ = job->GetResultDistances();

    // step 4: get entities by result ids
2485
    auto status = GetEntitiesByID(collection_id, result.result_ids_, field_names, result.vectors_, result.attrs_);
Y
yukun 已提交
2486 2487 2488 2489 2490 2491
    if (!status.ok()) {
        query_async_ctx->GetTraceContext()->GetSpan()->Finish();
        return status;
    }

    // step 5: filter entities by field names
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
    //    std::vector<engine::AttrsData> filter_attrs;
    //    for (auto attr : result.attrs_) {
    //        AttrsData attrs_data;
    //        attrs_data.attr_type_ = attr.attr_type_;
    //        attrs_data.attr_count_ = attr.attr_count_;
    //        attrs_data.id_array_ = attr.id_array_;
    //        for (auto& name : field_names) {
    //            if (attr.attr_data_.find(name) != attr.attr_data_.end()) {
    //                attrs_data.attr_data_.insert(std::make_pair(name, attr.attr_data_.at(name)));
    //            }
    //        }
    //        filter_attrs.emplace_back(attrs_data);
    //    }
    //
    //    result.attrs_ = filter_attrs;
Y
yukun 已提交
2507

2508 2509 2510 2511 2512 2513 2514
    rc.ElapseFromBegin("Engine query totally cost");

    query_async_ctx->GetTraceContext()->GetSpan()->Finish();

    return Status::OK();
}

S
starlord 已提交
2515
void
G
groot 已提交
2516
DBImpl::BackgroundIndexThread() {
G
groot 已提交
2517
    SetThreadName("index_thread");
Y
yu yunfeng 已提交
2518
    server::SystemInfo::GetInstance().Init();
X
Xu Peng 已提交
2519
    while (true) {
2520
        if (!initialized_.load(std::memory_order_acquire)) {
2521 2522
            WaitMergeFileFinish();
            WaitBuildIndexFinish();
S
starlord 已提交
2523

2524
            LOG_ENGINE_DEBUG_ << "DB background thread exit";
G
groot 已提交
2525 2526
            break;
        }
X
Xu Peng 已提交
2527

G
groot 已提交
2528
        swn_index_.Wait_For(std::chrono::seconds(BACKGROUND_INDEX_INTERVAL));
X
Xu Peng 已提交
2529

G
groot 已提交
2530
        WaitMergeFileFinish();
G
groot 已提交
2531 2532
        StartBuildIndexTask();
    }
X
Xu Peng 已提交
2533 2534
}

S
starlord 已提交
2535 2536
void
DBImpl::WaitMergeFileFinish() {
2537
    //    LOG_ENGINE_DEBUG_ << "Begin WaitMergeFileFinish";
2538 2539
    std::lock_guard<std::mutex> lck(merge_result_mutex_);
    for (auto& iter : merge_thread_results_) {
2540 2541
        iter.wait();
    }
2542
    //    LOG_ENGINE_DEBUG_ << "End WaitMergeFileFinish";
2543 2544
}

S
starlord 已提交
2545 2546
void
DBImpl::WaitBuildIndexFinish() {
2547
    //    LOG_ENGINE_DEBUG_ << "Begin WaitBuildIndexFinish";
2548
    std::lock_guard<std::mutex> lck(index_result_mutex_);
Y
Yu Kun 已提交
2549
    for (auto& iter : index_thread_results_) {
2550 2551
        iter.wait();
    }
2552
    //    LOG_ENGINE_DEBUG_ << "End WaitBuildIndexFinish";
2553 2554
}

S
starlord 已提交
2555 2556
void
DBImpl::StartMetricTask() {
G
groot 已提交
2557
    server::Metrics::GetInstance().KeepingAliveCounterIncrement(BACKGROUND_METRIC_INTERVAL);
G
groot 已提交
2558 2559
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
S
shengjh 已提交
2560 2561
    fiu_do_on("DBImpl.StartMetricTask.InvalidTotalCache", cache_total = 0);

J
JinHai-CN 已提交
2562 2563 2564 2565 2566 2567 2568
    if (cache_total > 0) {
        double cache_usage_double = cache_usage;
        server::Metrics::GetInstance().CpuCacheUsageGaugeSet(cache_usage_double * 100 / cache_total);
    } else {
        server::Metrics::GetInstance().CpuCacheUsageGaugeSet(0);
    }

Y
Yu Kun 已提交
2569
    server::Metrics::GetInstance().GpuCacheUsageGaugeSet();
G
groot 已提交
2570 2571 2572 2573 2574 2575 2576 2577
    uint64_t size;
    Size(size);
    server::Metrics::GetInstance().DataFileSizeGaugeSet(size);
    server::Metrics::GetInstance().CPUUsagePercentSet();
    server::Metrics::GetInstance().RAMUsagePercentSet();
    server::Metrics::GetInstance().GPUPercentGaugeSet();
    server::Metrics::GetInstance().GPUMemoryUsageGaugeSet();
    server::Metrics::GetInstance().OctetsSet();
S
starlord 已提交
2578

K
kun yu 已提交
2579
    server::Metrics::GetInstance().CPUCoreUsagePercentSet();
K
kun yu 已提交
2580 2581
    server::Metrics::GetInstance().GPUTemperature();
    server::Metrics::GetInstance().CPUTemperature();
2582
    server::Metrics::GetInstance().PushToGateway();
G
groot 已提交
2583 2584
}

S
starlord 已提交
2585
void
G
groot 已提交
2586
DBImpl::StartMergeTask(const std::set<std::string>& merge_collection_ids, bool force_merge_all) {
2587
    // LOG_ENGINE_DEBUG_ << "Begin StartMergeTask";
2588
    // merge task has been finished?
2589
    {
2590 2591
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (!merge_thread_results_.empty()) {
2592
            std::chrono::milliseconds span(10);
2593 2594
            if (merge_thread_results_.back().wait_for(span) == std::future_status::ready) {
                merge_thread_results_.pop_back();
2595
            }
G
groot 已提交
2596 2597
        }
    }
X
Xu Peng 已提交
2598

2599
    // add new merge task
2600
    {
2601 2602
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (merge_thread_results_.empty()) {
2603
            // start merge file thread
2604
            merge_thread_results_.push_back(
G
groot 已提交
2605
                merge_thread_pool_.enqueue(&DBImpl::BackgroundMerge, this, merge_collection_ids, force_merge_all));
2606
        }
G
groot 已提交
2607
    }
2608

2609
    // LOG_ENGINE_DEBUG_ << "End StartMergeTask";
X
Xu Peng 已提交
2610 2611
}

Y
yukun 已提交
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
// Status
// DBImpl::MergeHybridFiles(const std::string& collection_id, meta::FilesHolder& files_holder) {
//    // const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
//
//    LOG_ENGINE_DEBUG_ << "Merge files for collection: " << collection_id;
//
//    // step 1: create table file
//    meta::SegmentSchema table_file;
//    table_file.collection_id_ = collection_id;
//    table_file.file_type_ = meta::SegmentSchema::NEW_MERGE;
//    Status status = meta_ptr_->CreateHybridCollectionFile(table_file);
//
//    if (!status.ok()) {
//        LOG_ENGINE_ERROR_ << "Failed to create collection: " << status.ToString();
//        return status;
//    }
//
//    // step 2: merge files
//    /*
//    ExecutionEnginePtr index =
//        EngineFactory::Build(table_file.dimension_, table_file.location_, (EngineType)table_file.engine_type_,
//                             (MetricType)table_file.metric_type_, table_file.nlist_);
//*/
//    meta::SegmentsSchema updated;
//
//    std::string new_segment_dir;
//    utils::GetParentPath(table_file.location_, new_segment_dir);
//    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);
//
//    // attention: here is a copy, not reference, since files_holder.UnmarkFile will change the array internal
//    milvus::engine::meta::SegmentsSchema files = files_holder.HoldFiles();
//    for (auto& file : files) {
//        server::CollectMergeFilesMetrics metrics;
//        std::string segment_dir_to_merge;
//        utils::GetParentPath(file.location_, segment_dir_to_merge);
//        segment_writer_ptr->Merge(segment_dir_to_merge, table_file.file_id_);
//
//        files_holder.UnmarkFile(file);
//
//        auto file_schema = file;
//        file_schema.file_type_ = meta::SegmentSchema::TO_DELETE;
//        updated.push_back(file_schema);
//        int64_t size = segment_writer_ptr->Size();
//        if (size >= file_schema.index_file_size_) {
//            break;
//        }
//    }
//
//    // step 3: serialize to disk
//    try {
//        status = segment_writer_ptr->Serialize();
//        fiu_do_on("DBImpl.MergeFiles.Serialize_ThrowException", throw std::exception());
//        fiu_do_on("DBImpl.MergeFiles.Serialize_ErrorStatus", status = Status(DB_ERROR, ""));
//    } catch (std::exception& ex) {
//        std::string msg = "Serialize merged index encounter exception: " + std::string(ex.what());
//        LOG_ENGINE_ERROR_ << msg;
//        status = Status(DB_ERROR, msg);
//    }
//
//    if (!status.ok()) {
//        LOG_ENGINE_ERROR_ << "Failed to persist merged segment: " << new_segment_dir << ". Error: " <<
//        status.message();
//
//        // if failed to serialize merge file to disk
//        // typical error: out of disk space, out of memory or permission denied
//        table_file.file_type_ = meta::SegmentSchema::TO_DELETE;
//        status = meta_ptr_->UpdateCollectionFile(table_file);
//        LOG_ENGINE_DEBUG_ << "Failed to update file to index, mark file: " << table_file.file_id_ << " to to_delete";
//
//        return status;
//    }
//
//    // step 4: update table files state
//    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
//    // else set file type to RAW, no need to build index
//    if (!utils::IsRawIndexType(table_file.engine_type_)) {
//        table_file.file_type_ = (segment_writer_ptr->Size() >= (size_t)(table_file.index_file_size_))
//                                    ? meta::SegmentSchema::TO_INDEX
//                                    : meta::SegmentSchema::RAW;
//    } else {
//        table_file.file_type_ = meta::SegmentSchema::RAW;
//    }
//    table_file.file_size_ = segment_writer_ptr->Size();
//    table_file.row_count_ = segment_writer_ptr->VectorCount();
//    updated.push_back(table_file);
//    status = meta_ptr_->UpdateCollectionFiles(updated);
//    LOG_ENGINE_DEBUG_ << "New merged segment " << table_file.segment_id_ << " of size " << segment_writer_ptr->Size()
//                      << " bytes";
//
//    if (options_.insert_cache_immediately_) {
//        segment_writer_ptr->Cache();
//    }
//
//    return status;
//}
2707

S
starlord 已提交
2708
void
G
groot 已提交
2709
DBImpl::BackgroundMerge(std::set<std::string> collection_ids, bool force_merge_all) {
2710
    // LOG_ENGINE_TRACE_ << " Background merge thread start";
S
starlord 已提交
2711

G
groot 已提交
2712
    Status status;
2713
    for (auto& collection_id : collection_ids) {
G
groot 已提交
2714 2715
        const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);

G
groot 已提交
2716 2717 2718 2719 2720
        auto old_strategy = merge_mgr_ptr_->Strategy();
        if (force_merge_all) {
            merge_mgr_ptr_->UseStrategy(MergeStrategyType::ADAPTIVE);
        }

G
groot 已提交
2721
        auto status = merge_mgr_ptr_->MergeFiles(collection_id);
G
groot 已提交
2722
        merge_mgr_ptr_->UseStrategy(old_strategy);
G
groot 已提交
2723
        if (!status.ok()) {
G
groot 已提交
2724 2725
            LOG_ENGINE_ERROR_ << "Failed to get merge files for collection: " << collection_id
                              << " reason:" << status.message();
G
groot 已提交
2726
        }
S
starlord 已提交
2727

2728
        if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2729
            LOG_ENGINE_DEBUG_ << "Server will shutdown, skip merge action for collection: " << collection_id;
S
starlord 已提交
2730 2731
            break;
        }
G
groot 已提交
2732
    }
X
Xu Peng 已提交
2733

G
groot 已提交
2734
    //    meta_ptr_->Archive();
Z
update  
zhiru 已提交
2735

2736
    {
G
groot 已提交
2737
        uint64_t timeout = (options_.file_cleanup_timeout_ >= 0) ? options_.file_cleanup_timeout_ : 10;
G
groot 已提交
2738
        uint64_t ttl = timeout * meta::SECOND;  // default: file will be hard-deleted few seconds after soft-deleted
2739
        meta_ptr_->CleanUpFilesWithTTL(ttl);
Z
update  
zhiru 已提交
2740
    }
S
starlord 已提交
2741

2742
    // LOG_ENGINE_TRACE_ << " Background merge thread exit";
G
groot 已提交
2743
}
X
Xu Peng 已提交
2744

S
starlord 已提交
2745
void
G
groot 已提交
2746
DBImpl::StartBuildIndexTask() {
S
starlord 已提交
2747
    // build index has been finished?
2748 2749 2750 2751 2752 2753 2754
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (!index_thread_results_.empty()) {
            std::chrono::milliseconds span(10);
            if (index_thread_results_.back().wait_for(span) == std::future_status::ready) {
                index_thread_results_.pop_back();
            }
G
groot 已提交
2755 2756 2757
        }
    }

S
starlord 已提交
2758
    // add new build index task
2759 2760 2761
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (index_thread_results_.empty()) {
S
starlord 已提交
2762
            index_thread_results_.push_back(index_thread_pool_.enqueue(&DBImpl::BackgroundBuildIndex, this));
2763
        }
G
groot 已提交
2764
    }
X
Xu Peng 已提交
2765 2766
}

S
starlord 已提交
2767 2768
void
DBImpl::BackgroundBuildIndex() {
P
peng.xu 已提交
2769
    std::unique_lock<std::mutex> lock(build_index_mutex_);
G
groot 已提交
2770 2771 2772
    meta::FilesHolder files_holder;
    meta_ptr_->FilesToIndex(files_holder);

G
groot 已提交
2773
    milvus::engine::meta::SegmentsSchema to_index_files = files_holder.HoldFiles();
2774
    Status status = index_failed_checker_.IgnoreFailedIndexFiles(to_index_files);
2775

2776
    if (!to_index_files.empty()) {
G
groot 已提交
2777
        LOG_ENGINE_DEBUG_ << "Background build index thread begin " << to_index_files.size() << " files";
2778

2779
        // step 2: put build index task to scheduler
J
Jin Hai 已提交
2780
        std::vector<std::pair<scheduler::BuildIndexJobPtr, scheduler::SegmentSchemaPtr>> job2file_map;
2781
        for (auto& file : to_index_files) {
G
groot 已提交
2782
            scheduler::BuildIndexJobPtr job = std::make_shared<scheduler::BuildIndexJob>(meta_ptr_, options_);
J
Jin Hai 已提交
2783
            scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
2784
            job->AddToIndexFiles(file_ptr);
G
groot 已提交
2785
            scheduler::JobMgrInst::GetInstance()->Put(job);
G
groot 已提交
2786
            job2file_map.push_back(std::make_pair(job, file_ptr));
2787
        }
G
groot 已提交
2788

G
groot 已提交
2789
        // step 3: wait build index finished and mark failed files
2790
        int64_t completed = 0;
G
groot 已提交
2791 2792
        for (auto iter = job2file_map.begin(); iter != job2file_map.end(); ++iter) {
            scheduler::BuildIndexJobPtr job = iter->first;
J
Jin Hai 已提交
2793
            meta::SegmentSchema& file_schema = *(iter->second.get());
G
groot 已提交
2794
            job->WaitBuildIndexFinish();
2795
            LOG_ENGINE_INFO_ << "Build Index Progress: " << ++completed << " of " << job2file_map.size();
G
groot 已提交
2796 2797
            if (!job->GetStatus().ok()) {
                Status status = job->GetStatus();
2798
                LOG_ENGINE_ERROR_ << "Building index job " << job->id() << " failed: " << status.ToString();
G
groot 已提交
2799

2800
                index_failed_checker_.MarkFailedIndexFile(file_schema, status.message());
G
groot 已提交
2801
            } else {
2802
                LOG_ENGINE_DEBUG_ << "Building index job " << job->id() << " succeed.";
G
groot 已提交
2803 2804

                index_failed_checker_.MarkSucceedIndexFile(file_schema);
G
groot 已提交
2805
            }
G
groot 已提交
2806 2807
            status = files_holder.UnmarkFile(file_schema);
            LOG_ENGINE_DEBUG_ << "Finish build index file " << file_schema.file_id_;
2808
        }
G
groot 已提交
2809

2810
        LOG_ENGINE_DEBUG_ << "Background build index thread finished";
G
groot 已提交
2811
        index_req_swn_.Notify();  // notify CreateIndex check circle
Y
Yu Kun 已提交
2812
    }
X
Xu Peng 已提交
2813 2814
}

G
groot 已提交
2815
Status
J
Jin Hai 已提交
2816
DBImpl::GetFilesToBuildIndex(const std::string& collection_id, const std::vector<int>& file_types,
G
groot 已提交
2817 2818 2819
                             meta::FilesHolder& files_holder) {
    files_holder.ReleaseFiles();
    auto status = meta_ptr_->FilesByType(collection_id, file_types, files_holder);
G
groot 已提交
2820

G
groot 已提交
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
    // attention: here is a copy, not reference, since files_holder.UnmarkFile will change the array internal
    milvus::engine::meta::SegmentsSchema files = files_holder.HoldFiles();
    for (const milvus::engine::meta::SegmentSchema& file : files) {
        if (file.file_type_ == static_cast<int>(meta::SegmentSchema::RAW) &&
            file.row_count_ < meta::BUILD_INDEX_THRESHOLD) {
            // skip build index for files that row count less than certain threshold
            files_holder.UnmarkFile(file);
        } else if (index_failed_checker_.IsFailedIndexFile(file)) {
            // skip build index for files that failed before
            files_holder.UnmarkFile(file);
        }
G
groot 已提交
2832 2833 2834 2835 2836
    }

    return Status::OK();
}

2837
Status
J
Jin Hai 已提交
2838 2839
DBImpl::GetPartitionByTag(const std::string& collection_id, const std::string& partition_tag,
                          std::string& partition_name) {
2840 2841 2842
    Status status;

    if (partition_tag.empty()) {
J
Jin Hai 已提交
2843
        partition_name = collection_id;
2844 2845 2846 2847 2848

    } else {
        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = partition_tag;
2849
        StringHelpFunctions::TrimStringBlank(valid_tag);
2850 2851

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
2852
            partition_name = collection_id;
2853 2854 2855
            return status;
        }

J
Jin Hai 已提交
2856
        status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
2857
        if (!status.ok()) {
2858
            LOG_ENGINE_ERROR_ << status.message();
2859 2860 2861 2862 2863 2864
        }
    }

    return status;
}

G
groot 已提交
2865
Status
J
Jin Hai 已提交
2866
DBImpl::GetPartitionsByTags(const std::string& collection_id, const std::vector<std::string>& partition_tags,
G
groot 已提交
2867
                            std::set<std::string>& partition_name_array) {
J
Jin Hai 已提交
2868 2869
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2870 2871

    for (auto& tag : partition_tags) {
2872 2873 2874
        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = tag;
2875
        StringHelpFunctions::TrimStringBlank(valid_tag);
2876 2877

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
2878
            partition_name_array.insert(collection_id);
2879 2880 2881
            return status;
        }

G
groot 已提交
2882
        for (auto& schema : partition_array) {
2883
            if (StringHelpFunctions::IsRegexMatch(schema.partition_tag_, valid_tag)) {
J
Jin Hai 已提交
2884
                partition_name_array.insert(schema.collection_id_);
G
groot 已提交
2885 2886 2887 2888
            }
        }
    }

T
Tinkerrr 已提交
2889
    if (partition_name_array.empty()) {
G
groot 已提交
2890
        return Status(DB_PARTITION_NOT_FOUND, "The specified partiton does not exist");
T
Tinkerrr 已提交
2891 2892
    }

G
groot 已提交
2893 2894 2895 2896
    return Status::OK();
}

Status
2897
DBImpl::UpdateCollectionIndexRecursively(const std::string& collection_id, const CollectionIndex& index) {
J
Jin Hai 已提交
2898
    DropIndex(collection_id);
G
groot 已提交
2899
    WaitMergeFileFinish();  // DropIndex called StartMergeTask, need to wait merge thread finish
2900 2901
    auto status = meta_ptr_->UpdateCollectionIndex(collection_id, index);
    fiu_do_on("DBImpl.UpdateCollectionIndexRecursively.fail_update_collection_index",
S
shengjh 已提交
2902
              status = Status(DB_META_TRANSACTION_FAILED, ""));
G
groot 已提交
2903
    if (!status.ok()) {
2904
        LOG_ENGINE_ERROR_ << "Failed to update collection index info for collection: " << collection_id;
G
groot 已提交
2905 2906 2907
        return status;
    }

J
Jin Hai 已提交
2908 2909
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
A
AzAz 已提交
2910 2911 2912
    if (!status.ok()) {
        return status;
    }
G
groot 已提交
2913
    for (auto& schema : partition_array) {
2914
        status = UpdateCollectionIndexRecursively(schema.collection_id_, index);
G
groot 已提交
2915 2916 2917 2918 2919 2920 2921 2922 2923
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
G
groot 已提交
2924 2925
DBImpl::WaitCollectionIndexRecursively(const std::shared_ptr<server::Context>& context,
                                       const std::string& collection_id, const CollectionIndex& index) {
G
groot 已提交
2926 2927 2928
    // for IDMAP type, only wait all NEW file converted to RAW file
    // for other type, wait NEW/RAW/NEW_MERGE/NEW_INDEX/TO_INDEX files converted to INDEX files
    std::vector<int> file_types;
G
groot 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
    //    if (utils::IsRawIndexType(index.engine_type_)) {
    //        file_types = {
    //            static_cast<int32_t>(meta::SegmentSchema::NEW),
    //            static_cast<int32_t>(meta::SegmentSchema::NEW_MERGE),
    //        };
    //    } else {
    //        file_types = {
    //            static_cast<int32_t>(meta::SegmentSchema::RAW),       static_cast<int32_t>(meta::SegmentSchema::NEW),
    //            static_cast<int32_t>(meta::SegmentSchema::NEW_MERGE),
    //            static_cast<int32_t>(meta::SegmentSchema::NEW_INDEX),
    //            static_cast<int32_t>(meta::SegmentSchema::TO_INDEX),
    //        };
    //    }
G
groot 已提交
2942 2943

    // get files to build index
G
groot 已提交
2944 2945 2946 2947
    {
        meta::FilesHolder files_holder;
        auto status = GetFilesToBuildIndex(collection_id, file_types, files_holder);
        int times = 1;
G
groot 已提交
2948
        uint64_t repeat = 0;
G
groot 已提交
2949
        while (!files_holder.HoldFiles().empty()) {
G
groot 已提交
2950 2951 2952
            if (repeat % WAIT_BUILD_INDEX_INTERVAL == 0) {
                LOG_ENGINE_DEBUG_ << files_holder.HoldFiles().size() << " non-index files detected! Will build index "
                                  << times;
G
groot 已提交
2953 2954 2955
                //                if (!utils::IsRawIndexType(index.engine_type_)) {
                //                    status = meta_ptr_->UpdateCollectionFilesToIndex(collection_id);
                //                }
G
groot 已提交
2956
            }
G
groot 已提交
2957

G
groot 已提交
2958 2959 2960
            index_req_swn_.Wait_For(std::chrono::seconds(1));

            // client break the connection, no need to block, check every 1 second
G
groot 已提交
2961
            if (context && context->IsConnectionBroken()) {
G
groot 已提交
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
                LOG_ENGINE_DEBUG_ << "Client connection broken, build index in background";
                break;  // just break, not return, continue to update partitions files to to_index
            }

            // check to_index files every 5 seconds
            repeat++;
            if (repeat % WAIT_BUILD_INDEX_INTERVAL == 0) {
                GetFilesToBuildIndex(collection_id, file_types, files_holder);
                ++times;
            }
G
groot 已提交
2972 2973 2974 2975
        }
    }

    // build index for partition
J
Jin Hai 已提交
2976
    std::vector<meta::CollectionSchema> partition_array;
G
groot 已提交
2977
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2978
    for (auto& schema : partition_array) {
G
groot 已提交
2979
        status = WaitCollectionIndexRecursively(context, schema.collection_id_, index);
2980
        fiu_do_on("DBImpl.WaitCollectionIndexRecursively.fail_build_collection_Index_for_partition",
S
shengjh 已提交
2981
                  status = Status(DB_ERROR, ""));
G
groot 已提交
2982 2983 2984 2985 2986
        if (!status.ok()) {
            return status;
        }
    }

G
groot 已提交
2987
    // failed to build index for some files, return error
2988
    std::string err_msg;
2989 2990
    index_failed_checker_.GetErrMsgForCollection(collection_id, err_msg);
    fiu_do_on("DBImpl.WaitCollectionIndexRecursively.not_empty_err_msg", err_msg.append("fiu"));
2991 2992
    if (!err_msg.empty()) {
        return Status(DB_ERROR, err_msg);
G
groot 已提交
2993 2994
    }

G
groot 已提交
2995 2996
    LOG_ENGINE_DEBUG_ << "WaitCollectionIndexRecursively finished";

G
groot 已提交
2997 2998 2999 3000
    return Status::OK();
}

Status
3001
DBImpl::DropCollectionIndexRecursively(const std::string& collection_id) {
3002
    LOG_ENGINE_DEBUG_ << "Drop index for collection: " << collection_id;
3003 3004
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
    auto status = meta_ptr_->DropCollectionIndex(collection_id);
G
groot 已提交
3005 3006 3007 3008 3009
    if (!status.ok()) {
        return status;
    }

    // drop partition index
J
Jin Hai 已提交
3010 3011
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
3012
    for (auto& schema : partition_array) {
3013 3014
        status = DropCollectionIndexRecursively(schema.collection_id_);
        fiu_do_on("DBImpl.DropCollectionIndexRecursively.fail_drop_collection_Index_for_partition",
S
shengjh 已提交
3015
                  status = Status(DB_ERROR, ""));
G
groot 已提交
3016 3017 3018 3019 3020 3021 3022 3023 3024
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
3025
DBImpl::GetCollectionRowCountRecursively(const std::string& collection_id, uint64_t& row_count) {
G
groot 已提交
3026
    row_count = 0;
J
Jin Hai 已提交
3027
    auto status = meta_ptr_->Count(collection_id, row_count);
G
groot 已提交
3028 3029 3030 3031 3032
    if (!status.ok()) {
        return status;
    }

    // get partition row count
J
Jin Hai 已提交
3033 3034
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
3035
    for (auto& schema : partition_array) {
G
groot 已提交
3036
        uint64_t partition_row_count = 0;
3037 3038
        status = GetCollectionRowCountRecursively(schema.collection_id_, partition_row_count);
        fiu_do_on("DBImpl.GetCollectionRowCountRecursively.fail_get_collection_rowcount_for_partition",
S
shengjh 已提交
3039
                  status = Status(DB_ERROR, ""));
G
groot 已提交
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
        if (!status.ok()) {
            return status;
        }

        row_count += partition_row_count;
    }

    return Status::OK();
}

3050 3051 3052 3053
Status
DBImpl::ExecWalRecord(const wal::MXLogRecord& record) {
    fiu_return_on("DBImpl.ExexWalRecord.return", Status(););

G
groot 已提交
3054 3055
    auto collections_flushed = [&](const std::string collection_id,
                                   const std::set<std::string>& target_collection_names) -> uint64_t {
3056
        uint64_t max_lsn = 0;
G
groot 已提交
3057
        if (options_.wal_enable_ && !target_collection_names.empty()) {
G
groot 已提交
3058 3059
            uint64_t lsn = 0;
            for (auto& collection : target_collection_names) {
3060
                meta_ptr_->GetCollectionFlushLSN(collection, lsn);
3061 3062 3063 3064
                if (lsn > max_lsn) {
                    max_lsn = lsn;
                }
            }
G
groot 已提交
3065
            wal_mgr_->CollectionFlushed(collection_id, lsn);
3066 3067
        }

G
groot 已提交
3068
        std::set<std::string> merge_collection_ids;
G
groot 已提交
3069
        for (auto& collection : target_collection_names) {
G
groot 已提交
3070
            merge_collection_ids.insert(collection);
3071
        }
G
groot 已提交
3072
        StartMergeTask(merge_collection_ids);
3073 3074 3075
        return max_lsn;
    };

G
groot 已提交
3076 3077 3078 3079
    auto force_flush_if_mem_full = [&]() -> uint64_t {
        if (mem_mgr_->GetCurrentMem() > options_.insert_buffer_size_) {
            LOG_ENGINE_DEBUG_ << LogOut("[%s][%ld] ", "insert", 0) << "Insert buffer size exceeds limit. Force flush";
            InternalFlush();
G
groot 已提交
3080 3081 3082
        }
    };

3083 3084 3085
    Status status;

    switch (record.type) {
3086 3087 3088 3089
        case wal::MXLogType::Entity: {
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
            if (!status.ok()) {
3090
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
3091 3092 3093
                return status;
            }

G
groot 已提交
3094 3095 3096 3097
            status = mem_mgr_->InsertEntities(
                target_collection_name, record.length, record.ids, (record.data_size / record.length / sizeof(float)),
                (const float*)record.data, record.attr_nbytes, record.attr_data_size, record.attr_data, record.lsn);
            force_flush_if_mem_full();
3098

G
groot 已提交
3099
            // metrics
3100 3101 3102
            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }
3103
        case wal::MXLogType::InsertBinary: {
3104 3105
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
3106
            if (!status.ok()) {
3107
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
3108 3109 3110
                return status;
            }

3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
            Vectors vectors;
            vectors.vector_type_ = Vectors::BINARY;
            vectors.binary_vector = (const uint8_t*)record.data;
            status = mem_mgr_->InsertEntities(target_collection_name, record.length, record.ids,
                                              (record.data_size / record.length / sizeof(uint8_t)), vectors,
                                              record.attr_nbytes, record.attr_data_size, record.attr_data, record.lsn);

            //            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
            //                                             (record.data_size / record.length / sizeof(uint8_t)),
            //                                             (const u_int8_t*)record.data, record.lsn);
G
groot 已提交
3121
            force_flush_if_mem_full();
3122 3123 3124 3125 3126 3127 3128

            // metrics
            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }

        case wal::MXLogType::InsertVector: {
3129 3130
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
3131
            if (!status.ok()) {
3132
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
3133 3134 3135
                return status;
            }

3136 3137 3138 3139 3140 3141 3142 3143 3144 3145
            Vectors vectors;
            vectors.vector_type_ = Vectors::FLOAT;
            vectors.float_vector = (const float*)record.data;
            status = mem_mgr_->InsertEntities(target_collection_name, record.length, record.ids,
                                              (record.data_size / record.length / sizeof(float)), vectors,
                                              record.attr_nbytes, record.attr_data_size, record.attr_data, record.lsn);

            //            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
            //                                             (record.data_size / record.length / sizeof(float)),
            //                                             (const float*)record.data, record.lsn);
G
groot 已提交
3146
            force_flush_if_mem_full();
3147 3148 3149 3150 3151 3152 3153

            // metrics
            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }

        case wal::MXLogType::Delete: {
J
Jin Hai 已提交
3154 3155
            std::vector<meta::CollectionSchema> partition_array;
            status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
3156 3157 3158 3159
            if (!status.ok()) {
                return status;
            }

3160
            std::vector<std::string> collection_ids{record.collection_id};
3161
            for (auto& partition : partition_array) {
3162 3163
                auto& partition_collection_id = partition.collection_id_;
                collection_ids.emplace_back(partition_collection_id);
3164 3165 3166
            }

            if (record.length == 1) {
3167
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
3168
                    status = mem_mgr_->DeleteVector(collection_id, *record.ids, record.lsn);
3169 3170 3171 3172 3173
                    if (!status.ok()) {
                        return status;
                    }
                }
            } else {
3174
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
3175
                    status = mem_mgr_->DeleteVectors(collection_id, record.length, record.ids, record.lsn);
3176 3177 3178 3179 3180 3181 3182 3183 3184
                    if (!status.ok()) {
                        return status;
                    }
                }
            }
            break;
        }

        case wal::MXLogType::Flush: {
J
Jin Hai 已提交
3185 3186 3187 3188
            if (!record.collection_id.empty()) {
                // flush one collection
                std::vector<meta::CollectionSchema> partition_array;
                status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
3189 3190 3191 3192
                if (!status.ok()) {
                    return status;
                }

3193
                std::vector<std::string> collection_ids{record.collection_id};
3194
                for (auto& partition : partition_array) {
3195 3196
                    auto& partition_collection_id = partition.collection_id_;
                    collection_ids.emplace_back(partition_collection_id);
3197 3198
                }

3199 3200
                std::set<std::string> flushed_collections;
                for (auto& collection_id : collection_ids) {
3201
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
J
Jin Hai 已提交
3202
                    status = mem_mgr_->Flush(collection_id);
3203 3204 3205
                    if (!status.ok()) {
                        break;
                    }
3206
                    flushed_collections.insert(collection_id);
3207 3208
                }

G
groot 已提交
3209
                collections_flushed(record.collection_id, flushed_collections);
3210 3211

            } else {
3212 3213
                // flush all collections
                std::set<std::string> collection_ids;
3214 3215
                {
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
3216
                    status = mem_mgr_->Flush(collection_ids);
3217 3218
                }

G
groot 已提交
3219
                uint64_t lsn = collections_flushed("", collection_ids);
3220 3221 3222 3223 3224 3225
                if (options_.wal_enable_) {
                    wal_mgr_->RemoveOldFiles(lsn);
                }
            }
            break;
        }
C
Cai Yudong 已提交
3226 3227 3228

        default:
            break;
3229 3230 3231 3232 3233 3234
    }

    return status;
}

void
G
groot 已提交
3235 3236 3237 3238 3239 3240 3241 3242 3243
DBImpl::InternalFlush(const std::string& collection_id) {
    wal::MXLogRecord record;
    record.type = wal::MXLogType::Flush;
    record.collection_id = collection_id;
    ExecWalRecord(record);
}

void
DBImpl::BackgroundWalThread() {
3244
    SetThreadName("wal_thread");
3245 3246
    server::SystemInfo::GetInstance().Init();

3247
    std::chrono::system_clock::time_point next_auto_flush_time;
3248
    auto get_next_auto_flush_time = [&]() {
3249
        return std::chrono::system_clock::now() + std::chrono::seconds(options_.auto_flush_interval_);
3250
    };
3251 3252 3253
    if (options_.auto_flush_interval_ > 0) {
        next_auto_flush_time = get_next_auto_flush_time();
    }
3254

G
groot 已提交
3255
    InternalFlush();
3256
    while (true) {
3257 3258
        if (options_.auto_flush_interval_ > 0) {
            if (std::chrono::system_clock::now() >= next_auto_flush_time) {
G
groot 已提交
3259
                InternalFlush();
3260 3261
                next_auto_flush_time = get_next_auto_flush_time();
            }
3262 3263
        }

G
groot 已提交
3264
        wal::MXLogRecord record;
3265
        auto error_code = wal_mgr_->GetNextEntityRecord(record);
3266
        if (error_code != WAL_SUCCESS) {
3267
            LOG_ENGINE_ERROR_ << "WAL background GetNextEntityRecord error";
3268 3269 3270 3271 3272 3273
            break;
        }

        if (record.type != wal::MXLogType::None) {
            ExecWalRecord(record);
            if (record.type == wal::MXLogType::Flush) {
G
groot 已提交
3274 3275
                // notify flush request to return
                flush_req_swn_.Notify();
3276 3277

                // if user flush all manually, update auto flush also
J
Jin Hai 已提交
3278
                if (record.collection_id.empty() && options_.auto_flush_interval_ > 0) {
3279 3280 3281 3282 3283 3284
                    next_auto_flush_time = get_next_auto_flush_time();
                }
            }

        } else {
            if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
3285 3286
                InternalFlush();
                flush_req_swn_.Notify();
3287 3288
                WaitMergeFileFinish();
                WaitBuildIndexFinish();
3289
                LOG_ENGINE_DEBUG_ << "WAL background thread exit";
3290 3291 3292
                break;
            }

3293
            if (options_.auto_flush_interval_ > 0) {
G
groot 已提交
3294
                swn_wal_.Wait_Until(next_auto_flush_time);
3295
            } else {
G
groot 已提交
3296
                swn_wal_.Wait();
3297
            }
3298 3299 3300 3301
        }
    }
}

G
groot 已提交
3302 3303
void
DBImpl::BackgroundFlushThread() {
3304
    SetThreadName("flush_thread");
G
groot 已提交
3305 3306 3307
    server::SystemInfo::GetInstance().Init();
    while (true) {
        if (!initialized_.load(std::memory_order_acquire)) {
3308
            LOG_ENGINE_DEBUG_ << "DB background flush thread exit";
G
groot 已提交
3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
            break;
        }

        InternalFlush();
        if (options_.auto_flush_interval_ > 0) {
            swn_flush_.Wait_For(std::chrono::seconds(options_.auto_flush_interval_));
        } else {
            swn_flush_.Wait();
        }
    }
}

void
DBImpl::BackgroundMetricThread() {
G
groot 已提交
3323
    SetThreadName("metric_thread");
G
groot 已提交
3324 3325 3326
    server::SystemInfo::GetInstance().Init();
    while (true) {
        if (!initialized_.load(std::memory_order_acquire)) {
3327
            LOG_ENGINE_DEBUG_ << "DB background metric thread exit";
G
groot 已提交
3328 3329 3330 3331 3332
            break;
        }

        swn_metric_.Wait_For(std::chrono::seconds(BACKGROUND_METRIC_INTERVAL));
        StartMetricTask();
G
groot 已提交
3333
        meta::FilesHolder::PrintInfo();
G
groot 已提交
3334 3335 3336
    }
}

3337
void
W
Wang XiangYu 已提交
3338 3339 3340
DBImpl::ConfigUpdate(const std::string& name) {
    options_.insert_cache_immediately_ = config.cache.cache_insert_data();
    faiss::distance_compute_blas_threshold = config.engine.use_blas_threshold();
3341 3342
}

3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360
void
DBImpl::SuspendIfFirst() {
    std::lock_guard<std::mutex> lock(suspend_build_mutex_);
    if (++live_search_num_ == 1) {
        LOG_ENGINE_TRACE_ << "live_search_num_: " << live_search_num_;
        knowhere::BuilderSuspend();
    }
}

void
DBImpl::ResumeIfLast() {
    std::lock_guard<std::mutex> lock(suspend_build_mutex_);
    if (--live_search_num_ == 0) {
        LOG_ENGINE_TRACE_ << "live_search_num_: " << live_search_num_;
        knowhere::BuildResume();
    }
}

S
starlord 已提交
3361 3362
}  // namespace engine
}  // namespace milvus