DBImpl.cpp 72.8 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 17 18 19 20

#include <algorithm>
#include <boost/filesystem.hpp>
#include <chrono>
#include <cstring>
21
#include <functional>
Z
Zhiru Zhu 已提交
22
#include <iostream>
23
#include <limits>
Z
Zhiru Zhu 已提交
24 25 26 27
#include <set>
#include <thread>
#include <utility>

S
starlord 已提交
28
#include "Utils.h"
S
starlord 已提交
29 30
#include "cache/CpuCacheMgr.h"
#include "cache/GpuCacheMgr.h"
31
#include "db/IDGenerator.h"
S
starlord 已提交
32
#include "engine/EngineFactory.h"
33
#include "index/thirdparty/faiss/utils/distances.h"
S
starlord 已提交
34
#include "insert/MemMenagerFactory.h"
S
starlord 已提交
35
#include "meta/MetaConsts.h"
S
starlord 已提交
36 37
#include "meta/MetaFactory.h"
#include "meta/SqliteMetaImpl.h"
G
groot 已提交
38
#include "metrics/Metrics.h"
S
starlord 已提交
39
#include "scheduler/SchedInst.h"
Y
Yu Kun 已提交
40
#include "scheduler/job/BuildIndexJob.h"
S
starlord 已提交
41 42
#include "scheduler/job/DeleteJob.h"
#include "scheduler/job/SearchJob.h"
43 44 45
#include "segment/SegmentReader.h"
#include "segment/SegmentWriter.h"
#include "utils/Exception.h"
S
starlord 已提交
46
#include "utils/Log.h"
G
groot 已提交
47
#include "utils/StringHelpFunctions.h"
S
starlord 已提交
48
#include "utils/TimeRecorder.h"
49 50
#include "utils/ValidationUtil.h"
#include "wal/WalDefinations.h"
X
Xu Peng 已提交
51

J
jinhai 已提交
52
namespace milvus {
X
Xu Peng 已提交
53
namespace engine {
X
Xu Peng 已提交
54

G
groot 已提交
55 56
namespace {

J
jinhai 已提交
57 58 59
constexpr uint64_t METRIC_ACTION_INTERVAL = 1;
constexpr uint64_t COMPACT_ACTION_INTERVAL = 1;
constexpr uint64_t INDEX_ACTION_INTERVAL = 1;
G
groot 已提交
60

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

S
starlord 已提交
63
}  // namespace
G
groot 已提交
64

Y
Yu Kun 已提交
65
DBImpl::DBImpl(const DBOptions& options)
66
    : options_(options), initialized_(false), merge_thread_pool_(1, 1), index_thread_pool_(1, 1) {
S
starlord 已提交
67
    meta_ptr_ = MetaFactory::Build(options.meta_, options.mode_);
Z
zhiru 已提交
68
    mem_mgr_ = MemManagerFactory::Build(meta_ptr_, options_);
69 70 71 72 73 74 75 76 77 78

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

79 80
    SetIdentity("DBImpl");
    AddCacheInsertDataListener();
81
    AddUseBlasThresholdListener();
82

S
starlord 已提交
83 84 85 86 87 88 89
    Start();
}

DBImpl::~DBImpl() {
    Stop();
}

S
starlord 已提交
90
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
91
// external api
S
starlord 已提交
92
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
93 94
Status
DBImpl::Start() {
95
    if (initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
96 97 98
        return Status::OK();
    }

S
Shouyu Luo 已提交
99
    // ENGINE_LOG_TRACE << "DB service start";
100
    initialized_.store(true, std::memory_order_release);
S
starlord 已提交
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    // 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;
            auto error_code = wal_mgr_->GetNextRecovery(record);
            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) {
            // background thread
            bg_wal_thread_ = std::thread(&DBImpl::BackgroundWalTask, this);
        }

    } else {
        // for distribute version, some nodes are read only
        if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
            // ENGINE_LOG_TRACE << "StartTimerTasks";
            bg_timer_thread_ = std::thread(&DBImpl::BackgroundTimerTask, this);
        }
Z
update  
zhiru 已提交
138
    }
S
starlord 已提交
139

S
starlord 已提交
140 141 142
    return Status::OK();
}

S
starlord 已提交
143 144
Status
DBImpl::Stop() {
145
    if (!initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
146 147
        return Status::OK();
    }
148

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

151 152 153
    if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        if (options_.wal_enable_) {
            // wait flush merge/buildindex finish
154
            bg_task_swn_.Notify();
155
            bg_wal_thread_.join();
S
starlord 已提交
156

157 158 159 160 161 162 163
        } else {
            // flush all
            wal::MXLogRecord record;
            record.type = wal::MXLogType::Flush;
            ExecWalRecord(record);

            // wait merge/buildindex finish
164
            bg_task_swn_.Notify();
165 166
            bg_timer_thread_.join();
        }
S
starlord 已提交
167

168
        meta_ptr_->CleanUpShadowFiles();
S
starlord 已提交
169 170
    }

S
Shouyu Luo 已提交
171
    // ENGINE_LOG_TRACE << "DB service stop";
S
starlord 已提交
172
    return Status::OK();
X
Xu Peng 已提交
173 174
}

S
starlord 已提交
175 176
Status
DBImpl::DropAll() {
S
starlord 已提交
177 178 179
    return meta_ptr_->DropAll();
}

S
starlord 已提交
180
Status
181
DBImpl::CreateCollection(meta::CollectionSchema& collection_schema) {
182
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
183
        return SHUTDOWN_ERROR;
S
starlord 已提交
184 185
    }

186
    meta::CollectionSchema temp_schema = collection_schema;
S
starlord 已提交
187
    temp_schema.index_file_size_ *= ONE_MB;  // store as MB
188
    if (options_.wal_enable_) {
189
        temp_schema.flush_lsn_ = wal_mgr_->CreateCollection(collection_schema.collection_id_);
190 191
    }

192
    return meta_ptr_->CreateCollection(temp_schema);
193 194
}

S
starlord 已提交
195
Status
196
DBImpl::DropCollection(const std::string& collection_id) {
197
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
198
        return SHUTDOWN_ERROR;
S
starlord 已提交
199 200
    }

201
    if (options_.wal_enable_) {
202
        wal_mgr_->DropCollection(collection_id);
203 204
    }

205
    return DropCollectionRecursively(collection_id);
G
groot 已提交
206 207
}

S
starlord 已提交
208
Status
209
DBImpl::DescribeCollection(meta::CollectionSchema& collection_schema) {
210
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
211
        return SHUTDOWN_ERROR;
S
starlord 已提交
212 213
    }

214 215
    auto stat = meta_ptr_->DescribeCollection(collection_schema);
    collection_schema.index_file_size_ /= ONE_MB;  // return as MB
S
starlord 已提交
216
    return stat;
217 218
}

S
starlord 已提交
219
Status
220
DBImpl::HasCollection(const std::string& collection_id, bool& has_or_not) {
221
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
222
        return SHUTDOWN_ERROR;
S
starlord 已提交
223 224
    }

225
    return meta_ptr_->HasCollection(collection_id, has_or_not);
226 227
}

228
Status
229
DBImpl::HasNativeCollection(const std::string& collection_id, bool& has_or_not_) {
230 231 232 233
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

234 235 236
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
237 238 239 240
    if (!status.ok()) {
        has_or_not_ = false;
        return status;
    } else {
241
        if (!collection_schema.owner_collection_.empty()) {
242 243 244 245 246 247 248 249 250
            has_or_not_ = false;
            return Status(DB_NOT_FOUND, "");
        }

        has_or_not_ = true;
        return Status::OK();
    }
}

S
starlord 已提交
251
Status
252
DBImpl::AllCollections(std::vector<meta::CollectionSchema>& collection_schema_array) {
253
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
254
        return SHUTDOWN_ERROR;
S
starlord 已提交
255 256
    }

257 258
    std::vector<meta::CollectionSchema> all_collections;
    auto status = meta_ptr_->AllCollections(all_collections);
259

260 261 262 263 264
    // only return real collections, dont return partition collections
    collection_schema_array.clear();
    for (auto& schema : all_collections) {
        if (schema.owner_collection_.empty()) {
            collection_schema_array.push_back(schema);
265 266 267 268
        }
    }

    return status;
G
groot 已提交
269 270
}

271
Status
272
DBImpl::GetCollectionInfo(const std::string& collection_id, CollectionInfo& collection_info) {
273 274 275 276 277
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // step1: get all partition ids
J
Jin Hai 已提交
278 279 280
    std::vector<std::pair<std::string, std::string>> name2tag = {{collection_id, milvus::engine::DEFAULT_PARTITON_TAG}};
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
281
    for (auto& schema : partition_array) {
J
Jin Hai 已提交
282
        name2tag.push_back(std::make_pair(schema.collection_id_, schema.partition_tag_));
283 284
    }

J
Jin Hai 已提交
285 286 287
    // step2: get native collection info
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::INDEX};
288 289 290 291 292 293

    static std::map<int32_t, std::string> index_type_name = {
        {(int32_t)engine::EngineType::FAISS_IDMAP, "IDMAP"},
        {(int32_t)engine::EngineType::FAISS_IVFFLAT, "IVFFLAT"},
        {(int32_t)engine::EngineType::FAISS_IVFSQ8, "IVFSQ8"},
        {(int32_t)engine::EngineType::NSG_MIX, "NSG"},
O
op-hunter 已提交
294
        {(int32_t)engine::EngineType::ANNOY, "ANNOY"},
295 296 297 298 299 300 301 302 303
        {(int32_t)engine::EngineType::FAISS_IVFSQ8H, "IVFSQ8H"},
        {(int32_t)engine::EngineType::FAISS_PQ, "PQ"},
        {(int32_t)engine::EngineType::SPTAG_KDT, "KDT"},
        {(int32_t)engine::EngineType::SPTAG_BKT, "BKT"},
        {(int32_t)engine::EngineType::FAISS_BIN_IDMAP, "IDMAP"},
        {(int32_t)engine::EngineType::FAISS_BIN_IVFFLAT, "IVFFLAT"},
    };

    for (auto& name_tag : name2tag) {
304 305
        meta::SegmentsSchema collection_files;
        status = meta_ptr_->FilesByType(name_tag.first, file_types, collection_files);
306
        if (!status.ok()) {
J
Jin Hai 已提交
307
            std::string err_msg = "Failed to get collection info: " + status.ToString();
308 309 310 311 312
            ENGINE_LOG_ERROR << err_msg;
            return Status(DB_ERROR, err_msg);
        }

        std::vector<SegmentStat> segments_stat;
313
        for (auto& file : collection_files) {
314 315 316 317 318 319 320 321 322
            SegmentStat seg_stat;
            seg_stat.name_ = file.segment_id_;
            seg_stat.row_count_ = (int64_t)file.row_count_;
            seg_stat.index_name_ = index_type_name[file.engine_type_];
            seg_stat.data_size_ = (int64_t)file.file_size_;
            segments_stat.emplace_back(seg_stat);
        }

        PartitionStat partition_stat;
J
Jin Hai 已提交
323
        if (name_tag.first == collection_id) {
324 325 326 327 328 329
            partition_stat.tag_ = milvus::engine::DEFAULT_PARTITON_TAG;
        } else {
            partition_stat.tag_ = name_tag.second;
        }

        partition_stat.segments_stat_.swap(segments_stat);
330
        collection_info.partitions_stat_.emplace_back(partition_stat);
331 332 333 334 335
    }

    return Status::OK();
}

