DBImpl.cpp 71.0 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"
S
starlord 已提交
33
#include "insert/MemMenagerFactory.h"
S
starlord 已提交
34
#include "meta/MetaConsts.h"
S
starlord 已提交
35 36
#include "meta/MetaFactory.h"
#include "meta/SqliteMetaImpl.h"
G
groot 已提交
37
#include "metrics/Metrics.h"
S
starlord 已提交
38
#include "scheduler/SchedInst.h"
Y
Yu Kun 已提交
39
#include "scheduler/job/BuildIndexJob.h"
S
starlord 已提交
40 41
#include "scheduler/job/DeleteJob.h"
#include "scheduler/job/SearchJob.h"
42 43 44
#include "segment/SegmentReader.h"
#include "segment/SegmentWriter.h"
#include "utils/Exception.h"
S
starlord 已提交
45
#include "utils/Log.h"
G
groot 已提交
46
#include "utils/StringHelpFunctions.h"
S
starlord 已提交
47
#include "utils/TimeRecorder.h"
48 49
#include "utils/ValidationUtil.h"
#include "wal/WalDefinations.h"
X
Xu Peng 已提交
50

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

G
groot 已提交
54 55
namespace {

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

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

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

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

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

78 79 80
    SetIdentity("DBImpl");
    AddCacheInsertDataListener();

S
starlord 已提交
81 82 83 84
    Start();
}

DBImpl::~DBImpl() {
85
    RemoveCacheInsertDataListener();
S
starlord 已提交
86 87 88
    Stop();
}

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

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

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    // 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 已提交
137
    }
S
starlord 已提交
138

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

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

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

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

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

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

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

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

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

S
starlord 已提交
179
Status
Y
Yu Kun 已提交
180
DBImpl::CreateTable(meta::TableSchema& table_schema) {
181
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
182
        return SHUTDOWN_ERROR;
S
starlord 已提交
183 184
    }

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

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

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

200 201 202 203 204
    if (options_.wal_enable_) {
        wal_mgr_->DropTable(table_id);
    }

    return DropTableRecursively(table_id);
G
groot 已提交
205 206
}

S
starlord 已提交
207
Status
Y
Yu Kun 已提交
208
DBImpl::DescribeTable(meta::TableSchema& table_schema) {
209
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
210
        return SHUTDOWN_ERROR;
S
starlord 已提交
211 212
    }

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

S
starlord 已提交
218
Status
Y
Yu Kun 已提交
219
DBImpl::HasTable(const std::string& table_id, bool& has_or_not) {
220
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
221
        return SHUTDOWN_ERROR;
S
starlord 已提交
222 223
    }

G
groot 已提交
224
    return meta_ptr_->HasTable(table_id, has_or_not);
225 226
}

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
Status
DBImpl::HasNativeTable(const std::string& table_id, bool& has_or_not_) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    engine::meta::TableSchema table_schema;
    table_schema.table_id_ = table_id;
    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 已提交
250
Status
Y
Yu Kun 已提交
251
DBImpl::AllTables(std::vector<meta::TableSchema>& table_schema_array) {
252
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
253
        return SHUTDOWN_ERROR;
S
starlord 已提交
254 255
    }

256 257 258 259 260 261 262 263 264 265 266 267
    std::vector<meta::TableSchema> all_tables;
    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 已提交
268 269
}

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
Status
DBImpl::GetTableInfo(const std::string& table_id, TableInfo& table_info) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // step1: get all partition ids
    std::vector<std::pair<std::string, std::string>> name2tag = {{table_id, milvus::engine::DEFAULT_PARTITON_TAG}};
    std::vector<meta::TableSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
        name2tag.push_back(std::make_pair(schema.table_id_, schema.partition_tag_));
    }

    // step2: get native table info
    std::vector<int> file_types{meta::TableFileSchema::FILE_TYPE::RAW, meta::TableFileSchema::FILE_TYPE::TO_INDEX,
                                meta::TableFileSchema::FILE_TYPE::INDEX};

    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"},
        {(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) {
        meta::TableFilesSchema table_files;
        status = meta_ptr_->FilesByType(name_tag.first, file_types, table_files);
        if (!status.ok()) {
            std::string err_msg = "Failed to get table info: " + status.ToString();
            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;
        if (name_tag.first == table_id) {
            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 已提交
334
Status
Y
Yu Kun 已提交
335
DBImpl::PreloadTable(const std::string& table_id) {
336
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
337
        return SHUTDOWN_ERROR;
S
starlord 已提交
338 339
    }

340
    // step 1: get all table files from parent table
341
    std::vector<size_t> ids;
G
groot 已提交
342
    meta::TableFilesSchema files_array;
343
    auto status = GetFilesToSearch(table_id, ids, files_array);
Y
Yu Kun 已提交
344 345 346
    if (!status.ok()) {
        return status;
    }
Y
Yu Kun 已提交
347

348
    // step 2: get files from partition tables
G
groot 已提交
349 350 351
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
352
        status = GetFilesToSearch(schema.table_id_, ids, files_array);
G
groot 已提交
353 354
    }

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

360 361 362 363
    // step 3: load file one by one
    ENGINE_LOG_DEBUG << "Begin pre-load table:" + table_id + ", totally " << files_array.size()
                     << " files need to be pre-loaded";
    TimeRecorderAuto rc("Pre-load table:" + table_id);
G
groot 已提交
364
    for (auto& file : files_array) {
365 366 367 368 369 370 371 372 373 374
        EngineType engine_type;
        if (file.file_type_ == meta::TableFileSchema::FILE_TYPE::RAW ||
            file.file_type_ == meta::TableFileSchema::FILE_TYPE::TO_INDEX ||
            file.file_type_ == meta::TableFileSchema::FILE_TYPE::BACKUP) {
            engine_type = server::ValidationUtil::IsBinaryMetricType(file.metric_type_) ? EngineType::FAISS_BIN_IDMAP
                                                                                        : EngineType::FAISS_IDMAP;
        } else {
            engine_type = (EngineType)file.engine_type_;
        }
        ExecutionEnginePtr engine = EngineFactory::Build(file.dimension_, file.location_, engine_type,
G
groot 已提交
375
                                                         (MetricType)file.metric_type_, file.nlist_);
S
shengjh 已提交
376
        fiu_do_on("DBImpl.PreloadTable.null_engine", engine = nullptr);
G
groot 已提交
377 378 379 380
        if (engine == nullptr) {
            ENGINE_LOG_ERROR << "Invalid engine type";
            return Status(DB_ERROR, "Invalid engine type");
        }
Y
Yu Kun 已提交
381

G
groot 已提交
382
        size += engine->PhysicalSize();
S
shengjh 已提交
383
        fiu_do_on("DBImpl.PreloadTable.exceed_cache", size = available_size + 1);
G
groot 已提交
384
        if (size > available_size) {
385
            ENGINE_LOG_DEBUG << "Pre-load canceled since cache almost full";
G
groot 已提交
386 387 388
            return Status(SERVER_CACHE_FULL, "Cache is full");
        } else {
            try {
S
shengjh 已提交
389
                fiu_do_on("DBImpl.PreloadTable.engine_throw_exception", throw std::exception());
390 391
                std::string msg = "Pre-loaded file: " + file.file_id_ + " size: " + std::to_string(file.file_size_);
                TimeRecorderAuto rc_1(msg);
G
groot 已提交
392 393 394 395 396
                engine->Load(true);
            } catch (std::exception& ex) {
                std::string msg = "Pre-load table encounter exception: " + std::string(ex.what());
                ENGINE_LOG_ERROR << msg;
                return Status(DB_ERROR, msg);
Y
Yu Kun 已提交
397 398 399
            }
        }
    }
G
groot 已提交
400

Y
Yu Kun 已提交
401
    return Status::OK();
Y
Yu Kun 已提交
402 403
}

S
starlord 已提交
404
Status
Y
Yu Kun 已提交
405
DBImpl::UpdateTableFlag(const std::string& table_id, int64_t flag) {
406
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
407
        return SHUTDOWN_ERROR;
S
starlord 已提交
408 409
    }

S
starlord 已提交
410 411 412
    return meta_ptr_->UpdateTableFlag(table_id, flag);
}

S
starlord 已提交
413
Status
Y
Yu Kun 已提交
414
DBImpl::GetTableRowCount(const std::string& table_id, uint64_t& row_count) {
415
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
416 417 418 419 420 421 422 423 424
        return SHUTDOWN_ERROR;
    }

    return GetTableRowCountRecursively(table_id, row_count);
}

