DBImpl.cpp 71.7 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
J
Jin Hai 已提交
181
DBImpl::CreateTable(meta::CollectionSchema& table_schema) {
182
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
183
        return SHUTDOWN_ERROR;
S
starlord 已提交
184 185
    }

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

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

S
starlord 已提交
195
Status
J
Jin Hai 已提交
196
DBImpl::DropTable(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_) {
J
Jin Hai 已提交
202
        wal_mgr_->DropTable(collection_id);
203 204
    }

J
Jin Hai 已提交
205
    return DropTableRecursively(collection_id);
G
groot 已提交
206 207
}

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

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

S
starlord 已提交
219
Status
J
Jin Hai 已提交
220
DBImpl::HasTable(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
    }

J
Jin Hai 已提交
225
    return meta_ptr_->HasTable(collection_id, has_or_not);
226 227
}

228
Status
J
Jin Hai 已提交
229
DBImpl::HasNativeTable(const std::string& collection_id, bool& has_or_not_) {
230 231 232 233
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
234 235
    engine::meta::CollectionSchema table_schema;
    table_schema.collection_id_ = collection_id;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    auto status = DescribeTable(table_schema);
    if (!status.ok()) {
        has_or_not_ = false;
        return status;
    } else {
        if (!table_schema.owner_table_.empty()) {
            has_or_not_ = false;
            return Status(DB_NOT_FOUND, "");
        }

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

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

J
Jin Hai 已提交
257
    std::vector<meta::CollectionSchema> all_tables;
258 259 260 261 262 263 264 265 266 267 268
    auto status = meta_ptr_->AllTables(all_tables);

    // only return real tables, dont return partition tables
    table_schema_array.clear();
    for (auto& schema : all_tables) {
        if (schema.owner_table_.empty()) {
            table_schema_array.push_back(schema);
        }
    }

    return status;
G
groot 已提交
269 270
}

271
Status
J
Jin Hai 已提交
272
DBImpl::GetTableInfo(const std::string& collection_id, TableInfo& table_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) {
J
Jin Hai 已提交
304
        meta::SegmentsSchema table_files;
305 306
        status = meta_ptr_->FilesByType(name_tag.first, file_types, table_files);
        if (!status.ok()) {
J
Jin Hai 已提交
307
            std::string err_msg = "Failed to get collection info: " + status.ToString();
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
            ENGINE_LOG_ERROR << err_msg;
            return Status(DB_ERROR, err_msg);
        }

        std::vector<SegmentStat> segments_stat;
        for (auto& file : table_files) {
            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 330 331 332 333 334 335
            partition_stat.tag_ = milvus::engine::DEFAULT_PARTITON_TAG;
        } else {
            partition_stat.tag_ = name_tag.second;
        }

        partition_stat.segments_stat_.swap(segments_stat);
        table_info.partitions_stat_.emplace_back(partition_stat);
    }

    return Status::OK();
}