S
starlord 已提交
336
Status
337
DBImpl::PreloadCollection(const std::string& collection_id) {
338
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
339
        return SHUTDOWN_ERROR;
S
starlord 已提交
340 341
    }

J
Jin Hai 已提交
342 343 344
    // step 1: get all collection files from parent collection
    meta::SegmentsSchema files_array;
    auto status = GetFilesToSearch(collection_id, files_array);
Y
Yu Kun 已提交
345 346 347
    if (!status.ok()) {
        return status;
    }
Y
Yu Kun 已提交
348

349
    // step 2: get files from partition collections
J
Jin Hai 已提交
350 351
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
352
    for (auto& schema : partition_array) {
J
Jin Hai 已提交
353
        status = GetFilesToSearch(schema.collection_id_, files_array);
G
groot 已提交
354 355
    }

Y
Yu Kun 已提交
356 357
    int64_t size = 0;
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
Y
Yu Kun 已提交
358 359
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t available_size = cache_total - cache_usage;
Y
Yu Kun 已提交
360

361
    // step 3: load file one by one
J
Jin Hai 已提交
362
    ENGINE_LOG_DEBUG << "Begin pre-load collection:" + collection_id + ", totally " << files_array.size()
363
                     << " files need to be pre-loaded";
J
Jin Hai 已提交
364
    TimeRecorderAuto rc("Pre-load collection:" + collection_id);
G
groot 已提交
365
    for (auto& file : files_array) {
366
        EngineType engine_type;
J
Jin Hai 已提交
367 368 369
        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) {
370 371
            engine_type =
                utils::IsBinaryMetricType(file.metric_type_) ? EngineType::FAISS_BIN_IDMAP : EngineType::FAISS_IDMAP;
372 373 374
        } else {
            engine_type = (EngineType)file.engine_type_;
        }
375 376 377 378

        auto json = milvus::json::parse(file.index_params_);
        ExecutionEnginePtr engine =
            EngineFactory::Build(file.dimension_, file.location_, engine_type, (MetricType)file.metric_type_, json);
379
        fiu_do_on("DBImpl.PreloadCollection.null_engine", engine = nullptr);
G
groot 已提交
380 381 382 383
        if (engine == nullptr) {
            ENGINE_LOG_ERROR << "Invalid engine type";
            return Status(DB_ERROR, "Invalid engine type");
        }
Y
Yu Kun 已提交
384

385
        fiu_do_on("DBImpl.PreloadCollection.exceed_cache", size = available_size + 1);
386 387

        try {
388
            fiu_do_on("DBImpl.PreloadCollection.engine_throw_exception", throw std::exception());
389 390 391 392 393 394 395 396
            std::string msg = "Pre-loaded file: " + file.file_id_ + " size: " + std::to_string(file.file_size_);
            TimeRecorderAuto rc_1(msg);
            engine->Load(true);

            size += engine->Size();
            if (size > available_size) {
                ENGINE_LOG_DEBUG << "Pre-load cancelled since cache is almost full";
                return Status(SERVER_CACHE_FULL, "Cache is full");
Y
Yu Kun 已提交
397
            }
398
        } catch (std::exception& ex) {
J
Jin Hai 已提交
399
            std::string msg = "Pre-load collection encounter exception: " + std::string(ex.what());
400 401
            ENGINE_LOG_ERROR << msg;
            return Status(DB_ERROR, msg);
Y
Yu Kun 已提交
402 403
        }
    }
G
groot 已提交
404

Y
Yu Kun 已提交
405
    return Status::OK();
Y
Yu Kun 已提交
406 407
}

S
starlord 已提交
408
Status
409
DBImpl::UpdateCollectionFlag(const std::string& collection_id, int64_t flag) {
410
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
411
        return SHUTDOWN_ERROR;
S
starlord 已提交
412 413
    }

414
    return meta_ptr_->UpdateCollectionFlag(collection_id, flag);
S
starlord 已提交
415 416
}

S
starlord 已提交
417
Status
418
DBImpl::GetCollectionRowCount(const std::string& collection_id, uint64_t& row_count) {
419
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
420 421 422
        return SHUTDOWN_ERROR;
    }

423
    return GetCollectionRowCountRecursively(collection_id, row_count);
G
groot 已提交
424 425 426
}

Status
J
Jin Hai 已提交
427
DBImpl::CreatePartition(const std::string& collection_id, const std::string& partition_name,
G
groot 已提交
428
                        const std::string& partition_tag) {
429
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
430 431 432
        return SHUTDOWN_ERROR;
    }

433
    uint64_t lsn = 0;
434
    meta_ptr_->GetCollectionFlushLSN(collection_id, lsn);
J
Jin Hai 已提交
435
    return meta_ptr_->CreatePartition(collection_id, partition_name, partition_tag, lsn);
G
groot 已提交
436 437 438 439
}

Status
DBImpl::DropPartition(const std::string& partition_name) {
440
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
441
        return SHUTDOWN_ERROR;
S
starlord 已提交
442 443
    }

444
    mem_mgr_->EraseMemVector(partition_name);                // not allow insert
J
Jin Hai 已提交
445
    auto status = meta_ptr_->DropPartition(partition_name);  // soft delete collection
446 447 448 449
    if (!status.ok()) {
        ENGINE_LOG_ERROR << status.message();
        return status;
    }
G
groot 已提交
450

J
Jin Hai 已提交
451
    // scheduler will determine when to delete collection files
G
groot 已提交
452 453 454 455 456 457
    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 已提交
458 459
}

S
starlord 已提交
460
Status
J
Jin Hai 已提交
461
DBImpl::DropPartitionByTag(const std::string& collection_id, const std::string& partition_tag) {
462
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
463 464 465 466
        return SHUTDOWN_ERROR;
    }

    std::string partition_name;
J
Jin Hai 已提交
467
    auto status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
468 469 470 471 472
    if (!status.ok()) {
        ENGINE_LOG_ERROR << status.message();
        return status;
    }

G
groot 已提交
473 474 475 476
    return DropPartition(partition_name);
}

Status
J
Jin Hai 已提交
477
DBImpl::ShowPartitions(const std::string& collection_id, std::vector<meta::CollectionSchema>& partition_schema_array) {
478
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
479 480 481
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
482
    return meta_ptr_->ShowPartitions(collection_id, partition_schema_array);
G
groot 已提交
483 484 485
}

Status
J
Jin Hai 已提交
486
DBImpl::InsertVectors(const std::string& collection_id, const std::string& partition_tag, VectorsData& vectors) {
S
starlord 已提交
487
    //    ENGINE_LOG_DEBUG << "Insert " << n << " vectors to cache";
488
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
489
        return SHUTDOWN_ERROR;
S
starlord 已提交
490
    }
Y
yu yunfeng 已提交
491

J
Jin Hai 已提交
492
    // insert vectors into target collection
493 494
    // (zhiru): generate ids
    if (vectors.id_array_.empty()) {
J
Jin Hai 已提交
495 496 497 498 499
        SafeIDGenerator& id_generator = SafeIDGenerator::GetInstance();
        Status status = id_generator.GetNextIDNumbers(vectors.vector_count_, vectors.id_array_);
        if (!status.ok()) {
            return status;
        }
500 501
    }

502
    Status status;
503
    if (options_.wal_enable_) {
504 505
        std::string target_collection_name;
        status = GetPartitionByTag(collection_id, partition_tag, target_collection_name);
G
groot 已提交
506 507 508
        if (!status.ok()) {
            return status;
        }
509 510

        if (!vectors.float_data_.empty()) {
J
Jin Hai 已提交
511
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.float_data_);
512
        } else if (!vectors.binary_data_.empty()) {
J
Jin Hai 已提交
513
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.binary_data_);
514
        }
515
        bg_task_swn_.Notify();
516 517 518 519

    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
J
Jin Hai 已提交
520
        record.collection_id = collection_id;
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        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 已提交
537 538
    }

539 540 541 542
    return status;
}

Status
J
Jin Hai 已提交
543
DBImpl::DeleteVector(const std::string& collection_id, IDNumber vector_id) {
544 545
    IDNumbers ids;
    ids.push_back(vector_id);
J
Jin Hai 已提交
546
    return DeleteVectors(collection_id, ids);
547 548 549
}

Status
J
Jin Hai 已提交
550
DBImpl::DeleteVectors(const std::string& collection_id, IDNumbers vector_ids) {
551 552 553 554 555 556
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    if (options_.wal_enable_) {
J
Jin Hai 已提交
557
        wal_mgr_->DeleteById(collection_id, vector_ids);
558
        bg_task_swn_.Notify();
559 560 561 562 563

    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
        record.type = wal::MXLogType::Delete;
J
Jin Hai 已提交
564
        record.collection_id = collection_id;
565 566 567 568 569 570 571 572 573 574
        record.ids = vector_ids.data();
        record.length = vector_ids.size();

        status = ExecWalRecord(record);
    }

    return status;
}