Status
DBImpl::CreatePartition(const std::string& table_id, const std::string& partition_name,
                        const std::string& partition_tag) {
425
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
426 427 428
        return SHUTDOWN_ERROR;
    }

429 430 431
    uint64_t lsn = 0;
    meta_ptr_->GetTableFlushLSN(table_id, lsn);
    return meta_ptr_->CreatePartition(table_id, partition_name, partition_tag, lsn);
G
groot 已提交
432 433 434 435
}

Status
DBImpl::DropPartition(const std::string& partition_name) {
436
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
437
        return SHUTDOWN_ERROR;
S
starlord 已提交
438 439
    }

440 441 442 443 444 445
    mem_mgr_->EraseMemVector(partition_name);                // not allow insert
    auto status = meta_ptr_->DropPartition(partition_name);  // soft delete table
    if (!status.ok()) {
        ENGINE_LOG_ERROR << status.message();
        return status;
    }
G
groot 已提交
446 447 448 449 450 451 452 453

    // scheduler will determine when to delete table files
    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 已提交
454 455
}

S
starlord 已提交
456
Status
G
groot 已提交
457
DBImpl::DropPartitionByTag(const std::string& table_id, const std::string& partition_tag) {
458
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
459 460 461 462 463
        return SHUTDOWN_ERROR;
    }

    std::string partition_name;
    auto status = meta_ptr_->GetPartitionName(table_id, partition_tag, partition_name);
464 465 466 467 468
    if (!status.ok()) {
        ENGINE_LOG_ERROR << status.message();
        return status;
    }

G
groot 已提交
469 470 471 472
    return DropPartition(partition_name);
}

Status
G
groot 已提交
473
DBImpl::ShowPartitions(const std::string& table_id, std::vector<meta::TableSchema>& partition_schema_array) {
474
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
475 476 477
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
478
    return meta_ptr_->ShowPartitions(table_id, partition_schema_array);
G
groot 已提交
479 480 481
}

Status
G
groot 已提交
482
DBImpl::InsertVectors(const std::string& table_id, const std::string& partition_tag, VectorsData& vectors) {
S
starlord 已提交
483
    //    ENGINE_LOG_DEBUG << "Insert " << n << " vectors to cache";
484
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
485
        return SHUTDOWN_ERROR;
S
starlord 已提交
486
    }
Y
yu yunfeng 已提交
487

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

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

        if (!vectors.float_data_.empty()) {
            wal_mgr_->Insert(table_id, partition_tag, vectors.id_array_, vectors.float_data_);
        } else if (!vectors.binary_data_.empty()) {
            wal_mgr_->Insert(table_id, partition_tag, vectors.id_array_, vectors.binary_data_);
        }
511
        bg_task_swn_.Notify();
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532

    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
        record.table_id = table_id;
        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 已提交
533 534
    }

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    return status;
}

Status
DBImpl::DeleteVector(const std::string& table_id, IDNumber vector_id) {
    IDNumbers ids;
    ids.push_back(vector_id);
    return DeleteVectors(table_id, ids);
}

Status
DBImpl::DeleteVectors(const std::string& table_id, IDNumbers vector_ids) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    if (options_.wal_enable_) {
        wal_mgr_->DeleteById(table_id, vector_ids);
554
        bg_task_swn_.Notify();
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
        record.type = wal::MXLogType::Delete;
        record.table_id = table_id;
        record.ids = vector_ids.data();
        record.length = vector_ids.size();

        status = ExecWalRecord(record);
    }

    return status;
}

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

    Status status;
    bool has_table;
    status = HasTable(table_id, has_table);
    if (!status.ok()) {
        return status;
    }
    if (!has_table) {
        ENGINE_LOG_ERROR << "Table to flush does not exist: " << table_id;
        return Status(DB_NOT_FOUND, "Table to flush does not exist");
    }

    ENGINE_LOG_DEBUG << "Begin flush table: " << table_id;

    if (options_.wal_enable_) {
        ENGINE_LOG_DEBUG << "WAL flush";
        auto lsn = wal_mgr_->Flush(table_id);
        ENGINE_LOG_DEBUG << "wal_mgr_->Flush";
        if (lsn != 0) {
594
            bg_task_swn_.Notify();
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
            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;
        record.table_id = table_id;
        status = ExecWalRecord(record);
    }

    ENGINE_LOG_DEBUG << "End flush table: " << table_id;

    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) {
625
            bg_task_swn_.Notify();
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
            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
DBImpl::Compact(const std::string& table_id) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    engine::meta::TableSchema table_schema;
    table_schema.table_id_ = table_id;
    auto status = DescribeTable(table_schema);
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
            ENGINE_LOG_ERROR << "Table to compact does not exist: " << table_id;
            return Status(DB_NOT_FOUND, "Table to compact does not exist");
        } else {
            return status;
        }
    } else {
        if (!table_schema.owner_table_.empty()) {
            ENGINE_LOG_ERROR << "Table to compact does not exist: " << table_id;
            return Status(DB_NOT_FOUND, "Table to compact does not exist");
        }
    }

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

Z
Zhiru Zhu 已提交
665
    WaitBuildIndexFinish();
666

Z
Zhiru Zhu 已提交
667 668
    std::lock_guard<std::mutex> index_lock(index_result_mutex_);
    const std::lock_guard<std::mutex> merge_lock(flush_merge_compact_mutex_);
Z
Zhiru Zhu 已提交
669

Z
Zhiru Zhu 已提交
670
    ENGINE_LOG_DEBUG << "Compacting table: " << table_id;
Z
Zhiru Zhu 已提交
671

Z
Zhiru Zhu 已提交
672 673 674 675 676 677 678
    /*
        // Save table index
        TableIndex table_index;
        status = DescribeIndex(table_id, table_index);
        if (!status.ok()) {
            return status;
        }
679

Z
Zhiru Zhu 已提交
680 681 682 683 684 685 686 687 688 689 690 691
        // Drop all index
        status = DropIndex(table_id);
        if (!status.ok()) {
            return status;
        }

        // Then update table index to the previous index
        status = UpdateTableIndexRecursively(table_id, table_index);
        if (!status.ok()) {
            return status;
        }
    */
692
    // Get files to compact from meta.
Z
Zhiru Zhu 已提交
693 694
    std::vector<int> file_types{meta::TableFileSchema::FILE_TYPE::RAW, meta::TableFileSchema::FILE_TYPE::TO_INDEX,
                                meta::TableFileSchema::FILE_TYPE::BACKUP};
695 696 697 698 699 700 701 702 703 704 705
    meta::TableFilesSchema files_to_compact;
    status = meta_ptr_->FilesByType(table_id, file_types, files_to_compact);
    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 已提交
706 707 708

    meta::TableFilesSchema files_to_update;
    Status compact_status;