S
starlord 已提交
336
Status
J
Jin Hai 已提交
337
DBImpl::PreloadTable(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 tables
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);
S
shengjh 已提交
379
        fiu_do_on("DBImpl.PreloadTable.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

S
shengjh 已提交
385
        fiu_do_on("DBImpl.PreloadTable.exceed_cache", size = available_size + 1);
386 387 388 389 390 391 392 393 394 395 396

        try {
            fiu_do_on("DBImpl.PreloadTable.engine_throw_exception", throw std::exception());
            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
J
Jin Hai 已提交
409
DBImpl::UpdateTableFlag(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
    }

J
Jin Hai 已提交
414
    return meta_ptr_->UpdateTableFlag(collection_id, flag);
S
starlord 已提交
415 416
}

S
starlord 已提交
417
Status
J
Jin Hai 已提交
418
DBImpl::GetTableRowCount(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;
    }

J
Jin Hai 已提交
423
    return GetTableRowCountRecursively(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;
J
Jin Hai 已提交
434 435
    meta_ptr_->GetTableFlushLSN(collection_id, lsn);
    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 504
    if (options_.wal_enable_) {
        std::string target_table_name;
J
Jin Hai 已提交
505
        status = GetPartitionByTag(collection_id, partition_tag, target_table_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 581
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    bool has_table;
J
Jin Hai 已提交
582
    status = HasTable(collection_id, has_table);
583 584 585 586
    if (!status.ok()) {
        return status;
    }
    if (!has_table) {
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 622 623 624 625 626 627 628

    return status;
}

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

    ENGINE_LOG_DEBUG << "Begin flush all tables";

    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 639 640 641 642 643 644
            flush_task_swn_.Wait();
        }
    } else {
        ENGINE_LOG_DEBUG << "MemTable flush";
        wal::MXLogRecord record;
        record.type = wal::MXLogType::Flush;
        status = ExecWalRecord(record);
    }

    ENGINE_LOG_DEBUG << "End flush all tables";

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

J
Jin Hai 已提交
650 651
    engine::meta::CollectionSchema table_schema;
    table_schema.collection_id_ = collection_id;
652 653 654
    auto status = DescribeTable(table_schema);
    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 661
        } else {
            return status;
        }
    } else {
        if (!table_schema.owner_table_.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 725
        ENGINE_LOG_DEBUG << "Updating meta after compaction...";
        status = meta_ptr_->UpdateTableFiles(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 753 754
    Status status = meta_ptr_->CreateTableFile(compacted_file);

    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 778 779 780 781 782 783
        auto mark_status = meta_ptr_->UpdateTableFile(compacted_file);
        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;
Z
Zhiru Zhu 已提交
807 808 809 810 811
    status = meta_ptr_->GetTableFilesBySegmentId(segment_id, segment_files);
    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 833
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    bool has_table;
J
Jin Hai 已提交
834
    auto status = HasTable(collection_id, has_table);
835
    if (!has_table) {
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 847 848
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
    meta::SegmentsSchema table_files;
    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
    bool has_table;
J
Jin Hai 已提交
893
    auto status = HasTable(collection_id, has_table);
894
    if (!has_table) {
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
J
Jin Hai 已提交
903
    meta::SegmentsSchema table_files;
904 905 906 907 908 909 910 911 912
    status = meta_ptr_->GetTableFilesBySegmentId(segment_id, table_files);
    if (!status.ok()) {
        return status;
    }

    if (table_files.empty()) {
        return Status(DB_NOT_FOUND, "Segment does not exist");
    }

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

    // step 3: load segment ids and delete offset
    std::string segment_dir;
    engine::utils::GetParentPath(table_files[0].location_, segment_dir);
    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
J
Jin Hai 已提交
1023
DBImpl::CreateIndex(const std::string& collection_id, const TableIndex& 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 1031
    //    std::set<std::string> sync_table_ids;
    //    auto status = SyncMemData(sync_table_ids);
    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
S
starlord 已提交
1037
        TableIndex 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
S
starlord 已提交
1045
        TableIndex new_index = index;
S
starlord 已提交
1046
        new_index.metric_type_ = old_index.metric_type_;  // dont change metric type, it was defined by CreateTable
S
starlord 已提交
1047
        if (!utils::IsSameIndex(old_index, new_index)) {
J
Jin Hai 已提交
1048
            status = UpdateTableIndexRecursively(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
J
Jin Hai 已提交
1060 1061
    status = index_failed_checker_.CleanFailedIndexFileOfTable(collection_id);
    status = WaitTableIndexRecursively(collection_id, index);
S
starlord 已提交
1062

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

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

J
Jin Hai 已提交
1072
    return meta_ptr_->DescribeTableIndex(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 1082
    ENGINE_LOG_DEBUG << "Drop index for collection: " << collection_id;
    return DropTableIndexRecursively(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 1346
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (merge_thread_results_.empty()) {
            // collect merge files for all tables(if merge_table_ids_ is empty) for two reasons:
1347 1348
            // 1. other tables may still has un-merged files
            // 2. server may be closed unexpected, these un-merge files need to be merged when server restart
1349
            if (merge_table_ids_.empty()) {
J
Jin Hai 已提交
1350
                std::vector<meta::CollectionSchema> table_schema_array;
1351
                meta_ptr_->AllTables(table_schema_array);
G
groot 已提交
1352
                for (auto& schema : table_schema_array) {
J
Jin Hai 已提交
1353
                    merge_table_ids_.insert(schema.collection_id_);
1354 1355 1356 1357
                }
            }

            // start merge file thread
1358 1359 1360
            merge_thread_results_.push_back(
                merge_thread_pool_.enqueue(&DBImpl::BackgroundMerge, this, merge_table_ids_));
            merge_table_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 1374 1375 1376
    // step 1: create collection file
    meta::SegmentSchema table_file;
    table_file.collection_id_ = collection_id;
    table_file.file_type_ = meta::SegmentSchema::NEW_MERGE;
G
groot 已提交
1377
    Status status = meta_ptr_->CreateTableFile(table_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 =
Y
Yu Kun 已提交
1387 1388
        EngineFactory::Build(table_file.dimension_, table_file.location_, (EngineType)table_file.engine_type_,
                             (MetricType)table_file.metric_type_, table_file.nlist_);
1389
*/
J
Jin Hai 已提交
1390
    meta::SegmentsSchema updated;
1391 1392 1393 1394

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

Y
Yu Kun 已提交
1396
    for (auto& file : files) {
Y
Yu Kun 已提交
1397
        server::CollectMergeFilesMetrics metrics;
1398 1399 1400
        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_);
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
J
Jin Hai 已提交
1426
        table_file.file_type_ = meta::SegmentSchema::TO_DELETE;
S
starlord 已提交
1427 1428
        status = meta_ptr_->UpdateTableFile(table_file);
        ENGINE_LOG_DEBUG << "Failed to update file to index, mark file: " << table_file.file_id_ << " to to_delete";
X
Xu Peng 已提交
1429

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

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

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

1454 1455 1456
    return status;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return Status::OK();
}

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

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

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

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

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

    } 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 已提交
1636
            partition_name = collection_id;
1637 1638 1639
            return status;
        }

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

    return status;
}

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

    for (auto& tag : partition_tags) {
1656 1657 1658 1659
        // 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);
1660 1661

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

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

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

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

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

    Status status;
1686
    if (options_.wal_enable_) {
J
Jin Hai 已提交
1687
        wal_mgr_->DropTable(collection_id);
G
groot 已提交
1688 1689
    }

J
Jin Hai 已提交
1690 1691 1692
    status = mem_mgr_->EraseMemVector(collection_id);  // not allow insert
    status = meta_ptr_->DropTable(collection_id);      // soft delete collection
    index_failed_checker_.CleanFailedIndexFileOfTable(collection_id);
1693

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

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

    return Status::OK();
}

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

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

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

    return Status::OK();
}

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

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

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

        std::this_thread::sleep_for(std::chrono::milliseconds(std::min(10 * 1000, times * 100)));
J
Jin Hai 已提交
1767
        GetFilesToBuildIndex(collection_id, file_types, table_files);
1768
        ++times;
G
groot 已提交
1769

1770
        index_failed_checker_.IgnoreFailedIndexFiles(table_files);
G
groot 已提交
1771 1772 1773
    }

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

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

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

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

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

    return Status::OK();
}

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

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

        row_count += partition_row_count;
    }

    return Status::OK();
}

1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
Status
DBImpl::ExecWalRecord(const wal::MXLogRecord& record) {
    fiu_return_on("DBImpl.ExexWalRecord.return", Status(););

    auto tables_flushed = [&](const std::set<std::string>& table_ids) -> uint64_t {
        if (table_ids.empty()) {
            return 0;
        }

        uint64_t max_lsn = 0;
        if (options_.wal_enable_) {
J
Jin Hai 已提交
1857
            for (auto& collection : table_ids) {
1858
                uint64_t lsn = 0;
J
Jin Hai 已提交
1859 1860
                meta_ptr_->GetTableFlushLSN(collection, lsn);
                wal_mgr_->TableFlushed(collection, lsn);
1861 1862 1863 1864 1865 1866 1867
                if (lsn > max_lsn) {
                    max_lsn = lsn;
                }
            }
        }

        std::lock_guard<std::mutex> lck(merge_result_mutex_);
J
Jin Hai 已提交
1868 1869
        for (auto& collection : table_ids) {
            merge_table_ids_.insert(collection);
1870 1871 1872 1873 1874 1875 1876 1877 1878
        }
        return max_lsn;
    };

    Status status;

    switch (record.type) {
        case wal::MXLogType::InsertBinary: {
            std::string target_table_name;
J
Jin Hai 已提交
1879
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_table_name);
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
            if (!status.ok()) {
                return status;
            }

            std::set<std::string> flushed_tables;
            status = mem_mgr_->InsertVectors(target_table_name, record.length, record.ids,
                                             (record.data_size / record.length / sizeof(uint8_t)),
                                             (const u_int8_t*)record.data, record.lsn, flushed_tables);
            // even though !status.ok, run
            tables_flushed(flushed_tables);

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

        case wal::MXLogType::InsertVector: {
            std::string target_table_name;
J
Jin Hai 已提交
1898
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_table_name);
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
            if (!status.ok()) {
                return status;
            }

            std::set<std::string> flushed_tables;
            status = mem_mgr_->InsertVectors(target_table_name, record.length, record.ids,
                                             (record.data_size / record.length / sizeof(float)),
                                             (const float*)record.data, record.lsn, flushed_tables);
            // even though !status.ok, run
            tables_flushed(flushed_tables);

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

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

J
Jin Hai 已提交
1922
            std::vector<std::string> table_ids{record.collection_id};
1923
            for (auto& partition : partition_array) {
J
Jin Hai 已提交
1924
                auto& partition_table_id = partition.collection_id_;
1925 1926 1927 1928
                table_ids.emplace_back(partition_table_id);
            }

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

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

J
Jin Hai 已提交
1955
                std::vector<std::string> table_ids{record.collection_id};
1956
                for (auto& partition : partition_array) {
J
Jin Hai 已提交
1957
                    auto& partition_table_id = partition.collection_id_;
1958 1959 1960 1961
                    table_ids.emplace_back(partition_table_id);
                }

                std::set<std::string> flushed_tables;
J
Jin Hai 已提交
1962
                for (auto& collection_id : table_ids) {
1963
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
J
Jin Hai 已提交
1964
                    status = mem_mgr_->Flush(collection_id);
1965 1966 1967
                    if (!status.ok()) {
                        break;
                    }
J
Jin Hai 已提交
1968
                    flushed_tables.insert(collection_id);
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
                }

                tables_flushed(flushed_tables);

            } else {
                // flush all tables
                std::set<std::string> table_ids;
                {
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
                    status = mem_mgr_->Flush(table_ids);
                }

                uint64_t lsn = tables_flushed(table_ids);
                if (options_.wal_enable_) {
                    wal_mgr_->RemoveOldFiles(lsn);
                }
            }
            break;
        }
    }

    return status;
}

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

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

    wal::MXLogRecord record;

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

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

    while (true) {
2018 2019 2020 2021 2022
        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();
            }
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
        }

        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 已提交
2038
                if (record.collection_id.empty() && options_.auto_flush_interval_ > 0) {
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
                    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;
            }

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

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

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

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