Status
J
Jin Hai 已提交
575
DBImpl::Flush(const std::string& collection_id) {
576 577 578 579 580
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
581 582
    bool has_collection;
    status = HasCollection(collection_id, has_collection);
583 584 585
    if (!status.ok()) {
        return status;
    }
586
    if (!has_collection) {
J
Jin Hai 已提交
587 588
        ENGINE_LOG_ERROR << "Collection to flush does not exist: " << collection_id;
        return Status(DB_NOT_FOUND, "Collection to flush does not exist");
589 590
    }

J
Jin Hai 已提交
591
    ENGINE_LOG_DEBUG << "Begin flush collection: " << collection_id;
592 593 594

    if (options_.wal_enable_) {
        ENGINE_LOG_DEBUG << "WAL flush";
J
Jin Hai 已提交
595
        auto lsn = wal_mgr_->Flush(collection_id);
596 597
        ENGINE_LOG_DEBUG << "wal_mgr_->Flush";
        if (lsn != 0) {
598
            bg_task_swn_.Notify();
599 600 601 602 603 604 605 606
            flush_task_swn_.Wait();
            ENGINE_LOG_DEBUG << "flush_task_swn_.Wait()";
        }

    } else {
        ENGINE_LOG_DEBUG << "MemTable flush";
        wal::MXLogRecord record;
        record.type = wal::MXLogType::Flush;
J
Jin Hai 已提交
607
        record.collection_id = collection_id;
608 609 610
        status = ExecWalRecord(record);
    }

J
Jin Hai 已提交
611
    ENGINE_LOG_DEBUG << "End flush collection: " << collection_id;
612 613 614 615 616 617 618 619 620 621

    return status;
}

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

622
    ENGINE_LOG_DEBUG << "Begin flush all collections";
623 624 625 626 627 628

    Status status;
    if (options_.wal_enable_) {
        ENGINE_LOG_DEBUG << "WAL flush";
        auto lsn = wal_mgr_->Flush();
        if (lsn != 0) {
629
            bg_task_swn_.Notify();
630 631 632 633 634 635 636 637 638
            flush_task_swn_.Wait();
        }
    } else {
        ENGINE_LOG_DEBUG << "MemTable flush";
        wal::MXLogRecord record;
        record.type = wal::MXLogType::Flush;
        status = ExecWalRecord(record);
    }

639
    ENGINE_LOG_DEBUG << "End flush all collections";
640 641 642 643 644

    return status;
}

Status
J
Jin Hai 已提交
645
DBImpl::Compact(const std::string& collection_id) {
646 647 648 649
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

650 651 652
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
653 654
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
J
Jin Hai 已提交
655 656
            ENGINE_LOG_ERROR << "Collection to compact does not exist: " << collection_id;
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
657 658 659 660
        } else {
            return status;
        }
    } else {
661
        if (!collection_schema.owner_collection_.empty()) {
J
Jin Hai 已提交
662 663
            ENGINE_LOG_ERROR << "Collection to compact does not exist: " << collection_id;
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
664 665 666
        }
    }

Z
Zhiru Zhu 已提交
667
    ENGINE_LOG_DEBUG << "Before compacting, wait for build index thread to finish...";
668

Z
update  
Zhiru Zhu 已提交
669
    // WaitBuildIndexFinish();
670

Z
update  
Zhiru Zhu 已提交
671
    const std::lock_guard<std::mutex> index_lock(build_index_mutex_);
Z
Zhiru Zhu 已提交
672
    const std::lock_guard<std::mutex> merge_lock(flush_merge_compact_mutex_);
Z
Zhiru Zhu 已提交
673

J
Jin Hai 已提交
674
    ENGINE_LOG_DEBUG << "Compacting collection: " << collection_id;
Z
Zhiru Zhu 已提交
675

676
    // Get files to compact from meta.
J
Jin Hai 已提交
677 678 679 680
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
    meta::SegmentsSchema files_to_compact;
    status = meta_ptr_->FilesByType(collection_id, file_types, files_to_compact);
681 682 683 684 685 686 687 688 689
    if (!status.ok()) {
        std::string err_msg = "Failed to get files to compact: " + status.message();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    ENGINE_LOG_DEBUG << "Found " << files_to_compact.size() << " segment to compact";

    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_compact);
Z
Zhiru Zhu 已提交
690 691

    Status compact_status;
Z
Zhiru Zhu 已提交
692
    for (auto iter = files_to_compact.begin(); iter != files_to_compact.end();) {
J
Jin Hai 已提交
693
        meta::SegmentSchema file = *iter;
G
groot 已提交
694 695
        iter = files_to_compact.erase(iter);

Z
Zhiru Zhu 已提交
696 697 698
        // Check if the segment needs compacting
        std::string segment_dir;
        utils::GetParentPath(file.location_, segment_dir);
699

Z
Zhiru Zhu 已提交
700
        segment::SegmentReader segment_reader(segment_dir);
Z
Zhiru Zhu 已提交
701 702
        size_t deleted_docs_size;
        status = segment_reader.ReadDeletedDocsSize(deleted_docs_size);
Z
Zhiru Zhu 已提交
703
        if (!status.ok()) {
G
groot 已提交
704 705
            OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
            continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
706 707
        }

J
Jin Hai 已提交
708
        meta::SegmentsSchema files_to_update;
Z
Zhiru Zhu 已提交
709
        if (deleted_docs_size != 0) {
J
Jin Hai 已提交
710
            compact_status = CompactFile(collection_id, file, files_to_update);
Z
Zhiru Zhu 已提交
711 712 713 714

            if (!compact_status.ok()) {
                ENGINE_LOG_ERROR << "Compact failed for segment " << file.segment_id_ << ": "
                                 << compact_status.message();
G
groot 已提交
715 716
                OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
                continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
717 718
            }
        } else {
G
groot 已提交
719
            OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
G
typo  
groot 已提交
720
            ENGINE_LOG_DEBUG << "Segment " << file.segment_id_ << " has no deleted data. No need to compact";
G
groot 已提交
721
            continue;  // skip this file and try compact next one
722
        }
Z
Zhiru Zhu 已提交
723

G
groot 已提交
724
        ENGINE_LOG_DEBUG << "Updating meta after compaction...";
725
        status = meta_ptr_->UpdateCollectionFiles(files_to_update);
G
groot 已提交
726
        OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
G
groot 已提交
727 728 729 730
        if (!status.ok()) {
            compact_status = status;
            break;  // meta error, could not go on
        }
Z
Zhiru Zhu 已提交
731 732
    }

733 734
    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_compact);

G
groot 已提交
735
    if (compact_status.ok()) {
J
Jin Hai 已提交
736
        ENGINE_LOG_DEBUG << "Finished compacting collection: " << collection_id;
G
groot 已提交
737
    }
738

G
groot 已提交
739
    return compact_status;
740 741 742
}

Status
J
Jin Hai 已提交
743 744 745
DBImpl::CompactFile(const std::string& collection_id, const meta::SegmentSchema& file,
                    meta::SegmentsSchema& files_to_update) {
    ENGINE_LOG_DEBUG << "Compacting segment " << file.segment_id_ << " for collection: " << collection_id;
746

J
Jin Hai 已提交
747 748 749
    // Create new collection file
    meta::SegmentSchema compacted_file;
    compacted_file.collection_id_ = collection_id;
750
    // compacted_file.date_ = date;
J
Jin Hai 已提交
751
    compacted_file.file_type_ = meta::SegmentSchema::NEW_MERGE;  // TODO: use NEW_MERGE for now
752
    Status status = meta_ptr_->CreateCollectionFile(compacted_file);
753 754

    if (!status.ok()) {
J
Jin Hai 已提交
755
        ENGINE_LOG_ERROR << "Failed to create collection file: " << status.message();
756 757 758
        return status;
    }

J
Jin Hai 已提交
759
    // Compact (merge) file to the newly created collection file
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

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

    std::string segment_dir_to_merge;
    utils::GetParentPath(file.location_, segment_dir_to_merge);

    ENGINE_LOG_DEBUG << "Compacting begin...";
    segment_writer_ptr->Merge(segment_dir_to_merge, compacted_file.file_id_);

    // Serialize
    ENGINE_LOG_DEBUG << "Serializing compacted segment...";
    status = segment_writer_ptr->Serialize();
    if (!status.ok()) {
        ENGINE_LOG_ERROR << "Failed to serialize compacted segment: " << status.message();
J
Jin Hai 已提交
776
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
777
        auto mark_status = meta_ptr_->UpdateCollectionFile(compacted_file);
778 779 780 781 782 783
        if (mark_status.ok()) {
            ENGINE_LOG_DEBUG << "Mark file: " << compacted_file.file_id_ << " to to_delete";
        }
        return status;
    }

J
Jin Hai 已提交
784
    // Update collection files state
785 786
    // 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
787
    if (!utils::IsRawIndexType(compacted_file.engine_type_)) {
788
        compacted_file.file_type_ = (segment_writer_ptr->Size() >= compacted_file.index_file_size_)
J
Jin Hai 已提交
789 790
                                        ? meta::SegmentSchema::TO_INDEX
                                        : meta::SegmentSchema::RAW;
791
    } else {
J
Jin Hai 已提交
792
        compacted_file.file_type_ = meta::SegmentSchema::RAW;
793 794 795 796 797 798
    }
    compacted_file.file_size_ = segment_writer_ptr->Size();
    compacted_file.row_count_ = segment_writer_ptr->VectorCount();

    if (compacted_file.row_count_ == 0) {
        ENGINE_LOG_DEBUG << "Compacted segment is empty. Mark it as TO_DELETE";
J
Jin Hai 已提交
799
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
800 801
    }

Z
Zhiru Zhu 已提交
802
    files_to_update.emplace_back(compacted_file);
Z
Zhiru Zhu 已提交
803

Z
Zhiru Zhu 已提交
804 805
    // Set all files in segment to TO_DELETE
    auto& segment_id = file.segment_id_;
J
Jin Hai 已提交
806
    meta::SegmentsSchema segment_files;
807
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, segment_files);
Z
Zhiru Zhu 已提交
808 809 810 811
    if (!status.ok()) {
        return status;
    }
    for (auto& f : segment_files) {
J
Jin Hai 已提交
812
        f.file_type_ = meta::SegmentSchema::FILE_TYPE::TO_DELETE;
Z
Zhiru Zhu 已提交
813 814
        files_to_update.emplace_back(f);
    }