709
    for (auto& file : files_to_compact) {
Z
Zhiru Zhu 已提交
710 711 712
        // Check if the segment needs compacting
        std::string segment_dir;
        utils::GetParentPath(file.location_, segment_dir);
713

Z
Zhiru Zhu 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        segment::SegmentReader segment_reader(segment_dir);
        segment::DeletedDocsPtr deleted_docs;
        status = segment_reader.LoadDeletedDocs(deleted_docs);
        if (!status.ok()) {
            std::string msg = "Failed to load deleted_docs from " + segment_dir;
            ENGINE_LOG_ERROR << msg;
            return Status(DB_ERROR, msg);
        }

        if (deleted_docs->GetSize() != 0) {
            compact_status = CompactFile(table_id, file, files_to_update);

            if (!compact_status.ok()) {
                ENGINE_LOG_ERROR << "Compact failed for segment " << file.segment_id_ << ": "
                                 << compact_status.message();
                break;
            }
        } else {
            ENGINE_LOG_ERROR << "Segment " << file.segment_id_ << " has no deleted data. No need to compact";
733 734
        }
    }
Z
Zhiru Zhu 已提交
735 736 737 738 739 740 741

    if (compact_status.ok()) {
        ENGINE_LOG_DEBUG << "Finished compacting table: " << table_id;
    }

    ENGINE_LOG_ERROR << "Updating meta after compaction...";

Z
Zhiru Zhu 已提交
742
    /*
Z
Zhiru Zhu 已提交
743 744 745 746 747 748 749 750 751 752 753
    // Drop index again, in case some files were in the index building process during compacting
    status = DropIndex(table_id);
    if (!status.ok()) {
        return status;
    }

    // Update index
    status = UpdateTableIndexRecursively(table_id, table_index);
    if (!status.ok()) {
        return status;
    }
Z
Zhiru Zhu 已提交
754
     */
Z
Zhiru Zhu 已提交
755 756 757 758 759 760

    status = meta_ptr_->UpdateTableFiles(files_to_update);
    if (!status.ok()) {
        return status;
    }

761 762
    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_compact);

Z
Zhiru Zhu 已提交
763
    ENGINE_LOG_DEBUG << "Finished updating meta after compaction";
764 765 766 767 768

    return status;
}

Status
Z
Zhiru Zhu 已提交
769 770
DBImpl::CompactFile(const std::string& table_id, const meta::TableFileSchema& file,
                    meta::TableFilesSchema& files_to_update) {
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    ENGINE_LOG_DEBUG << "Compacting segment " << file.segment_id_ << " for table: " << table_id;

    // Create new table file
    meta::TableFileSchema compacted_file;
    compacted_file.table_id_ = table_id;
    // compacted_file.date_ = date;
    compacted_file.file_type_ = meta::TableFileSchema::NEW_MERGE;  // TODO: use NEW_MERGE for now
    Status status = meta_ptr_->CreateTableFile(compacted_file);

    if (!status.ok()) {
        ENGINE_LOG_ERROR << "Failed to create table file: " << status.message();
        return status;
    }

    // Compact (merge) file to the newly created table file

    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();
        compacted_file.file_type_ = meta::TableFileSchema::TO_DELETE;
        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;
    }

    // Update table files state
    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
    // else set file type to RAW, no need to build index
    if (compacted_file.engine_type_ != (int)EngineType::FAISS_IDMAP) {
        compacted_file.file_type_ = (segment_writer_ptr->Size() >= compacted_file.index_file_size_)
                                        ? meta::TableFileSchema::TO_INDEX
                                        : meta::TableFileSchema::RAW;
    } else {
        compacted_file.file_type_ = meta::TableFileSchema::RAW;
    }
    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";
        compacted_file.file_type_ = meta::TableFileSchema::TO_DELETE;
    }

Z
Zhiru Zhu 已提交
828
    files_to_update.emplace_back(compacted_file);
Z
Zhiru Zhu 已提交
829

Z
Zhiru Zhu 已提交
830 831 832 833 834 835 836 837 838
    // Set all files in segment to TO_DELETE
    auto& segment_id = file.segment_id_;
    meta::TableFilesSchema segment_files;
    status = meta_ptr_->GetTableFilesBySegmentId(segment_id, segment_files);
    if (!status.ok()) {
        return status;
    }
    for (auto& f : segment_files) {
        f.file_type_ = meta::TableFileSchema::FILE_TYPE::TO_DELETE;
Z
Zhiru Zhu 已提交
839 840
        files_to_update.emplace_back(f);
    }
841 842

    ENGINE_LOG_DEBUG << "Compacted segment " << compacted_file.segment_id_ << " from "
Z
Zhiru Zhu 已提交
843 844
                     << std::to_string(file.file_size_) << " bytes to " << std::to_string(compacted_file.file_size_)
                     << " bytes";
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 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 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

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

    return status;
}

Status
DBImpl::GetVectorByID(const std::string& table_id, const IDNumber& vector_id, VectorsData& vector) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    bool has_table;
    auto status = HasTable(table_id, has_table);
    if (!has_table) {
        ENGINE_LOG_ERROR << "Table " << table_id << " does not exist: ";
        return Status(DB_NOT_FOUND, "Table does not exist");
    }
    if (!status.ok()) {
        return status;
    }

    meta::TableFilesSchema files_to_query;

    std::vector<int> file_types{meta::TableFileSchema::FILE_TYPE::RAW, meta::TableFileSchema::FILE_TYPE::TO_INDEX,
                                meta::TableFileSchema::FILE_TYPE::BACKUP};
    meta::TableFilesSchema table_files;
    status = meta_ptr_->FilesByType(table_id, file_types, files_to_query);
    if (!status.ok()) {
        std::string err_msg = "Failed to get files for GetVectorByID: " + status.message();
        ENGINE_LOG_ERROR << err_msg;
        return status;
    }

    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
        meta::TableFilesSchema files;
        status = meta_ptr_->FilesByType(schema.table_id_, file_types, files);
        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);

    status = GetVectorByIdHelper(table_id, vector_id, vector, files_to_query);

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

    return status;
}

Status
DBImpl::GetVectorIDs(const std::string& table_id, const std::string& segment_id, IDNumbers& vector_ids) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // step 1: check table existence
    bool has_table;
    auto status = HasTable(table_id, has_table);
    if (!has_table) {
        ENGINE_LOG_ERROR << "Table " << table_id << " does not exist: ";
        return Status(DB_NOT_FOUND, "Table does not exist");
    }
    if (!status.ok()) {
        return status;
    }

    //  step 2: find segment
    meta::TableFilesSchema table_files;
    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");
    }

    // check the segment is belong to this table
    if (table_files[0].table_id_ != table_id) {
        // the segment could be in a partition under this table
        meta::TableSchema table_schema;
        table_schema.table_id_ = table_files[0].table_id_;
        status = DescribeTable(table_schema);
        if (table_schema.owner_table_ != table_id) {
            return Status(DB_NOT_FOUND, "Segment does not belong to this table");
        }
    }

    // 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 已提交
978

G
groot 已提交
979
    return status;