815 816

    ENGINE_LOG_DEBUG << "Compacted segment " << compacted_file.segment_id_ << " from "
Z
Zhiru Zhu 已提交
817 818
                     << std::to_string(file.file_size_) << " bytes to " << std::to_string(compacted_file.file_size_)
                     << " bytes";
819 820 821 822 823 824 825 826 827

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

    return status;
}

Status
J
Jin Hai 已提交
828
DBImpl::GetVectorByID(const std::string& collection_id, const IDNumber& vector_id, VectorsData& vector) {
829 830 831 832
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

833 834 835
    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
J
Jin Hai 已提交
836 837
        ENGINE_LOG_ERROR << "Collection " << collection_id << " does not exist: ";
        return Status(DB_NOT_FOUND, "Collection does not exist");
838 839 840 841 842
    }
    if (!status.ok()) {
        return status;
    }

J
Jin Hai 已提交
843
    meta::SegmentsSchema files_to_query;
844

J
Jin Hai 已提交
845 846
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
847
    meta::SegmentsSchema collection_files;
J
Jin Hai 已提交
848
    status = meta_ptr_->FilesByType(collection_id, file_types, files_to_query);
849 850 851 852 853 854
    if (!status.ok()) {
        std::string err_msg = "Failed to get files for GetVectorByID: " + status.message();
        ENGINE_LOG_ERROR << err_msg;
        return status;
    }

J
Jin Hai 已提交
855 856
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
857
    for (auto& schema : partition_array) {
J
Jin Hai 已提交
858 859
        meta::SegmentsSchema files;
        status = meta_ptr_->FilesByType(schema.collection_id_, file_types, files);
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        if (!status.ok()) {
            std::string err_msg = "Failed to get files for GetVectorByID: " + status.message();
            ENGINE_LOG_ERROR << err_msg;
            return status;
        }
        files_to_query.insert(files_to_query.end(), std::make_move_iterator(files.begin()),
                              std::make_move_iterator(files.end()));
    }

    if (files_to_query.empty()) {
        ENGINE_LOG_DEBUG << "No files to get vector by id from";
        return Status::OK();
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();
    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_query);

J
Jin Hai 已提交
877
    status = GetVectorByIdHelper(collection_id, vector_id, vector, files_to_query);
878 879 880 881 882 883 884 885

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_query);
    cache::CpuCacheMgr::GetInstance()->PrintInfo();

    return status;
}

Status
J
Jin Hai 已提交
886
DBImpl::GetVectorIDs(const std::string& collection_id, const std::string& segment_id, IDNumbers& vector_ids) {
887 888 889 890
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
891
    // step 1: check collection existence
892 893 894
    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
J
Jin Hai 已提交
895 896
        ENGINE_LOG_ERROR << "Collection " << collection_id << " does not exist: ";
        return Status(DB_NOT_FOUND, "Collection does not exist");
897 898 899 900 901 902
    }
    if (!status.ok()) {
        return status;
    }

    //  step 2: find segment
903 904
    meta::SegmentsSchema collection_files;
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, collection_files);
905 906 907 908
    if (!status.ok()) {
        return status;
    }

909
    if (collection_files.empty()) {
910 911 912
        return Status(DB_NOT_FOUND, "Segment does not exist");
    }

J
Jin Hai 已提交
913
    // check the segment is belong to this collection
914
    if (collection_files[0].collection_id_ != collection_id) {
J
Jin Hai 已提交
915
        // the segment could be in a partition under this collection
916 917 918 919
        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 已提交
920
            return Status(DB_NOT_FOUND, "Segment does not belong to this collection");
921 922 923 924 925
        }
    }

    // step 3: load segment ids and delete offset
    std::string segment_dir;
926
    engine::utils::GetParentPath(collection_files[0].location_, segment_dir);
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    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 已提交
952

G
groot 已提交
953
    return status;
X
Xu Peng 已提交
954 955
}

956
Status
J
Jin Hai 已提交
957 958
DBImpl::GetVectorByIdHelper(const std::string& collection_id, IDNumber vector_id, VectorsData& vector,
                            const meta::SegmentsSchema& files) {
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    ENGINE_LOG_DEBUG << "Getting vector by id in " << files.size() << " files";

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

        // 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<int64_t> offsets;
            std::vector<segment::doc_id_t> uids;
            auto status = segment_reader.LoadUids(uids);
            if (!status.ok()) {
                return status;
            }

            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);
                if (!status.ok()) {
                    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()) {
                    // Load raw vector
994
                    bool is_binary = utils::IsBinaryMetricType(file.metric_type_);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
                    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()) {
                        return status;
                    }

                    vector.vector_count_ = 1;
                    if (is_binary) {
                        vector.binary_data_ = std::move(raw_vector);
                    } else {
                        std::vector<float> float_vector;
                        float_vector.resize(file.dimension_);
                        memcpy(float_vector.data(), raw_vector.data(), single_vector_bytes);
                        vector.float_data_ = std::move(float_vector);
                    }
                    return Status::OK();
                }
            }
        } else {
            continue;
        }
    }

    return Status::OK();
}

S
starlord 已提交
1022
Status
1023
DBImpl::CreateIndex(const std::string& collection_id, const CollectionIndex& index) {
1024
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1025 1026 1027
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
1028
    // serialize memory data
1029 1030
    //    std::set<std::string> sync_collection_ids;
    //    auto status = SyncMemData(sync_collection_ids);
1031
    auto status = Flush();
G
groot 已提交
1032

S
starlord 已提交
1033 1034 1035
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);

S
starlord 已提交
1036
        // step 1: check index difference
1037
        CollectionIndex old_index;
J
Jin Hai 已提交
1038
        status = DescribeIndex(collection_id, old_index);
S
starlord 已提交
1039
        if (!status.ok()) {
J
Jin Hai 已提交
1040
            ENGINE_LOG_ERROR << "Failed to get collection index info for collection: " << collection_id;
S
starlord 已提交
1041 1042 1043
            return status;
        }

S
starlord 已提交
1044
        // step 2: update index info
1045 1046
        CollectionIndex new_index = index;
        new_index.metric_type_ = old_index.metric_type_;  // dont change metric type, it was defined by CreateCollection
S
starlord 已提交
1047
        if (!utils::IsSameIndex(old_index, new_index)) {
1048
            status = UpdateCollectionIndexRecursively(collection_id, new_index);
S
starlord 已提交
1049 1050 1051 1052 1053 1054
            if (!status.ok()) {
                return status;
            }
        }
    }

S
starlord 已提交
1055 1056
    // step 3: let merge file thread finish
    // to avoid duplicate data bug
1057 1058
    WaitMergeFileFinish();

S
starlord 已提交
1059
    // step 4: wait and build index
1060 1061
    status = index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
    status = WaitCollectionIndexRecursively(collection_id, index);
S
starlord 已提交
1062

G
groot 已提交
1063
    return status;
S
starlord 已提交
1064 1065
}

S
starlord 已提交
1066
Status
1067
DBImpl::DescribeIndex(const std::string& collection_id, CollectionIndex& index) {
1068
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1069 1070 1071
        return SHUTDOWN_ERROR;
    }

1072
    return meta_ptr_->DescribeCollectionIndex(collection_id, index);
S
starlord 已提交
1073 1074
}

S
starlord 已提交
1075
Status
J
Jin Hai 已提交
1076
DBImpl::DropIndex(const std::string& collection_id) {
1077
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1078 1079 1080
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
1081
    ENGINE_LOG_DEBUG << "Drop index for collection: " << collection_id;
1082
    return DropCollectionIndexRecursively(collection_id);
S
starlord 已提交
1083 1084
}

S
starlord 已提交
1085
Status
J
Jin Hai 已提交
1086
DBImpl::QueryByID(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
1087 1088
                  const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
                  IDNumber vector_id, ResultIds& result_ids, ResultDistances& result_distances) {
1089
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1090
        return SHUTDOWN_ERROR;
S
starlord 已提交
1091 1092
    }

1093 1094 1095
    VectorsData vectors_data = VectorsData();
    vectors_data.id_array_.emplace_back(vector_id);
    vectors_data.vector_count_ = 1;
1096
    Status result =
J
Jin Hai 已提交
1097
        Query(context, collection_id, partition_tags, k, extra_params, vectors_data, result_ids, result_distances);
Y
yu yunfeng 已提交
1098
    return result;
X
Xu Peng 已提交
1099 1100
}

S
starlord 已提交
1101
Status
J
Jin Hai 已提交
1102
DBImpl::Query(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
1103 1104
              const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
              const VectorsData& vectors, ResultIds& result_ids, ResultDistances& result_distances) {
1105
    milvus::server::ContextChild tracer(context, "Query");
Z
Zhiru Zhu 已提交
1106

1107
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1108
        return SHUTDOWN_ERROR;
S
starlord 已提交
1109 1110
    }

G
groot 已提交
1111
    Status status;
J
Jin Hai 已提交
1112
    meta::SegmentsSchema files_array;
1113

G
groot 已提交
1114
    if (partition_tags.empty()) {
J
Jin Hai 已提交
1115 1116 1117
        // no partition tag specified, means search in whole collection
        // get all collection files from parent collection
        status = GetFilesToSearch(collection_id, files_array);
G
groot 已提交
1118 1119 1120 1121
        if (!status.ok()) {
            return status;
        }

J
Jin Hai 已提交
1122 1123
        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1124
        for (auto& schema : partition_array) {
J
Jin Hai 已提交
1125
            status = GetFilesToSearch(schema.collection_id_, files_array);
1126 1127 1128 1129
        }

        if (files_array.empty()) {
            return Status::OK();
G
groot 已提交
1130 1131 1132 1133
        }
    } else {
        // get files from specified partitions
        std::set<std::string> partition_name_array;
J
Jin Hai 已提交
1134
        status = GetPartitionsByTags(collection_id, partition_tags, partition_name_array);
T
Tinkerrr 已提交
1135 1136 1137
        if (!status.ok()) {
            return status;  // didn't match any partition.
        }
G
groot 已提交
1138 1139

        for (auto& partition_name : partition_name_array) {
1140
            status = GetFilesToSearch(partition_name, files_array);
1141 1142 1143 1144
        }

        if (files_array.empty()) {
            return Status::OK();
1145 1146 1147
        }
    }

S
starlord 已提交
1148
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
1149
    status = QueryAsync(tracer.Context(), files_array, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
1150
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1151

S
starlord 已提交
1152
    return status;
G
groot 已提交
1153
}
X
Xu Peng 已提交
1154

S
starlord 已提交
1155
Status
1156 1157 1158
DBImpl::QueryByFileID(const std::shared_ptr<server::Context>& context, const std::vector<std::string>& file_ids,
                      uint64_t k, const milvus::json& extra_params, const VectorsData& vectors, ResultIds& result_ids,
                      ResultDistances& result_distances) {
1159
    milvus::server::ContextChild tracer(context, "Query by file id");
Z
Zhiru Zhu 已提交
1160

1161
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1162
        return SHUTDOWN_ERROR;
S
starlord 已提交
1163 1164
    }

S
starlord 已提交
1165
    // get specified files
1166
    std::vector<size_t> ids;
Y
Yu Kun 已提交
1167
    for (auto& id : file_ids) {
1168
        std::string::size_type sz;
J
jinhai 已提交
1169
        ids.push_back(std::stoul(id, &sz));
1170 1171
    }

J
Jin Hai 已提交
1172
    meta::SegmentsSchema search_files;
1173
    auto status = meta_ptr_->FilesByID(ids, search_files);
1174 1175
    if (!status.ok()) {
        return status;
1176 1177
    }

1178 1179
    fiu_do_on("DBImpl.QueryByFileID.empty_files_array", search_files.clear());
    if (search_files.empty()) {
S
starlord 已提交
1180
        return Status(DB_ERROR, "Invalid file id");
G
groot 已提交
1181 1182
    }

S
starlord 已提交
1183
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
1184
    status = QueryAsync(tracer.Context(), search_files, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
1185
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1186

S
starlord 已提交
1187
    return status;
1188 1189
}

S
starlord 已提交
1190
Status
Y
Yu Kun 已提交
1191
DBImpl::Size(uint64_t& result) {
1192
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1193
        return SHUTDOWN_ERROR;
S
starlord 已提交
1194 1195
    }

S
starlord 已提交
1196
    return meta_ptr_->Size(result);
S
starlord 已提交
1197 1198 1199
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1200
// internal methods
S
starlord 已提交
1201
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1202
Status
J
Jin Hai 已提交
1203
DBImpl::QueryAsync(const std::shared_ptr<server::Context>& context, const meta::SegmentsSchema& files, uint64_t k,
1204 1205
                   const milvus::json& extra_params, const VectorsData& vectors, ResultIds& result_ids,
                   ResultDistances& result_distances) {
1206
    milvus::server::ContextChild tracer(context, "Query Async");
G
groot 已提交
1207
    server::CollectQueryMetrics metrics(vectors.vector_count_);
Y
Yu Kun 已提交
1208

S
starlord 已提交
1209
    TimeRecorder rc("");
G
groot 已提交
1210

1211
    // step 1: construct search job
1212
    auto status = OngoingFileChecker::GetInstance().MarkOngoingFiles(files);
1213

1214
    ENGINE_LOG_DEBUG << "Engine query begin, index file count: " << files.size();
1215
    scheduler::SearchJobPtr job = std::make_shared<scheduler::SearchJob>(tracer.Context(), k, extra_params, vectors);
Y
Yu Kun 已提交
1216
    for (auto& file : files) {
J
Jin Hai 已提交
1217
        scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
W
wxyu 已提交
1218
        job->AddIndexFile(file_ptr);
G
groot 已提交
1219 1220
    }

1221
    // step 2: put search job to scheduler and wait result
S
starlord 已提交
1222
    scheduler::JobMgrInst::GetInstance()->Put(job);
W
wxyu 已提交
1223
    job->WaitResult();
1224

1225
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files);
W
wxyu 已提交
1226 1227
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
1228
    }
G
groot 已提交
1229

1230
    // step 3: construct results
G
groot 已提交
1231 1232
    result_ids = job->GetResultIds();
    result_distances = job->GetResultDistances();
S
starlord 已提交
1233
    rc.ElapseFromBegin("Engine query totally cost");
G
groot 已提交
1234 1235 1236 1237

    return Status::OK();
}

S
starlord 已提交
1238 1239
void
DBImpl::BackgroundTimerTask() {
Y
yu yunfeng 已提交
1240
    server::SystemInfo::GetInstance().Init();
X
Xu Peng 已提交
1241
    while (true) {
1242
        if (!initialized_.load(std::memory_order_acquire)) {
1243 1244
            WaitMergeFileFinish();
            WaitBuildIndexFinish();
S
starlord 已提交
1245 1246

            ENGINE_LOG_DEBUG << "DB background thread exit";
G
groot 已提交
1247 1248
            break;
        }
X
Xu Peng 已提交
1249

1250 1251 1252 1253 1254
        if (options_.auto_flush_interval_ > 0) {
            bg_task_swn_.Wait_For(std::chrono::seconds(options_.auto_flush_interval_));
        } else {
            bg_task_swn_.Wait();
        }
X
Xu Peng 已提交
1255

G
groot 已提交
1256
        StartMetricTask();
1257
        StartMergeTask();
G
groot 已提交
1258 1259
        StartBuildIndexTask();
    }
X
Xu Peng 已提交
1260 1261
}

S
starlord 已提交
1262 1263
void
DBImpl::WaitMergeFileFinish() {
1264 1265 1266
    ENGINE_LOG_DEBUG << "Begin WaitMergeFileFinish";
    std::lock_guard<std::mutex> lck(merge_result_mutex_);
    for (auto& iter : merge_thread_results_) {
1267 1268
        iter.wait();
    }
1269
    ENGINE_LOG_DEBUG << "End WaitMergeFileFinish";
1270 1271
}

S
starlord 已提交
1272 1273
void
DBImpl::WaitBuildIndexFinish() {
1274
    ENGINE_LOG_DEBUG << "Begin WaitBuildIndexFinish";
1275
    std::lock_guard<std::mutex> lck(index_result_mutex_);
Y
Yu Kun 已提交
1276
    for (auto& iter : index_thread_results_) {
1277 1278
        iter.wait();
    }
1279
    ENGINE_LOG_DEBUG << "End WaitBuildIndexFinish";
1280 1281
}

S
starlord 已提交
1282 1283
void
DBImpl::StartMetricTask() {
G
groot 已提交
1284
    static uint64_t metric_clock_tick = 0;
1285
    ++metric_clock_tick;
S
starlord 已提交
1286
    if (metric_clock_tick % METRIC_ACTION_INTERVAL != 0) {
G
groot 已提交
1287 1288 1289 1290 1291 1292
        return;
    }

    server::Metrics::GetInstance().KeepingAliveCounterIncrement(METRIC_ACTION_INTERVAL);
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
S
shengjh 已提交
1293 1294
    fiu_do_on("DBImpl.StartMetricTask.InvalidTotalCache", cache_total = 0);

J
JinHai-CN 已提交
1295 1296 1297 1298 1299 1300 1301
    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 已提交
1302
    server::Metrics::GetInstance().GpuCacheUsageGaugeSet();
G
groot 已提交
1303 1304 1305 1306 1307 1308 1309 1310
    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 已提交
1311

K
kun yu 已提交
1312
    server::Metrics::GetInstance().CPUCoreUsagePercentSet();
K
kun yu 已提交
1313 1314
    server::Metrics::GetInstance().GPUTemperature();
    server::Metrics::GetInstance().CPUTemperature();
1315
    server::Metrics::GetInstance().PushToGateway();
G
groot 已提交
1316 1317
}

S
starlord 已提交
1318
void
1319
DBImpl::StartMergeTask() {
1320
    static uint64_t compact_clock_tick = 0;
1321
    ++compact_clock_tick;
S
starlord 已提交
1322
    if (compact_clock_tick % COMPACT_ACTION_INTERVAL != 0) {
1323 1324 1325
        return;
    }

1326 1327 1328
    if (!options_.wal_enable_) {
        Flush();
    }
1329

1330 1331
    // ENGINE_LOG_DEBUG << "Begin StartMergeTask";
    // merge task has been finished?
1332
    {
1333 1334
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (!merge_thread_results_.empty()) {
1335
            std::chrono::milliseconds span(10);
1336 1337
            if (merge_thread_results_.back().wait_for(span) == std::future_status::ready) {
                merge_thread_results_.pop_back();
1338
            }
G
groot 已提交
1339 1340
        }
    }
X
Xu Peng 已提交
1341

1342
    // add new merge task
1343
    {
1344 1345
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (merge_thread_results_.empty()) {
1346 1347
            // collect merge files for all collections(if merge_collection_ids_ is empty) for two reasons:
            // 1. other collections may still has un-merged files
1348
            // 2. server may be closed unexpected, these un-merge files need to be merged when server restart
1349 1350 1351 1352 1353
            if (merge_collection_ids_.empty()) {
                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_);
1354 1355 1356 1357
                }
            }

            // start merge file thread
1358
            merge_thread_results_.push_back(
1359 1360
                merge_thread_pool_.enqueue(&DBImpl::BackgroundMerge, this, merge_collection_ids_));
            merge_collection_ids_.clear();
1361
        }