X
Xu Peng 已提交
980 981
}

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
Status
DBImpl::GetVectorByIdHelper(const std::string& table_id, IDNumber vector_id, VectorsData& vector,
                            const meta::TableFilesSchema& files) {
    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
                    bool is_binary = server::ValidationUtil::IsBinaryMetricType(file.metric_type_);
                    size_t single_vector_bytes = is_binary ? file.dimension_ / 8 : file.dimension_ * sizeof(float);
                    std::vector<uint8_t> raw_vector;
                    status = segment_reader.LoadVectors(offset * single_vector_bytes, single_vector_bytes, raw_vector);
                    if (!status.ok()) {
                        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 已提交
1048
Status
Y
Yu Kun 已提交
1049
DBImpl::CreateIndex(const std::string& table_id, const TableIndex& index) {
1050
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1051 1052 1053
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
1054
    // serialize memory data
1055 1056 1057
    //    std::set<std::string> sync_table_ids;
    //    auto status = SyncMemData(sync_table_ids);
    auto status = Flush();
G
groot 已提交
1058

S
starlord 已提交
1059 1060 1061
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);

S
starlord 已提交
1062
        // step 1: check index difference
S
starlord 已提交
1063
        TableIndex old_index;
G
groot 已提交
1064
        status = DescribeIndex(table_id, old_index);
S
starlord 已提交
1065
        if (!status.ok()) {
S
starlord 已提交
1066 1067 1068 1069
            ENGINE_LOG_ERROR << "Failed to get table index info for table: " << table_id;
            return status;
        }

S
starlord 已提交
1070
        // step 2: update index info
S
starlord 已提交
1071
        TableIndex new_index = index;
S
starlord 已提交
1072
        new_index.metric_type_ = old_index.metric_type_;  // dont change metric type, it was defined by CreateTable
S
starlord 已提交
1073
        if (!utils::IsSameIndex(old_index, new_index)) {
G
groot 已提交
1074
            status = UpdateTableIndexRecursively(table_id, new_index);
S
starlord 已提交
1075 1076 1077 1078 1079 1080
            if (!status.ok()) {
                return status;
            }
        }
    }

S
starlord 已提交
1081 1082
    // step 3: let merge file thread finish
    // to avoid duplicate data bug
1083 1084
    WaitMergeFileFinish();

S
starlord 已提交
1085
    // step 4: wait and build index
1086
    status = index_failed_checker_.CleanFailedIndexFileOfTable(table_id);
G
groot 已提交
1087
    status = BuildTableIndexRecursively(table_id, index);
S
starlord 已提交
1088

G
groot 已提交
1089
    return status;
S
starlord 已提交
1090 1091
}

S
starlord 已提交
1092
Status
Y
Yu Kun 已提交
1093
DBImpl::DescribeIndex(const std::string& table_id, TableIndex& index) {
1094
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1095 1096 1097
        return SHUTDOWN_ERROR;
    }

S
starlord 已提交
1098 1099 1100
    return meta_ptr_->DescribeTableIndex(table_id, index);
}

S
starlord 已提交
1101
Status
Y
Yu Kun 已提交
1102
DBImpl::DropIndex(const std::string& table_id) {
1103
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1104 1105 1106
        return SHUTDOWN_ERROR;
    }

S
starlord 已提交
1107
    ENGINE_LOG_DEBUG << "Drop index for table: " << table_id;
G
groot 已提交
1108
    return DropTableIndexRecursively(table_id);
S
starlord 已提交
1109 1110
}

S
starlord 已提交
1111
Status
1112 1113 1114
DBImpl::QueryByID(const std::shared_ptr<server::Context>& context, const std::string& table_id,
                  const std::vector<std::string>& partition_tags, uint64_t k, uint64_t nprobe, IDNumber vector_id,
                  ResultIds& result_ids, ResultDistances& result_distances) {
1115
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1116
        return SHUTDOWN_ERROR;
S
starlord 已提交
1117 1118
    }

1119 1120 1121 1122
    VectorsData vectors_data = VectorsData();
    vectors_data.id_array_.emplace_back(vector_id);
    vectors_data.vector_count_ = 1;
    Status result = Query(context, table_id, partition_tags, k, nprobe, vectors_data, result_ids, result_distances);
Y
yu yunfeng 已提交
1123
    return result;
X
Xu Peng 已提交
1124 1125
}

S
starlord 已提交
1126
Status
Z
Zhiru Zhu 已提交
1127
DBImpl::Query(const std::shared_ptr<server::Context>& context, const std::string& table_id,
G
groot 已提交
1128
              const std::vector<std::string>& partition_tags, uint64_t k, uint64_t nprobe, const VectorsData& vectors,
1129
              ResultIds& result_ids, ResultDistances& result_distances) {
Z
Zhiru Zhu 已提交
1130 1131
    auto query_ctx = context->Child("Query");

1132
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1133
        return SHUTDOWN_ERROR;
S
starlord 已提交
1134 1135
    }

G
groot 已提交
1136
    Status status;
1137
    std::vector<size_t> ids;
G
groot 已提交
1138
    meta::TableFilesSchema files_array;
1139

G
groot 已提交
1140 1141 1142
    if (partition_tags.empty()) {
        // no partition tag specified, means search in whole table
        // get all table files from parent table
1143
        status = GetFilesToSearch(table_id, ids, files_array);
G
groot 已提交
1144 1145 1146 1147
        if (!status.ok()) {
            return status;
        }

G
groot 已提交
1148 1149 1150
        std::vector<meta::TableSchema> partition_array;
        status = meta_ptr_->ShowPartitions(table_id, partition_array);
        for (auto& schema : partition_array) {
1151 1152 1153 1154 1155
            status = GetFilesToSearch(schema.table_id_, ids, files_array);
        }

        if (files_array.empty()) {
            return Status::OK();
G
groot 已提交
1156 1157 1158 1159 1160 1161 1162
        }
    } else {
        // get files from specified partitions
        std::set<std::string> partition_name_array;
        GetPartitionsByTags(table_id, partition_tags, partition_name_array);

        for (auto& partition_name : partition_name_array) {
1163 1164 1165 1166 1167
            status = GetFilesToSearch(partition_name, ids, files_array);
        }

        if (files_array.empty()) {
            return Status::OK();
1168 1169 1170
        }
    }

S
starlord 已提交
1171
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
G
groot 已提交
1172
    status = QueryAsync(query_ctx, table_id, files_array, k, nprobe, vectors, result_ids, result_distances);
S
starlord 已提交
1173
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1174 1175 1176

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

S
starlord 已提交
1177
    return status;
G
groot 已提交
1178
}
X
Xu Peng 已提交
1179

S
starlord 已提交
1180
Status
Z
Zhiru Zhu 已提交
1181
DBImpl::QueryByFileID(const std::shared_ptr<server::Context>& context, const std::string& table_id,
G
groot 已提交
1182
                      const std::vector<std::string>& file_ids, uint64_t k, uint64_t nprobe, const VectorsData& vectors,
1183
                      ResultIds& result_ids, ResultDistances& result_distances) {
Z
Zhiru Zhu 已提交
1184 1185
    auto query_ctx = context->Child("Query by file id");

1186
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1187
        return SHUTDOWN_ERROR;
S
starlord 已提交
1188 1189
    }

S
starlord 已提交
1190
    // get specified files
1191
    std::vector<size_t> ids;
Y
Yu Kun 已提交
1192
    for (auto& id : file_ids) {
1193
        meta::TableFileSchema table_file;
1194 1195
        table_file.table_id_ = table_id;
        std::string::size_type sz;
J
jinhai 已提交
1196
        ids.push_back(std::stoul(id, &sz));
1197 1198
    }

G
groot 已提交
1199
    meta::TableFilesSchema files_array;
1200
    auto status = GetFilesToSearch(table_id, ids, files_array);
1201 1202
    if (!status.ok()) {
        return status;
1203 1204
    }

S
shengjh 已提交
1205
    fiu_do_on("DBImpl.QueryByFileID.empty_files_array", files_array.clear());
G
groot 已提交
1206
    if (files_array.empty()) {
S
starlord 已提交
1207
        return Status(DB_ERROR, "Invalid file id");
G
groot 已提交
1208 1209
    }

S
starlord 已提交
1210
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
G
groot 已提交
1211
    status = QueryAsync(query_ctx, table_id, files_array, k, nprobe, vectors, result_ids, result_distances);
S
starlord 已提交
1212
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1213 1214 1215

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

S
starlord 已提交
1216
    return status;
1217 1218
}

S
starlord 已提交
1219
Status
Y
Yu Kun 已提交
1220
DBImpl::Size(uint64_t& result) {
1221
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1222
        return SHUTDOWN_ERROR;
S
starlord 已提交
1223 1224
    }

S
starlord 已提交
1225
    return meta_ptr_->Size(result);
S
starlord 已提交
1226 1227 1228
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1229
// internal methods
S
starlord 已提交
1230
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1231
Status
Z
Zhiru Zhu 已提交
1232
DBImpl::QueryAsync(const std::shared_ptr<server::Context>& context, const std::string& table_id,
G
groot 已提交
1233
                   const meta::TableFilesSchema& files, uint64_t k, uint64_t nprobe, const VectorsData& vectors,
Z
Zhiru Zhu 已提交
1234 1235 1236
                   ResultIds& result_ids, ResultDistances& result_distances) {
    auto query_async_ctx = context->Child("Query Async");

G
groot 已提交
1237
    server::CollectQueryMetrics metrics(vectors.vector_count_);
Y
Yu Kun 已提交
1238

S
starlord 已提交
1239
    TimeRecorder rc("");
G
groot 已提交
1240

1241
    // step 1: construct search job
1242
    auto status = OngoingFileChecker::GetInstance().MarkOngoingFiles(files);
1243

1244
    ENGINE_LOG_DEBUG << "Engine query begin, index file count: " << files.size();
G
groot 已提交
1245
    scheduler::SearchJobPtr job = std::make_shared<scheduler::SearchJob>(query_async_ctx, k, nprobe, vectors);
Y
Yu Kun 已提交
1246
    for (auto& file : files) {
S
starlord 已提交
1247
        scheduler::TableFileSchemaPtr file_ptr = std::make_shared<meta::TableFileSchema>(file);
W
wxyu 已提交
1248
        job->AddIndexFile(file_ptr);
G
groot 已提交
1249 1250
    }

1251
    // step 2: put search job to scheduler and wait result
S
starlord 已提交
1252
    scheduler::JobMgrInst::GetInstance()->Put(job);
W
wxyu 已提交
1253
    job->WaitResult();
1254

1255
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files);
W
wxyu 已提交
1256 1257
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
1258
    }
G
groot 已提交
1259

1260
    // step 3: construct results
G
groot 已提交
1261 1262
    result_ids = job->GetResultIds();
    result_distances = job->GetResultDistances();
S
starlord 已提交
1263
    rc.ElapseFromBegin("Engine query totally cost");
G
groot 已提交
1264

Z
Zhiru Zhu 已提交
1265 1266
    query_async_ctx->GetTraceContext()->GetSpan()->Finish();

G
groot 已提交
1267 1268 1269
    return Status::OK();
}

S
starlord 已提交
1270 1271
void
DBImpl::BackgroundTimerTask() {
Y
yu yunfeng 已提交
1272
    server::SystemInfo::GetInstance().Init();
X
Xu Peng 已提交
1273
    while (true) {
1274
        if (!initialized_.load(std::memory_order_acquire)) {
1275 1276
            WaitMergeFileFinish();
            WaitBuildIndexFinish();
S
starlord 已提交
1277 1278

            ENGINE_LOG_DEBUG << "DB background thread exit";
G
groot 已提交
1279 1280
            break;
        }
X
Xu Peng 已提交
1281

1282 1283 1284 1285 1286
        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 已提交
1287

G
groot 已提交
1288
        StartMetricTask();
1289
        StartMergeTask();
G
groot 已提交
1290 1291
        StartBuildIndexTask();
    }
X
Xu Peng 已提交
1292 1293
}

S
starlord 已提交
1294 1295
void
DBImpl::WaitMergeFileFinish() {
1296 1297 1298
    ENGINE_LOG_DEBUG << "Begin WaitMergeFileFinish";
    std::lock_guard<std::mutex> lck(merge_result_mutex_);
    for (auto& iter : merge_thread_results_) {
1299 1300
        iter.wait();
    }
1301
    ENGINE_LOG_DEBUG << "End WaitMergeFileFinish";
1302 1303
}

S
starlord 已提交
1304 1305
void
DBImpl::WaitBuildIndexFinish() {
1306
    ENGINE_LOG_DEBUG << "Begin WaitBuildIndexFinish";
1307
    std::lock_guard<std::mutex> lck(index_result_mutex_);
Y
Yu Kun 已提交
1308
    for (auto& iter : index_thread_results_) {
1309 1310
        iter.wait();
    }
1311
    ENGINE_LOG_DEBUG << "End WaitBuildIndexFinish";
1312 1313
}

S
starlord 已提交
1314 1315
void
DBImpl::StartMetricTask() {
G
groot 已提交
1316
    static uint64_t metric_clock_tick = 0;
1317
    ++metric_clock_tick;
S
starlord 已提交
1318
    if (metric_clock_tick % METRIC_ACTION_INTERVAL != 0) {
G
groot 已提交
1319 1320 1321 1322 1323 1324
        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 已提交
1325 1326
    fiu_do_on("DBImpl.StartMetricTask.InvalidTotalCache", cache_total = 0);

J
JinHai-CN 已提交
1327 1328 1329 1330 1331 1332 1333
    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 已提交
1334
    server::Metrics::GetInstance().GpuCacheUsageGaugeSet();
G
groot 已提交
1335 1336 1337 1338 1339 1340 1341 1342
    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 已提交
1343

K
kun yu 已提交
1344
    server::Metrics::GetInstance().CPUCoreUsagePercentSet();
K
kun yu 已提交
1345 1346
    server::Metrics::GetInstance().GPUTemperature();
    server::Metrics::GetInstance().CPUTemperature();
1347
    server::Metrics::GetInstance().PushToGateway();
G
groot 已提交
1348 1349
}

S
starlord 已提交
1350
void
1351
DBImpl::StartMergeTask() {
1352
    static uint64_t compact_clock_tick = 0;
1353
    ++compact_clock_tick;
S
starlord 已提交
1354
    if (compact_clock_tick % COMPACT_ACTION_INTERVAL != 0) {
1355 1356 1357
        return;
    }

1358 1359 1360
    if (!options_.wal_enable_) {
        Flush();
    }
1361

1362 1363
    // ENGINE_LOG_DEBUG << "Begin StartMergeTask";
    // merge task has been finished?
1364
    {
1365 1366
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (!merge_thread_results_.empty()) {
1367
            std::chrono::milliseconds span(10);
1368 1369
            if (merge_thread_results_.back().wait_for(span) == std::future_status::ready) {
                merge_thread_results_.pop_back();
1370
            }
G
groot 已提交
1371 1372
        }
    }
X
Xu Peng 已提交
1373

1374
    // add new merge task
1375
    {
1376 1377 1378
        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:
1379 1380
            // 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
1381
            if (merge_table_ids_.empty()) {
1382 1383
                std::vector<meta::TableSchema> table_schema_array;
                meta_ptr_->AllTables(table_schema_array);
G
groot 已提交
1384
                for (auto& schema : table_schema_array) {
1385
                    merge_table_ids_.insert(schema.table_id_);
1386 1387 1388 1389
                }
            }

            // start merge file thread
1390 1391 1392
            merge_thread_results_.push_back(
                merge_thread_pool_.enqueue(&DBImpl::BackgroundMerge, this, merge_table_ids_));
            merge_table_ids_.clear();
1393
        }
G
groot 已提交
1394
    }
1395 1396

    // ENGINE_LOG_DEBUG << "End StartMergeTask";
X
Xu Peng 已提交
1397 1398
}