G
groot 已提交
1362
    }
1363 1364

    // ENGINE_LOG_DEBUG << "End StartMergeTask";
X
Xu Peng 已提交
1365 1366
}

S
starlord 已提交
1367
Status
J
Jin Hai 已提交
1368
DBImpl::MergeFiles(const std::string& collection_id, const meta::SegmentsSchema& files) {
Z
Zhiru Zhu 已提交
1369
    // const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1370

J
Jin Hai 已提交
1371
    ENGINE_LOG_DEBUG << "Merge files for collection: " << collection_id;
S
starlord 已提交
1372

J
Jin Hai 已提交
1373
    // step 1: create collection file
1374 1375 1376 1377
    meta::SegmentSchema collection_file;
    collection_file.collection_id_ = collection_id;
    collection_file.file_type_ = meta::SegmentSchema::NEW_MERGE;
    Status status = meta_ptr_->CreateCollectionFile(collection_file);
X
Xu Peng 已提交
1378

1379
    if (!status.ok()) {
J
Jin Hai 已提交
1380
        ENGINE_LOG_ERROR << "Failed to create collection: " << status.ToString();
1381 1382 1383
        return status;
    }

S
starlord 已提交
1384
    // step 2: merge files
1385
    /*
G
groot 已提交
1386
    ExecutionEnginePtr index =
1387 1388
        EngineFactory::Build(collection_file.dimension_, collection_file.location_,
    (EngineType)collection_file.engine_type_, (MetricType)collection_file.metric_type_, collection_file.nlist_);
1389
*/
J
Jin Hai 已提交
1390
    meta::SegmentsSchema updated;
1391 1392

    std::string new_segment_dir;
1393
    utils::GetParentPath(collection_file.location_, new_segment_dir);
1394
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);
1395

Y
Yu Kun 已提交
1396
    for (auto& file : files) {
Y
Yu Kun 已提交
1397
        server::CollectMergeFilesMetrics metrics;
1398 1399
        std::string segment_dir_to_merge;
        utils::GetParentPath(file.location_, segment_dir_to_merge);
1400
        segment_writer_ptr->Merge(segment_dir_to_merge, collection_file.file_id_);
1401
        auto file_schema = file;
J
Jin Hai 已提交
1402
        file_schema.file_type_ = meta::SegmentSchema::TO_DELETE;
1403
        updated.push_back(file_schema);
1404 1405
        auto size = segment_writer_ptr->Size();
        if (size >= file_schema.index_file_size_) {
S
starlord 已提交
1406
            break;
S
starlord 已提交
1407
        }
1408 1409
    }

S
starlord 已提交
1410
    // step 3: serialize to disk
S
starlord 已提交
1411
    try {
1412
        status = segment_writer_ptr->Serialize();
S
shengjh 已提交
1413 1414
        fiu_do_on("DBImpl.MergeFiles.Serialize_ThrowException", throw std::exception());
        fiu_do_on("DBImpl.MergeFiles.Serialize_ErrorStatus", status = Status(DB_ERROR, ""));
Y
Yu Kun 已提交
1415
    } catch (std::exception& ex) {
S
starlord 已提交
1416
        std::string msg = "Serialize merged index encounter exception: " + std::string(ex.what());
S
starlord 已提交
1417
        ENGINE_LOG_ERROR << msg;
G
groot 已提交
1418 1419
        status = Status(DB_ERROR, msg);
    }
Y
yu yunfeng 已提交
1420

G
groot 已提交
1421
    if (!status.ok()) {
1422 1423
        ENGINE_LOG_ERROR << "Failed to persist merged segment: " << new_segment_dir << ". Error: " << status.message();

G
groot 已提交
1424
        // if failed to serialize merge file to disk
1425
        // typical error: out of disk space, out of memory or permission denied
1426 1427 1428 1429
        collection_file.file_type_ = meta::SegmentSchema::TO_DELETE;
        status = meta_ptr_->UpdateCollectionFile(collection_file);
        ENGINE_LOG_DEBUG << "Failed to update file to index, mark file: " << collection_file.file_id_
                         << " to to_delete";
X
Xu Peng 已提交
1430

G
groot 已提交
1431
        return status;
S
starlord 已提交
1432 1433
    }

J
Jin Hai 已提交
1434
    // step 4: update collection files state
1435
    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
S
starlord 已提交
1436
    // else set file type to RAW, no need to build index
1437 1438 1439 1440
    if (!utils::IsRawIndexType(collection_file.engine_type_)) {
        collection_file.file_type_ = (segment_writer_ptr->Size() >= collection_file.index_file_size_)
                                         ? meta::SegmentSchema::TO_INDEX
                                         : meta::SegmentSchema::RAW;
1441
    } else {
1442
        collection_file.file_type_ = meta::SegmentSchema::RAW;
1443
    }
1444 1445 1446 1447 1448 1449
    collection_file.file_size_ = segment_writer_ptr->Size();
    collection_file.row_count_ = segment_writer_ptr->VectorCount();
    updated.push_back(collection_file);
    status = meta_ptr_->UpdateCollectionFiles(updated);
    ENGINE_LOG_DEBUG << "New merged segment " << collection_file.segment_id_ << " of size "
                     << segment_writer_ptr->Size() << " bytes";
1450

S
starlord 已提交
1451
    if (options_.insert_cache_immediately_) {
1452
        segment_writer_ptr->Cache();
S
starlord 已提交
1453
    }
X
Xu Peng 已提交
1454

1455 1456 1457
    return status;
}

S
starlord 已提交
1458
Status
J
Jin Hai 已提交
1459
DBImpl::BackgroundMergeFiles(const std::string& collection_id) {
Z
Zhiru Zhu 已提交
1460
    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1461

J
Jin Hai 已提交
1462 1463
    meta::SegmentsSchema raw_files;
    auto status = meta_ptr_->FilesToMerge(collection_id, raw_files);
X
Xu Peng 已提交
1464
    if (!status.ok()) {
J
Jin Hai 已提交
1465
        ENGINE_LOG_ERROR << "Failed to get merge files for collection: " << collection_id;
X
Xu Peng 已提交
1466 1467
        return status;
    }
1468

1469 1470 1471 1472
    if (raw_files.size() < options_.merge_trigger_number_) {
        ENGINE_LOG_TRACE << "Files number not greater equal than merge trigger number, skip merge action";
        return Status::OK();
    }
1473

1474
    status = OngoingFileChecker::GetInstance().MarkOngoingFiles(raw_files);
J
Jin Hai 已提交
1475
    MergeFiles(collection_id, raw_files);
1476
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(raw_files);
G
groot 已提交
1477

1478
    if (!initialized_.load(std::memory_order_acquire)) {
J
Jin Hai 已提交
1479
        ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action for collection: " << collection_id;
1480
    }
X
Xu Peng 已提交
1481

G
groot 已提交
1482 1483
    return Status::OK();
}
1484

S
starlord 已提交
1485
void
1486
DBImpl::BackgroundMerge(std::set<std::string> collection_ids) {
1487
    // ENGINE_LOG_TRACE << " Background merge thread start";
S
starlord 已提交
1488

G
groot 已提交
1489
    Status status;
1490
    for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
1491
        status = BackgroundMergeFiles(collection_id);
G
groot 已提交
1492
        if (!status.ok()) {
J
Jin Hai 已提交
1493
            ENGINE_LOG_ERROR << "Merge files for collection " << collection_id << " failed: " << status.ToString();
G
groot 已提交
1494
        }
S
starlord 已提交
1495

1496
        if (!initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
1497 1498 1499
            ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action";
            break;
        }
G
groot 已提交
1500
    }
X
Xu Peng 已提交
1501

G
groot 已提交
1502
    meta_ptr_->Archive();
Z
update  
zhiru 已提交
1503

1504
    {
G
groot 已提交
1505
        uint64_t ttl = 10 * meta::SECOND;  // default: file will be hard-deleted few seconds after soft-deleted
1506
        if (options_.mode_ == DBOptions::MODE::CLUSTER_WRITABLE) {
1507
            ttl = meta::HOUR;
1508
        }
G
groot 已提交
1509

1510
        meta_ptr_->CleanUpFilesWithTTL(ttl);
Z
update  
zhiru 已提交
1511
    }
S
starlord 已提交
1512

1513
    // ENGINE_LOG_TRACE << " Background merge thread exit";
G
groot 已提交
1514
}
X
Xu Peng 已提交
1515

S
starlord 已提交
1516 1517
void
DBImpl::StartBuildIndexTask(bool force) {
G
groot 已提交
1518
    static uint64_t index_clock_tick = 0;
1519
    ++index_clock_tick;
S
starlord 已提交
1520
    if (!force && (index_clock_tick % INDEX_ACTION_INTERVAL != 0)) {
G
groot 已提交
1521 1522 1523
        return;
    }

S
starlord 已提交
1524
    // build index has been finished?
1525 1526 1527 1528 1529 1530 1531
    {
        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 已提交
1532 1533 1534
        }
    }

S
starlord 已提交
1535
    // add new build index task
1536 1537 1538
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (index_thread_results_.empty()) {
S
starlord 已提交
1539
            index_thread_results_.push_back(index_thread_pool_.enqueue(&DBImpl::BackgroundBuildIndex, this));
1540
        }
G
groot 已提交
1541
    }
X
Xu Peng 已提交
1542 1543
}

S
starlord 已提交
1544 1545
void
DBImpl::BackgroundBuildIndex() {
P
peng.xu 已提交
1546
    std::unique_lock<std::mutex> lock(build_index_mutex_);
J
Jin Hai 已提交
1547
    meta::SegmentsSchema to_index_files;
G
groot 已提交
1548
    meta_ptr_->FilesToIndex(to_index_files);
1549
    Status status = index_failed_checker_.IgnoreFailedIndexFiles(to_index_files);
1550

1551
    if (!to_index_files.empty()) {
G
groot 已提交
1552
        ENGINE_LOG_DEBUG << "Background build index thread begin";
1553
        status = OngoingFileChecker::GetInstance().MarkOngoingFiles(to_index_files);
1554

1555
        // step 2: put build index task to scheduler
J
Jin Hai 已提交
1556
        std::vector<std::pair<scheduler::BuildIndexJobPtr, scheduler::SegmentSchemaPtr>> job2file_map;
1557
        for (auto& file : to_index_files) {
G
groot 已提交
1558
            scheduler::BuildIndexJobPtr job = std::make_shared<scheduler::BuildIndexJob>(meta_ptr_, options_);
J
Jin Hai 已提交
1559
            scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
1560
            job->AddToIndexFiles(file_ptr);
G
groot 已提交
1561
            scheduler::JobMgrInst::GetInstance()->Put(job);
G
groot 已提交
1562
            job2file_map.push_back(std::make_pair(job, file_ptr));
1563
        }
G
groot 已提交
1564

G
groot 已提交
1565
        // step 3: wait build index finished and mark failed files
G
groot 已提交
1566 1567
        for (auto iter = job2file_map.begin(); iter != job2file_map.end(); ++iter) {
            scheduler::BuildIndexJobPtr job = iter->first;
J
Jin Hai 已提交
1568
            meta::SegmentSchema& file_schema = *(iter->second.get());
G
groot 已提交
1569 1570 1571 1572 1573
            job->WaitBuildIndexFinish();
            if (!job->GetStatus().ok()) {
                Status status = job->GetStatus();
                ENGINE_LOG_ERROR << "Building index job " << job->id() << " failed: " << status.ToString();

1574
                index_failed_checker_.MarkFailedIndexFile(file_schema, status.message());
G
groot 已提交
1575 1576
            } else {
                ENGINE_LOG_DEBUG << "Building index job " << job->id() << " succeed.";
G
groot 已提交
1577 1578

                index_failed_checker_.MarkSucceedIndexFile(file_schema);
G
groot 已提交
1579
            }
1580
            status = OngoingFileChecker::GetInstance().UnmarkOngoingFile(file_schema);
1581
        }
G
groot 已提交
1582 1583

        ENGINE_LOG_DEBUG << "Background build index thread finished";
Y
Yu Kun 已提交
1584
    }
X
Xu Peng 已提交
1585 1586
}

G
groot 已提交
1587
Status
J
Jin Hai 已提交
1588 1589
DBImpl::GetFilesToBuildIndex(const std::string& collection_id, const std::vector<int>& file_types,
                             meta::SegmentsSchema& files) {
G
groot 已提交
1590
    files.clear();
J
Jin Hai 已提交
1591
    auto status = meta_ptr_->FilesByType(collection_id, file_types, files);
G
groot 已提交
1592 1593 1594

    // only build index for files that row count greater than certain threshold
    for (auto it = files.begin(); it != files.end();) {
J
Jin Hai 已提交
1595
        if ((*it).file_type_ == static_cast<int>(meta::SegmentSchema::RAW) &&
G
groot 已提交
1596 1597 1598
            (*it).row_count_ < meta::BUILD_INDEX_THRESHOLD) {
            it = files.erase(it);
        } else {
1599
            ++it;
G
groot 已提交
1600 1601 1602 1603 1604 1605
        }
    }

    return Status::OK();
}

G
groot 已提交
1606
Status
J
Jin Hai 已提交
1607 1608
DBImpl::GetFilesToSearch(const std::string& collection_id, meta::SegmentsSchema& files) {
    ENGINE_LOG_DEBUG << "Collect files from collection: " << collection_id;
1609

J
Jin Hai 已提交
1610 1611
    meta::SegmentsSchema search_files;
    auto status = meta_ptr_->FilesToSearch(collection_id, search_files);
G
groot 已提交
1612 1613 1614 1615
    if (!status.ok()) {
        return status;
    }

1616 1617 1618
    for (auto& file : search_files) {
        files.push_back(file);
    }
G
groot 已提交
1619 1620 1621
    return Status::OK();
}

1622
Status
J
Jin Hai 已提交
1623 1624
DBImpl::GetPartitionByTag(const std::string& collection_id, const std::string& partition_tag,
                          std::string& partition_name) {
1625 1626 1627
    Status status;

    if (partition_tag.empty()) {
J
Jin Hai 已提交
1628
        partition_name = collection_id;
1629 1630 1631 1632 1633 1634 1635 1636

    } 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;
        server::StringHelpFunctions::TrimStringBlank(valid_tag);

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
1637
            partition_name = collection_id;
1638 1639 1640
            return status;
        }

J
Jin Hai 已提交
1641
        status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
1642 1643 1644 1645 1646 1647 1648 1649
        if (!status.ok()) {
            ENGINE_LOG_ERROR << status.message();
        }
    }

    return status;
}

G
groot 已提交
1650
Status
J
Jin Hai 已提交
1651
DBImpl::GetPartitionsByTags(const std::string& collection_id, const std::vector<std::string>& partition_tags,
G
groot 已提交
1652
                            std::set<std::string>& partition_name_array) {
J
Jin Hai 已提交
1653 1654
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1655 1656

    for (auto& tag : partition_tags) {
1657 1658 1659 1660
        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = tag;
        server::StringHelpFunctions::TrimStringBlank(valid_tag);
1661 1662

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
1663
            partition_name_array.insert(collection_id);
1664 1665 1666
            return status;
        }

G
groot 已提交
1667
        for (auto& schema : partition_array) {
1668
            if (server::StringHelpFunctions::IsRegexMatch(schema.partition_tag_, valid_tag)) {
J
Jin Hai 已提交
1669
                partition_name_array.insert(schema.collection_id_);
G
groot 已提交
1670 1671 1672 1673
            }
        }
    }

T
Tinkerrr 已提交
1674 1675 1676 1677
    if (partition_name_array.empty()) {
        return Status(PARTITION_NOT_FOUND, "Cannot find the specified partitions");
    }

G
groot 已提交
1678 1679 1680 1681
    return Status::OK();
}