S
starlord 已提交
1399
Status
1400
DBImpl::MergeFiles(const std::string& table_id, const meta::TableFilesSchema& files) {
Z
Zhiru Zhu 已提交
1401
    // const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1402

S
starlord 已提交
1403
    ENGINE_LOG_DEBUG << "Merge files for table: " << table_id;
S
starlord 已提交
1404

S
starlord 已提交
1405
    // step 1: create table file
X
Xu Peng 已提交
1406
    meta::TableFileSchema table_file;
G
groot 已提交
1407
    table_file.table_id_ = table_id;
1408
    table_file.file_type_ = meta::TableFileSchema::NEW_MERGE;
G
groot 已提交
1409
    Status status = meta_ptr_->CreateTableFile(table_file);
X
Xu Peng 已提交
1410

1411
    if (!status.ok()) {
S
starlord 已提交
1412
        ENGINE_LOG_ERROR << "Failed to create table: " << status.ToString();
1413 1414 1415
        return status;
    }

S
starlord 已提交
1416
    // step 2: merge files
1417
    /*
G
groot 已提交
1418
    ExecutionEnginePtr index =
Y
Yu Kun 已提交
1419 1420
        EngineFactory::Build(table_file.dimension_, table_file.location_, (EngineType)table_file.engine_type_,
                             (MetricType)table_file.metric_type_, table_file.nlist_);
1421
*/
1422
    meta::TableFilesSchema updated;
1423 1424 1425 1426

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

Y
Yu Kun 已提交
1428
    for (auto& file : files) {
Y
Yu Kun 已提交
1429
        server::CollectMergeFilesMetrics metrics;
1430 1431 1432
        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_);
1433
        auto file_schema = file;
G
groot 已提交
1434
        file_schema.file_type_ = meta::TableFileSchema::TO_DELETE;
1435
        updated.push_back(file_schema);
1436 1437
        auto size = segment_writer_ptr->Size();
        if (size >= file_schema.index_file_size_) {
S
starlord 已提交
1438
            break;
S
starlord 已提交
1439
        }
1440 1441
    }

S
starlord 已提交
1442
    // step 3: serialize to disk
S
starlord 已提交
1443
    try {
1444
        status = segment_writer_ptr->Serialize();
S
shengjh 已提交
1445 1446
        fiu_do_on("DBImpl.MergeFiles.Serialize_ThrowException", throw std::exception());
        fiu_do_on("DBImpl.MergeFiles.Serialize_ErrorStatus", status = Status(DB_ERROR, ""));
Y
Yu Kun 已提交
1447
    } catch (std::exception& ex) {
S
starlord 已提交
1448
        std::string msg = "Serialize merged index encounter exception: " + std::string(ex.what());
S
starlord 已提交
1449
        ENGINE_LOG_ERROR << msg;
G
groot 已提交
1450 1451
        status = Status(DB_ERROR, msg);
    }
Y
yu yunfeng 已提交
1452

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

G
groot 已提交
1456
        // if failed to serialize merge file to disk
1457
        // typical error: out of disk space, out of memory or permission denied
S
starlord 已提交
1458 1459 1460
        table_file.file_type_ = meta::TableFileSchema::TO_DELETE;
        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 已提交
1461

G
groot 已提交
1462
        return status;
S
starlord 已提交
1463 1464
    }

S
starlord 已提交
1465
    // step 4: update table files state
1466
    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
S
starlord 已提交
1467
    // else set file type to RAW, no need to build index
Y
Yu Kun 已提交
1468
    if (table_file.engine_type_ != (int)EngineType::FAISS_IDMAP) {
1469 1470 1471
        table_file.file_type_ = (segment_writer_ptr->Size() >= table_file.index_file_size_)
                                    ? meta::TableFileSchema::TO_INDEX
                                    : meta::TableFileSchema::RAW;
1472 1473 1474
    } else {
        table_file.file_type_ = meta::TableFileSchema::RAW;
    }
1475 1476
    table_file.file_size_ = segment_writer_ptr->Size();
    table_file.row_count_ = segment_writer_ptr->VectorCount();
X
Xu Peng 已提交
1477
    updated.push_back(table_file);
G
groot 已提交
1478
    status = meta_ptr_->UpdateTableFiles(updated);
1479 1480
    ENGINE_LOG_DEBUG << "New merged segment " << table_file.segment_id_ << " of size " << segment_writer_ptr->Size()
                     << " bytes";
1481

S
starlord 已提交
1482
    if (options_.insert_cache_immediately_) {
1483
        segment_writer_ptr->Cache();
S
starlord 已提交
1484
    }
X
Xu Peng 已提交
1485

1486 1487 1488
    return status;
}

S
starlord 已提交
1489
Status
Y
Yu Kun 已提交
1490
DBImpl::BackgroundMergeFiles(const std::string& table_id) {
Z
Zhiru Zhu 已提交
1491
    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1492 1493

    meta::TableFilesSchema raw_files;
G
groot 已提交
1494
    auto status = meta_ptr_->FilesToMerge(table_id, raw_files);
X
Xu Peng 已提交
1495
    if (!status.ok()) {
S
starlord 已提交
1496
        ENGINE_LOG_ERROR << "Failed to get merge files for table: " << table_id;
X
Xu Peng 已提交
1497 1498
        return status;
    }
1499

1500 1501 1502 1503
    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();
    }
1504

1505 1506 1507
    status = OngoingFileChecker::GetInstance().MarkOngoingFiles(raw_files);
    MergeFiles(table_id, raw_files);
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(raw_files);
G
groot 已提交
1508

1509 1510
    if (!initialized_.load(std::memory_order_acquire)) {
        ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action for table: " << table_id;
1511
    }
X
Xu Peng 已提交
1512

G
groot 已提交
1513 1514
    return Status::OK();
}
1515

S
starlord 已提交
1516
void
1517 1518
DBImpl::BackgroundMerge(std::set<std::string> table_ids) {
    // ENGINE_LOG_TRACE << " Background merge thread start";
S
starlord 已提交
1519

G
groot 已提交
1520
    Status status;
Y
Yu Kun 已提交
1521
    for (auto& table_id : table_ids) {
G
groot 已提交
1522 1523
        status = BackgroundMergeFiles(table_id);
        if (!status.ok()) {
S
starlord 已提交
1524
            ENGINE_LOG_ERROR << "Merge files for table " << table_id << " failed: " << status.ToString();
G
groot 已提交
1525
        }
S
starlord 已提交
1526

1527
        if (!initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
1528 1529 1530
            ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action";
            break;
        }
G
groot 已提交
1531
    }
X
Xu Peng 已提交
1532

G
groot 已提交
1533
    meta_ptr_->Archive();
Z
update  
zhiru 已提交
1534

1535
    {
G
groot 已提交
1536
        uint64_t ttl = 10 * meta::SECOND;  // default: file will be hard-deleted few seconds after soft-deleted
1537
        if (options_.mode_ == DBOptions::MODE::CLUSTER_WRITABLE) {
1538
            ttl = meta::HOUR;
1539
        }
G
groot 已提交
1540

1541
        meta_ptr_->CleanUpFilesWithTTL(ttl);
Z
update  
zhiru 已提交
1542
    }
S
starlord 已提交
1543

1544
    // ENGINE_LOG_TRACE << " Background merge thread exit";
G
groot 已提交
1545
}
X
Xu Peng 已提交
1546

S
starlord 已提交
1547 1548
void
DBImpl::StartBuildIndexTask(bool force) {
G
groot 已提交
1549
    static uint64_t index_clock_tick = 0;
1550
    ++index_clock_tick;
S
starlord 已提交
1551
    if (!force && (index_clock_tick % INDEX_ACTION_INTERVAL != 0)) {
G
groot 已提交
1552 1553 1554
        return;
    }

S
starlord 已提交
1555
    // build index has been finished?
1556 1557 1558 1559 1560 1561 1562
    {
        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 已提交
1563 1564 1565
        }
    }

S
starlord 已提交
1566
    // add new build index task
1567 1568 1569
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (index_thread_results_.empty()) {
S
starlord 已提交
1570
            index_thread_results_.push_back(index_thread_pool_.enqueue(&DBImpl::BackgroundBuildIndex, this));
1571
        }
G
groot 已提交
1572
    }
X
Xu Peng 已提交
1573 1574
}