Status
1682
DBImpl::DropCollectionRecursively(const std::string& collection_id) {
J
Jin Hai 已提交
1683 1684
    // dates partly delete files of the collection but currently we don't support
    ENGINE_LOG_DEBUG << "Prepare to delete collection " << collection_id;
G
groot 已提交
1685 1686

    Status status;
1687
    if (options_.wal_enable_) {
1688
        wal_mgr_->DropCollection(collection_id);
G
groot 已提交
1689 1690
    }

1691 1692 1693
    status = mem_mgr_->EraseMemVector(collection_id);   // not allow insert
    status = meta_ptr_->DropCollection(collection_id);  // soft delete collection
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
1694

J
Jin Hai 已提交
1695
    // scheduler will determine when to delete collection files
1696
    auto nres = scheduler::ResMgrInst::GetInstance()->GetNumOfComputeResource();
J
Jin Hai 已提交
1697
    scheduler::DeleteJobPtr job = std::make_shared<scheduler::DeleteJob>(collection_id, meta_ptr_, nres);
1698 1699 1700
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitAndDelete();

J
Jin Hai 已提交
1701 1702
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1703
    for (auto& schema : partition_array) {
1704 1705
        status = DropCollectionRecursively(schema.collection_id_);
        fiu_do_on("DBImpl.DropCollectionRecursively.failed", status = Status(DB_ERROR, ""));
G
groot 已提交
1706 1707 1708 1709 1710 1711 1712 1713 1714
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
1715
DBImpl::UpdateCollectionIndexRecursively(const std::string& collection_id, const CollectionIndex& index) {
J
Jin Hai 已提交
1716
    DropIndex(collection_id);
G
groot 已提交
1717

1718 1719
    auto status = meta_ptr_->UpdateCollectionIndex(collection_id, index);
    fiu_do_on("DBImpl.UpdateCollectionIndexRecursively.fail_update_collection_index",
S
shengjh 已提交
1720
              status = Status(DB_META_TRANSACTION_FAILED, ""));
G
groot 已提交
1721
    if (!status.ok()) {
J
Jin Hai 已提交
1722
        ENGINE_LOG_ERROR << "Failed to update collection index info for collection: " << collection_id;
G
groot 已提交
1723 1724 1725
        return status;
    }

J
Jin Hai 已提交
1726 1727
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1728
    for (auto& schema : partition_array) {
1729
        status = UpdateCollectionIndexRecursively(schema.collection_id_, index);
G
groot 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
1739
DBImpl::WaitCollectionIndexRecursively(const std::string& collection_id, const CollectionIndex& index) {
G
groot 已提交
1740 1741 1742
    // 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;
1743
    if (utils::IsRawIndexType(index.engine_type_)) {
G
groot 已提交
1744
        file_types = {
J
Jin Hai 已提交
1745 1746
            static_cast<int32_t>(meta::SegmentSchema::NEW),
            static_cast<int32_t>(meta::SegmentSchema::NEW_MERGE),
G
groot 已提交
1747 1748 1749
        };
    } else {
        file_types = {
J
Jin Hai 已提交
1750 1751 1752
            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 已提交
1753 1754 1755 1756
        };
    }

    // get files to build index
1757 1758
    meta::SegmentsSchema collection_files;
    auto status = GetFilesToBuildIndex(collection_id, file_types, collection_files);
G
groot 已提交
1759 1760
    int times = 1;

1761
    while (!collection_files.empty()) {
G
groot 已提交
1762
        ENGINE_LOG_DEBUG << "Non index files detected! Will build index " << times;
1763
        if (!utils::IsRawIndexType(index.engine_type_)) {
1764
            status = meta_ptr_->UpdateCollectionFilesToIndex(collection_id);
G
groot 已提交
1765 1766 1767
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(std::min(10 * 1000, times * 100)));
1768
        GetFilesToBuildIndex(collection_id, file_types, collection_files);
1769
        ++times;
G
groot 已提交
1770

1771
        index_failed_checker_.IgnoreFailedIndexFiles(collection_files);
G
groot 已提交
1772 1773 1774
    }

    // build index for partition
J
Jin Hai 已提交
1775 1776
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1777
    for (auto& schema : partition_array) {
1778 1779
        status = WaitCollectionIndexRecursively(schema.collection_id_, index);
        fiu_do_on("DBImpl.WaitCollectionIndexRecursively.fail_build_collection_Index_for_partition",
S
shengjh 已提交
1780
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1781 1782 1783 1784 1785
        if (!status.ok()) {
            return status;
        }
    }

G
groot 已提交
1786
    // failed to build index for some files, return error
1787
    std::string err_msg;
1788 1789
    index_failed_checker_.GetErrMsgForCollection(collection_id, err_msg);
    fiu_do_on("DBImpl.WaitCollectionIndexRecursively.not_empty_err_msg", err_msg.append("fiu"));
1790 1791
    if (!err_msg.empty()) {
        return Status(DB_ERROR, err_msg);
G
groot 已提交
1792 1793
    }

G
groot 已提交
1794 1795 1796 1797
    return Status::OK();
}

Status
1798
DBImpl::DropCollectionIndexRecursively(const std::string& collection_id) {
J
Jin Hai 已提交
1799
    ENGINE_LOG_DEBUG << "Drop index for collection: " << collection_id;
1800 1801
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
    auto status = meta_ptr_->DropCollectionIndex(collection_id);
G
groot 已提交
1802 1803 1804 1805 1806
    if (!status.ok()) {
        return status;
    }

    // drop partition index
J
Jin Hai 已提交
1807 1808
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1809
    for (auto& schema : partition_array) {
1810 1811
        status = DropCollectionIndexRecursively(schema.collection_id_);
        fiu_do_on("DBImpl.DropCollectionIndexRecursively.fail_drop_collection_Index_for_partition",
S
shengjh 已提交
1812
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
1822
DBImpl::GetCollectionRowCountRecursively(const std::string& collection_id, uint64_t& row_count) {
G
groot 已提交
1823
    row_count = 0;
J
Jin Hai 已提交
1824
    auto status = meta_ptr_->Count(collection_id, row_count);
G
groot 已提交
1825 1826 1827 1828 1829
    if (!status.ok()) {
        return status;
    }

    // get partition row count
J
Jin Hai 已提交
1830 1831
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1832
    for (auto& schema : partition_array) {
G
groot 已提交
1833
        uint64_t partition_row_count = 0;
1834 1835
        status = GetCollectionRowCountRecursively(schema.collection_id_, partition_row_count);
        fiu_do_on("DBImpl.GetCollectionRowCountRecursively.fail_get_collection_rowcount_for_partition",
S
shengjh 已提交
1836
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
        if (!status.ok()) {
            return status;
        }

        row_count += partition_row_count;
    }

    return Status::OK();
}

1847 1848 1849 1850
Status
DBImpl::ExecWalRecord(const wal::MXLogRecord& record) {
    fiu_return_on("DBImpl.ExexWalRecord.return", Status(););

1851 1852
    auto collections_flushed = [&](const std::set<std::string>& collection_ids) -> uint64_t {
        if (collection_ids.empty()) {
1853 1854 1855 1856 1857
            return 0;
        }

        uint64_t max_lsn = 0;
        if (options_.wal_enable_) {
1858
            for (auto& collection : collection_ids) {
1859
                uint64_t lsn = 0;
1860 1861
                meta_ptr_->GetCollectionFlushLSN(collection, lsn);
                wal_mgr_->CollectionFlushed(collection, lsn);
1862 1863 1864 1865 1866 1867 1868
                if (lsn > max_lsn) {
                    max_lsn = lsn;
                }
            }
        }

        std::lock_guard<std::mutex> lck(merge_result_mutex_);
1869 1870
        for (auto& collection : collection_ids) {
            merge_collection_ids_.insert(collection);
1871 1872 1873 1874 1875 1876 1877 1878
        }
        return max_lsn;
    };

    Status status;

    switch (record.type) {
        case wal::MXLogType::InsertBinary: {
1879 1880
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
1881 1882 1883 1884
            if (!status.ok()) {
                return status;
            }

1885 1886
            std::set<std::string> flushed_collections;
            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
1887
                                             (record.data_size / record.length / sizeof(uint8_t)),
1888
                                             (const u_int8_t*)record.data, record.lsn, flushed_collections);
1889
            // even though !status.ok, run
1890
            collections_flushed(flushed_collections);
1891 1892 1893 1894 1895 1896 1897

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

        case wal::MXLogType::InsertVector: {
1898 1899
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
1900 1901 1902 1903
            if (!status.ok()) {
                return status;
            }

1904 1905
            std::set<std::string> flushed_collections;
            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
1906
                                             (record.data_size / record.length / sizeof(float)),
1907
                                             (const float*)record.data, record.lsn, flushed_collections);
1908
            // even though !status.ok, run
1909
            collections_flushed(flushed_collections);
1910 1911 1912 1913 1914 1915 1916

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

        case wal::MXLogType::Delete: {
J
Jin Hai 已提交
1917 1918
            std::vector<meta::CollectionSchema> partition_array;
            status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
1919 1920 1921 1922
            if (!status.ok()) {
                return status;
            }

1923
            std::vector<std::string> collection_ids{record.collection_id};
1924
            for (auto& partition : partition_array) {
1925 1926
                auto& partition_collection_id = partition.collection_id_;
                collection_ids.emplace_back(partition_collection_id);
1927 1928 1929
            }

            if (record.length == 1) {
1930
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
1931
                    status = mem_mgr_->DeleteVector(collection_id, *record.ids, record.lsn);
1932 1933 1934 1935 1936
                    if (!status.ok()) {
                        return status;
                    }
                }
            } else {
1937
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
1938
                    status = mem_mgr_->DeleteVectors(collection_id, record.length, record.ids, record.lsn);
1939 1940 1941 1942 1943 1944 1945 1946 1947
                    if (!status.ok()) {
                        return status;
                    }
                }
            }
            break;
        }

        case wal::MXLogType::Flush: {
J
Jin Hai 已提交
1948 1949 1950 1951
            if (!record.collection_id.empty()) {
                // flush one collection
                std::vector<meta::CollectionSchema> partition_array;
                status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
1952 1953 1954 1955
                if (!status.ok()) {
                    return status;
                }

1956
                std::vector<std::string> collection_ids{record.collection_id};
1957
                for (auto& partition : partition_array) {
1958 1959
                    auto& partition_collection_id = partition.collection_id_;
                    collection_ids.emplace_back(partition_collection_id);
1960 1961
                }

1962 1963
                std::set<std::string> flushed_collections;
                for (auto& collection_id : collection_ids) {
1964
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
J
Jin Hai 已提交
1965
                    status = mem_mgr_->Flush(collection_id);
1966 1967 1968
                    if (!status.ok()) {
                        break;
                    }
1969
                    flushed_collections.insert(collection_id);
1970 1971
                }

1972
                collections_flushed(flushed_collections);
1973 1974

            } else {
1975 1976
                // flush all collections
                std::set<std::string> collection_ids;
1977 1978
                {
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1979
                    status = mem_mgr_->Flush(collection_ids);
1980 1981
                }

1982
                uint64_t lsn = collections_flushed(collection_ids);
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
                if (options_.wal_enable_) {
                    wal_mgr_->RemoveOldFiles(lsn);
                }
            }
            break;
        }
    }

    return status;
}

void
DBImpl::BackgroundWalTask() {
    server::SystemInfo::GetInstance().Init();

1998
    std::chrono::system_clock::time_point next_auto_flush_time;
1999
    auto get_next_auto_flush_time = [&]() {
2000
        return std::chrono::system_clock::now() + std::chrono::seconds(options_.auto_flush_interval_);
2001
    };
2002 2003 2004
    if (options_.auto_flush_interval_ > 0) {
        next_auto_flush_time = get_next_auto_flush_time();
    }
2005 2006 2007 2008 2009

    wal::MXLogRecord record;

    auto auto_flush = [&]() {
        record.type = wal::MXLogType::Flush;
J
Jin Hai 已提交
2010
        record.collection_id.clear();
2011 2012 2013 2014 2015 2016 2017 2018
        ExecWalRecord(record);

        StartMetricTask();
        StartMergeTask();
        StartBuildIndexTask();
    };

    while (true) {
2019 2020 2021 2022 2023
        if (options_.auto_flush_interval_ > 0) {
            if (std::chrono::system_clock::now() >= next_auto_flush_time) {
                auto_flush();
                next_auto_flush_time = get_next_auto_flush_time();
            }
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
        }

        auto error_code = wal_mgr_->GetNextRecord(record);
        if (error_code != WAL_SUCCESS) {
            ENGINE_LOG_ERROR << "WAL background GetNextRecord error";
            break;
        }

        if (record.type != wal::MXLogType::None) {
            ExecWalRecord(record);
            if (record.type == wal::MXLogType::Flush) {
                // user req flush
                flush_task_swn_.Notify();

                // if user flush all manually, update auto flush also
J
Jin Hai 已提交
2039
                if (record.collection_id.empty() && options_.auto_flush_interval_ > 0) {
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
                    next_auto_flush_time = get_next_auto_flush_time();
                }
            }

        } else {
            if (!initialized_.load(std::memory_order_acquire)) {
                auto_flush();
                WaitMergeFileFinish();
                WaitBuildIndexFinish();
                ENGINE_LOG_DEBUG << "WAL background thread exit";
                break;
            }

2053 2054 2055 2056 2057
            if (options_.auto_flush_interval_ > 0) {
                bg_task_swn_.Wait_Until(next_auto_flush_time);
            } else {
                bg_task_swn_.Wait();
            }
2058 2059 2060 2061
        }
    }
}

2062 2063 2064 2065 2066
void
DBImpl::OnCacheInsertDataChanged(bool value) {
    options_.insert_cache_immediately_ = value;
}

2067 2068 2069 2070 2071
void
DBImpl::OnUseBlasThresholdChanged(int64_t threshold) {
    faiss::distance_compute_blas_threshold = threshold;
}

S
starlord 已提交
2072 2073
}  // namespace engine
}  // namespace milvus