S
starlord 已提交
1575 1576
void
DBImpl::BackgroundBuildIndex() {
P
peng.xu 已提交
1577
    std::unique_lock<std::mutex> lock(build_index_mutex_);
1578
    meta::TableFilesSchema to_index_files;
G
groot 已提交
1579
    meta_ptr_->FilesToIndex(to_index_files);
1580
    Status status = index_failed_checker_.IgnoreFailedIndexFiles(to_index_files);
1581

1582
    if (!to_index_files.empty()) {
G
groot 已提交
1583
        ENGINE_LOG_DEBUG << "Background build index thread begin";
1584
        status = OngoingFileChecker::GetInstance().MarkOngoingFiles(to_index_files);
1585

1586
        // step 2: put build index task to scheduler
G
groot 已提交
1587
        std::vector<std::pair<scheduler::BuildIndexJobPtr, scheduler::TableFileSchemaPtr>> job2file_map;
1588
        for (auto& file : to_index_files) {
G
groot 已提交
1589
            scheduler::BuildIndexJobPtr job = std::make_shared<scheduler::BuildIndexJob>(meta_ptr_, options_);
1590 1591
            scheduler::TableFileSchemaPtr file_ptr = std::make_shared<meta::TableFileSchema>(file);
            job->AddToIndexFiles(file_ptr);
G
groot 已提交
1592
            scheduler::JobMgrInst::GetInstance()->Put(job);
G
groot 已提交
1593
            job2file_map.push_back(std::make_pair(job, file_ptr));
1594
        }
G
groot 已提交
1595

G
groot 已提交
1596
        // step 3: wait build index finished and mark failed files
G
groot 已提交
1597 1598 1599 1600 1601 1602 1603 1604
        for (auto iter = job2file_map.begin(); iter != job2file_map.end(); ++iter) {
            scheduler::BuildIndexJobPtr job = iter->first;
            meta::TableFileSchema& file_schema = *(iter->second.get());
            job->WaitBuildIndexFinish();
            if (!job->GetStatus().ok()) {
                Status status = job->GetStatus();
                ENGINE_LOG_ERROR << "Building index job " << job->id() << " failed: " << status.ToString();

1605
                index_failed_checker_.MarkFailedIndexFile(file_schema, status.message());
G
groot 已提交
1606 1607
            } else {
                ENGINE_LOG_DEBUG << "Building index job " << job->id() << " succeed.";
G
groot 已提交
1608 1609

                index_failed_checker_.MarkSucceedIndexFile(file_schema);
G
groot 已提交
1610
            }
1611
            status = OngoingFileChecker::GetInstance().UnmarkOngoingFile(file_schema);
1612
        }
G
groot 已提交
1613 1614

        ENGINE_LOG_DEBUG << "Background build index thread finished";
Y
Yu Kun 已提交
1615
    }
X
Xu Peng 已提交
1616 1617
}

G
groot 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
Status
DBImpl::GetFilesToBuildIndex(const std::string& table_id, const std::vector<int>& file_types,
                             meta::TableFilesSchema& files) {
    files.clear();
    auto status = meta_ptr_->FilesByType(table_id, file_types, files);

    // only build index for files that row count greater than certain threshold
    for (auto it = files.begin(); it != files.end();) {
        if ((*it).file_type_ == static_cast<int>(meta::TableFileSchema::RAW) &&
            (*it).row_count_ < meta::BUILD_INDEX_THRESHOLD) {
            it = files.erase(it);
        } else {
1630
            ++it;
G
groot 已提交
1631 1632 1633 1634 1635 1636
        }
    }

    return Status::OK();
}

G
groot 已提交
1637
Status
1638
DBImpl::GetFilesToSearch(const std::string& table_id, const std::vector<size_t>& file_ids,
G
groot 已提交
1639
                         meta::TableFilesSchema& files) {
1640 1641
    ENGINE_LOG_DEBUG << "Collect files from table: " << table_id;

1642 1643
    meta::TableFilesSchema search_files;
    auto status = meta_ptr_->FilesToSearch(table_id, file_ids, search_files);
G
groot 已提交
1644 1645 1646 1647
    if (!status.ok()) {
        return status;
    }

1648 1649 1650
    for (auto& file : search_files) {
        files.push_back(file);
    }
G
groot 已提交
1651 1652 1653
    return Status::OK();
}

1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
Status
DBImpl::GetPartitionByTag(const std::string& table_id, const std::string& partition_tag, std::string& partition_name) {
    Status status;

    if (partition_tag.empty()) {
        partition_name = table_id;

    } 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) {
            partition_name = table_id;
            return status;
        }

        status = meta_ptr_->GetPartitionName(table_id, partition_tag, partition_name);
        if (!status.ok()) {
            ENGINE_LOG_ERROR << status.message();
        }
    }

    return status;
}

G
groot 已提交
1681 1682 1683
Status
DBImpl::GetPartitionsByTags(const std::string& table_id, const std::vector<std::string>& partition_tags,
                            std::set<std::string>& partition_name_array) {
G
groot 已提交
1684 1685
    std::vector<meta::TableSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(table_id, partition_array);
G
groot 已提交
1686 1687

    for (auto& tag : partition_tags) {
1688 1689 1690 1691
        // 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);
1692 1693 1694 1695 1696 1697

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
            partition_name_array.insert(table_id);
            return status;
        }

G
groot 已提交
1698
        for (auto& schema : partition_array) {
1699
            if (server::StringHelpFunctions::IsRegexMatch(schema.partition_tag_, valid_tag)) {
G
groot 已提交
1700 1701 1702 1703 1704 1705 1706 1707 1708
                partition_name_array.insert(schema.table_id_);
            }
        }
    }

    return Status::OK();
}

Status
1709
DBImpl::DropTableRecursively(const std::string& table_id) {
G
groot 已提交
1710 1711 1712 1713
    // dates partly delete files of the table but currently we don't support
    ENGINE_LOG_DEBUG << "Prepare to delete table " << table_id;

    Status status;
1714 1715
    if (options_.wal_enable_) {
        wal_mgr_->DropTable(table_id);
G
groot 已提交
1716 1717
    }

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
    status = mem_mgr_->EraseMemVector(table_id);  // not allow insert
    status = meta_ptr_->DropTable(table_id);      // soft delete table
    index_failed_checker_.CleanFailedIndexFileOfTable(table_id);

    // scheduler will determine when to delete table files
    auto nres = scheduler::ResMgrInst::GetInstance()->GetNumOfComputeResource();
    scheduler::DeleteJobPtr job = std::make_shared<scheduler::DeleteJob>(table_id, meta_ptr_, nres);
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitAndDelete();

G
groot 已提交
1728 1729 1730
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
1731
        status = DropTableRecursively(schema.table_id_);
S
shengjh 已提交
1732
        fiu_do_on("DBImpl.DropTableRecursively.failed", status = Status(DB_ERROR, ""));
G
groot 已提交
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
DBImpl::UpdateTableIndexRecursively(const std::string& table_id, const TableIndex& index) {
    DropIndex(table_id);

    auto status = meta_ptr_->UpdateTableIndex(table_id, index);
S
shengjh 已提交
1746 1747
    fiu_do_on("DBImpl.UpdateTableIndexRecursively.fail_update_table_index",
              status = Status(DB_META_TRANSACTION_FAILED, ""));
G
groot 已提交
1748 1749 1750 1751 1752
    if (!status.ok()) {
        ENGINE_LOG_ERROR << "Failed to update table index info for table: " << table_id;
        return status;
    }

G
groot 已提交
1753 1754 1755
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
G
groot 已提交
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        status = UpdateTableIndexRecursively(schema.table_id_, index);
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
DBImpl::BuildTableIndexRecursively(const std::string& table_id, const TableIndex& index) {
    // 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;
    if (index.engine_type_ == static_cast<int32_t>(EngineType::FAISS_IDMAP)) {
        file_types = {
            static_cast<int32_t>(meta::TableFileSchema::NEW),
            static_cast<int32_t>(meta::TableFileSchema::NEW_MERGE),
        };
    } else {
        file_types = {
            static_cast<int32_t>(meta::TableFileSchema::RAW),
            static_cast<int32_t>(meta::TableFileSchema::NEW),
            static_cast<int32_t>(meta::TableFileSchema::NEW_MERGE),
            static_cast<int32_t>(meta::TableFileSchema::NEW_INDEX),
            static_cast<int32_t>(meta::TableFileSchema::TO_INDEX),
        };
    }

    // get files to build index
G
groot 已提交
1786 1787
    meta::TableFilesSchema table_files;
    auto status = GetFilesToBuildIndex(table_id, file_types, table_files);
G
groot 已提交
1788 1789
    int times = 1;

G
groot 已提交
1790
    while (!table_files.empty()) {
G
groot 已提交
1791 1792 1793 1794 1795 1796
        ENGINE_LOG_DEBUG << "Non index files detected! Will build index " << times;
        if (index.engine_type_ != (int)EngineType::FAISS_IDMAP) {
            status = meta_ptr_->UpdateTableFilesToIndex(table_id);
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(std::min(10 * 1000, times * 100)));
G
groot 已提交
1797
        GetFilesToBuildIndex(table_id, file_types, table_files);
1798
        ++times;
G
groot 已提交
1799

1800
        index_failed_checker_.IgnoreFailedIndexFiles(table_files);
G
groot 已提交
1801 1802 1803
    }

    // build index for partition
G
groot 已提交
1804 1805 1806
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
G
groot 已提交
1807
        status = BuildTableIndexRecursively(schema.table_id_, index);
S
shengjh 已提交
1808 1809
        fiu_do_on("DBImpl.BuildTableIndexRecursively.fail_build_table_Index_for_partition",
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1810 1811 1812 1813 1814
        if (!status.ok()) {
            return status;
        }
    }

G
groot 已提交
1815
    // failed to build index for some files, return error
1816 1817
    std::string err_msg;
    index_failed_checker_.GetErrMsgForTable(table_id, err_msg);
S
shengjh 已提交
1818
    fiu_do_on("DBImpl.BuildTableIndexRecursively.not_empty_err_msg", err_msg.append("fiu"));
1819 1820
    if (!err_msg.empty()) {
        return Status(DB_ERROR, err_msg);
G
groot 已提交
1821 1822
    }

G
groot 已提交
1823 1824 1825 1826 1827 1828
    return Status::OK();
}

Status
DBImpl::DropTableIndexRecursively(const std::string& table_id) {
    ENGINE_LOG_DEBUG << "Drop index for table: " << table_id;
1829
    index_failed_checker_.CleanFailedIndexFileOfTable(table_id);
G
groot 已提交
1830 1831 1832 1833 1834 1835
    auto status = meta_ptr_->DropTableIndex(table_id);
    if (!status.ok()) {
        return status;
    }

    // drop partition index
G
groot 已提交
1836 1837 1838
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
G
groot 已提交
1839
        status = DropTableIndexRecursively(schema.table_id_);
S
shengjh 已提交
1840 1841
        fiu_do_on("DBImpl.DropTableIndexRecursively.fail_drop_table_Index_for_partition",
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
DBImpl::GetTableRowCountRecursively(const std::string& table_id, uint64_t& row_count) {
    row_count = 0;
    auto status = meta_ptr_->Count(table_id, row_count);
    if (!status.ok()) {
        return status;
    }

    // get partition row count
G
groot 已提交
1859 1860 1861
    std::vector<meta::TableSchema> partition_array;
    status = meta_ptr_->ShowPartitions(table_id, partition_array);
    for (auto& schema : partition_array) {
G
groot 已提交
1862 1863
        uint64_t partition_row_count = 0;
        status = GetTableRowCountRecursively(schema.table_id_, partition_row_count);
S
shengjh 已提交
1864 1865
        fiu_do_on("DBImpl.GetTableRowCountRecursively.fail_get_table_rowcount_for_partition",
                  status = Status(DB_ERROR, ""));
G
groot 已提交
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
        if (!status.ok()) {
            return status;
        }

        row_count += partition_row_count;
    }

    return Status::OK();
}

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
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_) {
            for (auto& table : table_ids) {
                uint64_t lsn = 0;
                meta_ptr_->GetTableFlushLSN(table, lsn);
                wal_mgr_->TableFlushed(table, lsn);
                if (lsn > max_lsn) {
                    max_lsn = lsn;
                }
            }
        }

        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        for (auto& table : table_ids) {
            merge_table_ids_.insert(table);
        }
        return max_lsn;
    };

    Status status;

    switch (record.type) {
        case wal::MXLogType::InsertBinary: {
            std::string target_table_name;
            status = GetPartitionByTag(record.table_id, record.partition_tag, target_table_name);
            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;
            status = GetPartitionByTag(record.table_id, record.partition_tag, target_table_name);
            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: {
            std::vector<meta::TableSchema> partition_array;
            status = meta_ptr_->ShowPartitions(record.table_id, partition_array);
            if (!status.ok()) {
                return status;
            }

            std::vector<std::string> table_ids{record.table_id};
            for (auto& partition : partition_array) {
                auto& partition_table_id = partition.table_id_;
                table_ids.emplace_back(partition_table_id);
            }

            if (record.length == 1) {
                for (auto& table_id : table_ids) {
                    status = mem_mgr_->DeleteVector(table_id, *record.ids, record.lsn);
                    if (!status.ok()) {
                        return status;
                    }
                }
            } else {
                for (auto& table_id : table_ids) {
                    status = mem_mgr_->DeleteVectors(table_id, record.length, record.ids, record.lsn);
                    if (!status.ok()) {
                        return status;
                    }
                }
            }
            break;
        }

        case wal::MXLogType::Flush: {
            if (!record.table_id.empty()) {
                // flush one table
                std::vector<meta::TableSchema> partition_array;
                status = meta_ptr_->ShowPartitions(record.table_id, partition_array);
                if (!status.ok()) {
                    return status;
                }

                std::vector<std::string> table_ids{record.table_id};
                for (auto& partition : partition_array) {
                    auto& partition_table_id = partition.table_id_;
                    table_ids.emplace_back(partition_table_id);
                }

                std::set<std::string> flushed_tables;
                for (auto& table_id : table_ids) {
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
                    status = mem_mgr_->Flush(table_id);
                    if (!status.ok()) {
                        break;
                    }
                    flushed_tables.insert(table_id);
                }

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

2027
    std::chrono::system_clock::time_point next_auto_flush_time;
2028
    auto get_next_auto_flush_time = [&]() {
2029
        return std::chrono::system_clock::now() + std::chrono::seconds(options_.auto_flush_interval_);
2030
    };
2031 2032 2033
    if (options_.auto_flush_interval_ > 0) {
        next_auto_flush_time = get_next_auto_flush_time();
    }
2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047

    wal::MXLogRecord record;

    auto auto_flush = [&]() {
        record.type = wal::MXLogType::Flush;
        record.table_id.clear();
        ExecWalRecord(record);

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

    while (true) {
2048 2049 2050 2051 2052
        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();
            }
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
        }

        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
2068
                if (record.table_id.empty() && options_.auto_flush_interval_ > 0) {
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
                    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;
            }

2082 2083 2084 2085 2086
            if (options_.auto_flush_interval_ > 0) {
                bg_task_swn_.Wait_Until(next_auto_flush_time);
            } else {
                bg_task_swn_.Wait();
            }
2087 2088 2089 2090
        }
    }
}

2091 2092 2093 2094 2095
void
DBImpl::OnCacheInsertDataChanged(bool value) {
    options_.insert_cache_immediately_ = value;
}

S
starlord 已提交
2096 2097
}  // namespace engine
}  // namespace milvus