“e4666f04f00306ed656749ef1da5deba8a905a0b”上不存在“cpp/src/db/DBImpl.cpp”
DBImpl.cpp 25.7 KB
Newer Older
X
Xu Peng 已提交
1 2 3 4 5
/*******************************************************************************
 * Copyright 上海赜睿信息科技有限公司(Zilliz) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 ******************************************************************************/
6
#include "DBImpl.h"
G
groot 已提交
7
#include "src/db/meta/SqliteMetaImpl.h"
G
groot 已提交
8
#include "Log.h"
9
#include "Utils.h"
G
groot 已提交
10
#include "engine/EngineFactory.h"
Z
update  
zhiru 已提交
11
#include "Factories.h"
G
groot 已提交
12
#include "metrics/Metrics.h"
G
groot 已提交
13
#include "scheduler/TaskScheduler.h"
J
jinhai 已提交
14

G
groot 已提交
15
#include "scheduler/context/DeleteContext.h"
G
groot 已提交
16
#include "utils/TimeRecorder.h"
G
groot 已提交
17
#include "meta/MetaConsts.h"
X
Xu Peng 已提交
18

X
Xu Peng 已提交
19
#include <assert.h>
X
Xu Peng 已提交
20
#include <chrono>
X
Xu Peng 已提交
21
#include <thread>
22
#include <iostream>
X
xj.lin 已提交
23
#include <cstring>
X
Xu Peng 已提交
24
#include <cache/CpuCacheMgr.h>
G
groot 已提交
25
#include <boost/filesystem.hpp>
W
wxyu 已提交
26
#include "scheduler/SchedInst.h"
Y
Yu Kun 已提交
27
#include <src/cache/GpuCacheMgr.h>
X
Xu Peng 已提交
28

X
Xu Peng 已提交
29
namespace zilliz {
J
jinhai 已提交
30
namespace milvus {
X
Xu Peng 已提交
31
namespace engine {
X
Xu Peng 已提交
32

G
groot 已提交
33 34
namespace {

J
jinhai 已提交
35 36 37
constexpr uint64_t METRIC_ACTION_INTERVAL = 1;
constexpr uint64_t COMPACT_ACTION_INTERVAL = 1;
constexpr uint64_t INDEX_ACTION_INTERVAL = 1;
G
groot 已提交
38

G
groot 已提交
39
}
Y
yu yunfeng 已提交
40

G
groot 已提交
41 42

DBImpl::DBImpl(const Options& options)
G
groot 已提交
43
    : options_(options),
X
Xu Peng 已提交
44
      shutting_down_(false),
G
groot 已提交
45 46
      compact_thread_pool_(1, 1),
      index_thread_pool_(1, 1) {
Z
update  
zhiru 已提交
47
    meta_ptr_ = DBMetaImplFactory::Build(options.meta, options.mode);
Z
zhiru 已提交
48
    mem_mgr_ = MemManagerFactory::Build(meta_ptr_, options_);
Z
update  
zhiru 已提交
49
    if (options.mode != Options::MODE::READ_ONLY) {
50
        ENGINE_LOG_TRACE << "StartTimerTasks";
Z
update  
zhiru 已提交
51 52
        StartTimerTasks();
    }
G
groot 已提交
53 54


X
Xu Peng 已提交
55 56
}

G
groot 已提交
57
Status DBImpl::CreateTable(meta::TableSchema& table_schema) {
G
groot 已提交
58
    return meta_ptr_->CreateTable(table_schema);
59 60
}

G
groot 已提交
61
Status DBImpl::DeleteTable(const std::string& table_id, const meta::DatesT& dates) {
G
groot 已提交
62
    //dates partly delete files of the table but currently we don't support
G
groot 已提交
63
    ENGINE_LOG_DEBUG << "Prepare to delete table " << table_id;
G
groot 已提交
64

65 66 67 68 69 70
    if (dates.empty()) {
        mem_mgr_->EraseMemVector(table_id); //not allow insert
        meta_ptr_->DeleteTable(table_id); //soft delete table

        //scheduler will determine when to delete table files
        TaskScheduler& scheduler = TaskScheduler::GetInstance();
W
wxyu 已提交
71 72 73
        DeleteContextPtr context = std::make_shared<DeleteContext>(table_id,
                                                               meta_ptr_,
                                                               ResMgrInst::GetInstance()->GetNumOfComputeResource());
74
        scheduler.Schedule(context);
W
wxyu 已提交
75
        context->WaitAndDelete();
76 77 78
    } else {
        meta_ptr_->DropPartitionsByDates(table_id, dates);
    }
G
groot 已提交
79

G
groot 已提交
80 81 82
    return Status::OK();
}

G
groot 已提交
83
Status DBImpl::DescribeTable(meta::TableSchema& table_schema) {
G
groot 已提交
84
    return meta_ptr_->DescribeTable(table_schema);
85 86
}

G
groot 已提交
87
Status DBImpl::HasTable(const std::string& table_id, bool& has_or_not) {
G
groot 已提交
88
    return meta_ptr_->HasTable(table_id, has_or_not);
89 90
}

G
groot 已提交
91
Status DBImpl::AllTables(std::vector<meta::TableSchema>& table_schema_array) {
G
groot 已提交
92
    return meta_ptr_->AllTables(table_schema_array);
G
groot 已提交
93 94
}

Y
Yu Kun 已提交
95
Status DBImpl::PreloadTable(const std::string &table_id) {
Y
Yu Kun 已提交
96
    meta::DatePartionedTableFilesSchema files;
Y
Yu Kun 已提交
97

Y
Yu Kun 已提交
98 99 100 101 102
    meta::DatesT dates;
    auto status = meta_ptr_->FilesToSearch(table_id, dates, files);
    if (!status.ok()) {
        return status;
    }
Y
Yu Kun 已提交
103

Y
Yu Kun 已提交
104 105
    int64_t size = 0;
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
Y
Yu Kun 已提交
106 107
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t available_size = cache_total - cache_usage;
Y
Yu Kun 已提交
108 109 110

    for(auto &day_files : files) {
        for (auto &file : day_files.second) {
G
groot 已提交
111
            ExecutionEnginePtr engine = EngineFactory::Build(file.dimension_, file.location_, (EngineType)file.engine_type_, (MetricType)file.metric_type_, file.nlist_);
Y
Yu Kun 已提交
112 113 114 115
            if(engine == nullptr) {
                ENGINE_LOG_ERROR << "Invalid engine type";
                return Status::Error("Invalid engine type");
            }
Y
Yu Kun 已提交
116

Y
Yu Kun 已提交
117
            size += engine->PhysicalSize();
Y
Yu Kun 已提交
118
            if (size > available_size) {
Y
Yu Kun 已提交
119 120 121 122
                break;
            } else {
                try {
                    //step 1: load index
Y
Yu Kun 已提交
123
                    engine->Load(true);
Y
Yu Kun 已提交
124 125 126 127 128
                } catch (std::exception &ex) {
                    std::string msg = "load to cache exception" + std::string(ex.what());
                    ENGINE_LOG_ERROR << msg;
                    return Status::Error(msg);
                }
Y
Yu Kun 已提交
129 130 131
            }
        }
    }
Y
Yu Kun 已提交
132
    return Status::OK();
Y
Yu Kun 已提交
133 134
}

G
groot 已提交
135 136 137 138
Status DBImpl::UpdateTableFlag(const std::string &table_id, int64_t flag) {
    return meta_ptr_->UpdateTableFlag(table_id, flag);
}

G
groot 已提交
139
Status DBImpl::GetTableRowCount(const std::string& table_id, uint64_t& row_count) {
G
groot 已提交
140
    return meta_ptr_->Count(table_id, row_count);
G
groot 已提交
141 142
}

G
groot 已提交
143
Status DBImpl::InsertVectors(const std::string& table_id_,
G
groot 已提交
144
        uint64_t n, const float* vectors, IDNumbers& vector_ids_) {
G
groot 已提交
145
    ENGINE_LOG_DEBUG << "Insert " << n << " vectors to cache";
Y
yu yunfeng 已提交
146

147 148 149
    Status status;
    zilliz::milvus::server::CollectInsertMetrics metrics(n, status);
    status = mem_mgr_->InsertVectors(table_id_, n, vectors, vector_ids_);
Y
yu yunfeng 已提交
150 151 152
//    std::chrono::microseconds time_span = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
//    double average_time = double(time_span.count()) / n;

G
groot 已提交
153 154
    ENGINE_LOG_DEBUG << "Insert vectors to cache finished";

G
groot 已提交
155
    return status;
X
Xu Peng 已提交
156 157
}

Y
Yu Kun 已提交
158
Status DBImpl::Query(const std::string &table_id, uint64_t k, uint64_t nq, uint64_t nprobe,
X
xj.lin 已提交
159
                      const float *vectors, QueryResults &results) {
Y
Yu Kun 已提交
160 161
    server::CollectQueryMetrics metrics(nq);

X
Xu Peng 已提交
162
    meta::DatesT dates = {meta::Meta::GetDate()};
Y
Yu Kun 已提交
163
    Status result = Query(table_id, k, nq, nprobe, vectors, dates, results);
Y
yu yunfeng 已提交
164

Y
yu yunfeng 已提交
165
    return result;
X
Xu Peng 已提交
166 167
}

Y
Yu Kun 已提交
168
Status DBImpl::Query(const std::string& table_id, uint64_t k, uint64_t nq, uint64_t nprobe,
X
Xu Peng 已提交
169
        const float* vectors, const meta::DatesT& dates, QueryResults& results) {
G
groot 已提交
170
    ENGINE_LOG_DEBUG << "Query by vectors " << table_id;
G
groot 已提交
171

172 173
    //get all table files from table
    meta::DatePartionedTableFilesSchema files;
G
groot 已提交
174
    auto status = meta_ptr_->FilesToSearch(table_id, dates, files);
175 176 177 178 179 180 181 182 183
    if (!status.ok()) { return status; }

    meta::TableFilesSchema file_id_array;
    for (auto &day_files : files) {
        for (auto &file : day_files.second) {
            file_id_array.push_back(file);
        }
    }

G
groot 已提交
184
    cache::CpuCacheMgr::GetInstance()->PrintInfo(); //print cache info before query
Y
Yu Kun 已提交
185
    status = QueryAsync(table_id, file_id_array, k, nq, nprobe, vectors, dates, results);
G
groot 已提交
186 187
    cache::CpuCacheMgr::GetInstance()->PrintInfo(); //print cache info after query
    return status;
G
groot 已提交
188
}
X
Xu Peng 已提交
189

190
Status DBImpl::Query(const std::string& table_id, const std::vector<std::string>& file_ids,
Y
Yu Kun 已提交
191
        uint64_t k, uint64_t nq, uint64_t nprobe, const float* vectors,
192
        const meta::DatesT& dates, QueryResults& results) {
G
groot 已提交
193 194
    ENGINE_LOG_DEBUG << "Query by file ids";

195
    //get specified files
196
    std::vector<size_t> ids;
197 198
    for (auto &id : file_ids) {
        meta::TableFileSchema table_file;
199 200
        table_file.table_id_ = table_id;
        std::string::size_type sz;
J
jinhai 已提交
201
        ids.push_back(std::stoul(id, &sz));
202 203
    }

X
xj.lin 已提交
204 205
    meta::DatePartionedTableFilesSchema files_array;
    auto status = meta_ptr_->FilesToSearch(table_id, ids, dates, files_array);
206 207
    if (!status.ok()) {
        return status;
208 209
    }

X
xj.lin 已提交
210 211 212 213 214 215 216 217
    meta::TableFilesSchema file_id_array;
    for (auto &day_files : files_array) {
        for (auto &file : day_files.second) {
            file_id_array.push_back(file);
        }
    }

    if(file_id_array.empty()) {
G
groot 已提交
218 219 220
        return Status::Error("Invalid file id");
    }

G
groot 已提交
221
    cache::CpuCacheMgr::GetInstance()->PrintInfo(); //print cache info before query
Y
Yu Kun 已提交
222
    status = QueryAsync(table_id, file_id_array, k, nq, nprobe, vectors, dates, results);
G
groot 已提交
223 224
    cache::CpuCacheMgr::GetInstance()->PrintInfo(); //print cache info after query
    return status;
225 226 227
}

Status DBImpl::QueryAsync(const std::string& table_id, const meta::TableFilesSchema& files,
Y
Yu Kun 已提交
228
                          uint64_t k, uint64_t nq, uint64_t nprobe, const float* vectors,
229
                          const meta::DatesT& dates, QueryResults& results) {
Y
Yu Kun 已提交
230 231
    server::CollectQueryMetrics metrics(nq);

G
groot 已提交
232
    server::TimeRecorder rc("");
G
groot 已提交
233 234

    //step 1: get files to search
G
groot 已提交
235
    ENGINE_LOG_DEBUG << "Engine query begin, index file count:" << files.size() << " date range count:" << dates.size();
Y
Yu Kun 已提交
236
    SearchContextPtr context = std::make_shared<SearchContext>(k, nq, nprobe, vectors);
237 238 239
    for (auto &file : files) {
        TableFileSchemaPtr file_ptr = std::make_shared<meta::TableFileSchema>(file);
        context->AddIndexFile(file_ptr);
G
groot 已提交
240 241
    }

G
groot 已提交
242
    //step 2: put search task to scheduler
G
groot 已提交
243 244
    TaskScheduler& scheduler = TaskScheduler::GetInstance();
    scheduler.Schedule(context);
G
groot 已提交
245 246

    context->WaitResult();
G
groot 已提交
247

G
groot 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    //step 3: print time cost information
    double load_cost = context->LoadCost();
    double search_cost = context->SearchCost();
    double reduce_cost = context->ReduceCost();
    std::string load_info = server::TimeRecorder::GetTimeSpanStr(load_cost);
    std::string search_info = server::TimeRecorder::GetTimeSpanStr(search_cost);
    std::string reduce_info = server::TimeRecorder::GetTimeSpanStr(reduce_cost);
    if(search_cost > 0.0 || reduce_cost > 0.0) {
        double total_cost = load_cost + search_cost + reduce_cost;
        double load_percent = load_cost/total_cost;
        double search_percent = search_cost/total_cost;
        double reduce_percent = reduce_cost/total_cost;

        ENGINE_LOG_DEBUG << "Engine load index totally cost:" << load_info << " percent: " << load_percent*100 << "%";
        ENGINE_LOG_DEBUG << "Engine search index totally cost:" << search_info << " percent: " << search_percent*100 << "%";
        ENGINE_LOG_DEBUG << "Engine reduce topk totally cost:" << reduce_info << " percent: " << reduce_percent*100 << "%";
    } else {
        ENGINE_LOG_DEBUG << "Engine load cost:" << load_info
            << " search cost: " << search_info
            << " reduce cost: " << reduce_info;
    }

    //step 4: construct results
J
jinhai 已提交
271
    results = context->GetResult();
G
groot 已提交
272
    rc.ElapseFromBegin("Engine query totally cost");
G
groot 已提交
273 274 275 276

    return Status::OK();
}

G
groot 已提交
277 278
void DBImpl::StartTimerTasks() {
    bg_timer_thread_ = std::thread(&DBImpl::BackgroundTimerTask, this);
X
Xu Peng 已提交
279 280
}

G
groot 已提交
281
void DBImpl::BackgroundTimerTask() {
X
Xu Peng 已提交
282
    Status status;
Y
yu yunfeng 已提交
283
    server::SystemInfo::GetInstance().Init();
X
Xu Peng 已提交
284
    while (true) {
G
groot 已提交
285 286 287 288 289 290 291
        if (shutting_down_.load(std::memory_order_acquire)){
            for(auto& iter : compact_thread_results_) {
                iter.wait();
            }
            for(auto& iter : index_thread_results_) {
                iter.wait();
            }
G
groot 已提交
292 293

            ENGINE_LOG_DEBUG << "DB background thread exit";
G
groot 已提交
294 295
            break;
        }
X
Xu Peng 已提交
296

G
groot 已提交
297
        std::this_thread::sleep_for(std::chrono::seconds(1));
X
Xu Peng 已提交
298

G
groot 已提交
299
        StartMetricTask();
G
groot 已提交
300 301 302
        StartCompactionTask();
        StartBuildIndexTask();
    }
X
Xu Peng 已提交
303 304
}

G
groot 已提交
305 306 307 308 309 310 311
void DBImpl::StartMetricTask() {
    static uint64_t metric_clock_tick = 0;
    metric_clock_tick++;
    if(metric_clock_tick%METRIC_ACTION_INTERVAL != 0) {
        return;
    }

312
    ENGINE_LOG_TRACE << "Start metric task";
G
groot 已提交
313

G
groot 已提交
314 315 316
    server::Metrics::GetInstance().KeepingAliveCounterIncrement(METRIC_ACTION_INTERVAL);
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
Y
Yu Kun 已提交
317
    server::Metrics::GetInstance().CpuCacheUsageGaugeSet(cache_usage*100/cache_total);
G
groot 已提交
318 319 320 321 322 323 324 325
    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();
G
groot 已提交
326

K
kun yu 已提交
327
    server::Metrics::GetInstance().CPUCoreUsagePercentSet();
K
kun yu 已提交
328 329
    server::Metrics::GetInstance().GPUTemperature();
    server::Metrics::GetInstance().CPUTemperature();
K
kun yu 已提交
330

331
    ENGINE_LOG_TRACE << "Metric task finished";
G
groot 已提交
332 333
}

G
groot 已提交
334
void DBImpl::StartCompactionTask() {
G
groot 已提交
335 336 337 338 339 340
    static uint64_t compact_clock_tick = 0;
    compact_clock_tick++;
    if(compact_clock_tick%COMPACT_ACTION_INTERVAL != 0) {
        return;
    }

G
groot 已提交
341
    //serialize memory data
G
groot 已提交
342
    std::set<std::string> temp_table_ids;
G
groot 已提交
343
    mem_mgr_->Serialize(temp_table_ids);
G
groot 已提交
344 345 346
    for(auto& id : temp_table_ids) {
        compact_table_ids_.insert(id);
    }
X
Xu Peng 已提交
347

348 349 350
    if(!temp_table_ids.empty()) {
        SERVER_LOG_DEBUG << "Insert cache serialized";
    }
G
groot 已提交
351

G
groot 已提交
352 353 354 355 356 357 358
    //compactiong has been finished?
    if(!compact_thread_results_.empty()) {
        std::chrono::milliseconds span(10);
        if (compact_thread_results_.back().wait_for(span) == std::future_status::ready) {
            compact_thread_results_.pop_back();
        }
    }
X
Xu Peng 已提交
359

G
groot 已提交
360 361 362 363 364 365
    //add new compaction task
    if(compact_thread_results_.empty()) {
        compact_thread_results_.push_back(
                compact_thread_pool_.enqueue(&DBImpl::BackgroundCompaction, this, compact_table_ids_));
        compact_table_ids_.clear();
    }
X
Xu Peng 已提交
366 367
}

G
groot 已提交
368
Status DBImpl::MergeFiles(const std::string& table_id, const meta::DateT& date,
369
        const meta::TableFilesSchema& files) {
G
groot 已提交
370
    ENGINE_LOG_DEBUG << "Merge files for table " << table_id;
G
groot 已提交
371

G
groot 已提交
372
    //step 1: create table file
X
Xu Peng 已提交
373
    meta::TableFileSchema table_file;
G
groot 已提交
374 375
    table_file.table_id_ = table_id;
    table_file.date_ = date;
376
    table_file.file_type_ = meta::TableFileSchema::NEW_MERGE;
G
groot 已提交
377
    Status status = meta_ptr_->CreateTableFile(table_file);
X
Xu Peng 已提交
378

379
    if (!status.ok()) {
G
groot 已提交
380
        ENGINE_LOG_ERROR << "Failed to create table: " << status.ToString();
381 382 383
        return status;
    }

G
groot 已提交
384
    //step 2: merge files
G
groot 已提交
385
    ExecutionEnginePtr index =
G
groot 已提交
386 387
            EngineFactory::Build(table_file.dimension_, table_file.location_, (EngineType)table_file.engine_type_,
                    (MetricType)table_file.metric_type_, table_file.nlist_);
388

389
    meta::TableFilesSchema updated;
X
Xu Peng 已提交
390
    long  index_size = 0;
391 392

    for (auto& file : files) {
Y
Yu Kun 已提交
393
        server::CollectMergeFilesMetrics metrics;
Y
yu yunfeng 已提交
394

G
groot 已提交
395
        index->Merge(file.location_);
396
        auto file_schema = file;
G
groot 已提交
397
        file_schema.file_type_ = meta::TableFileSchema::TO_DELETE;
398
        updated.push_back(file_schema);
G
groot 已提交
399
        ENGINE_LOG_DEBUG << "Merging file " << file_schema.file_id_;
G
groot 已提交
400
        index_size = index->Size();
X
Xu Peng 已提交
401

G
groot 已提交
402
        if (index_size >= file_schema.index_file_size_) break;
403 404
    }

G
groot 已提交
405 406 407 408 409 410 411
    //step 3: serialize to disk
    try {
        index->Serialize();
    } catch (std::exception& ex) {
        //typical error: out of disk space or permition denied
        std::string msg = "Serialize merged index encounter exception" + std::string(ex.what());
        ENGINE_LOG_ERROR << msg;
Y
yu yunfeng 已提交
412

G
groot 已提交
413 414 415
        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 已提交
416

G
groot 已提交
417 418 419 420 421 422 423
        std::cout << "ERROR: failed to persist merged index file: " << table_file.location_
                  << ", possible out of disk space" << std::endl;

        return Status::Error(msg);
    }

    //step 4: update table files state
G
groot 已提交
424
    table_file.file_type_ = meta::TableFileSchema::RAW;
425 426
    table_file.file_size_ = index->PhysicalSize();
    table_file.row_count_ = index->Count();
X
Xu Peng 已提交
427
    updated.push_back(table_file);
G
groot 已提交
428 429
    status = meta_ptr_->UpdateTableFiles(updated);
    ENGINE_LOG_DEBUG << "New merged file " << table_file.file_id_ <<
G
groot 已提交
430
        " of size " << index->PhysicalSize() << " bytes";
431

G
groot 已提交
432 433 434
    if(options_.insert_cache_immediately_) {
        index->Cache();
    }
X
Xu Peng 已提交
435

436 437 438
    return status;
}

G
groot 已提交
439
Status DBImpl::BackgroundMergeFiles(const std::string& table_id) {
440
    meta::DatePartionedTableFilesSchema raw_files;
G
groot 已提交
441
    auto status = meta_ptr_->FilesToMerge(table_id, raw_files);
X
Xu Peng 已提交
442
    if (!status.ok()) {
G
groot 已提交
443
        ENGINE_LOG_ERROR << "Failed to get merge files for table: " << table_id;
X
Xu Peng 已提交
444 445
        return status;
    }
446

X
Xu Peng 已提交
447
    bool has_merge = false;
448
    for (auto& kv : raw_files) {
X
Xu Peng 已提交
449
        auto files = kv.second;
G
groot 已提交
450 451
        if (files.size() < options_.merge_trigger_number) {
            ENGINE_LOG_DEBUG << "Files number not greater equal than merge trigger number, skip merge action";
X
Xu Peng 已提交
452 453
            continue;
        }
X
Xu Peng 已提交
454
        has_merge = true;
X
Xu Peng 已提交
455
        MergeFiles(table_id, kv.first, kv.second);
G
groot 已提交
456 457

        if (shutting_down_.load(std::memory_order_acquire)){
G
groot 已提交
458
            ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action for table " << table_id;
G
groot 已提交
459 460
            break;
        }
461
    }
X
Xu Peng 已提交
462

G
groot 已提交
463 464
    return Status::OK();
}
465

G
groot 已提交
466
void DBImpl::BackgroundCompaction(std::set<std::string> table_ids) {
467
    ENGINE_LOG_TRACE << " Background compaction thread start";
G
groot 已提交
468

G
groot 已提交
469
    Status status;
J
jinhai 已提交
470
    for (auto& table_id : table_ids) {
G
groot 已提交
471 472
        status = BackgroundMergeFiles(table_id);
        if (!status.ok()) {
G
groot 已提交
473
            ENGINE_LOG_ERROR << "Merge files for table " << table_id << " failed: " << status.ToString();
G
groot 已提交
474
            continue;//let other table get chance to merge
G
groot 已提交
475
        }
G
groot 已提交
476 477 478 479 480

        if (shutting_down_.load(std::memory_order_acquire)){
            ENGINE_LOG_DEBUG << "Server will shutdown, skip merge action";
            break;
        }
G
groot 已提交
481
    }
X
Xu Peng 已提交
482

G
groot 已提交
483
    meta_ptr_->Archive();
Z
update  
zhiru 已提交
484

485
    int ttl = 5*meta::M_SEC;//default: file will be deleted after 5 minutes
Z
update  
zhiru 已提交
486
    if (options_.mode == Options::MODE::CLUSTER) {
Z
update  
zhiru 已提交
487 488 489
        ttl = meta::D_SEC;
    }
    meta_ptr_->CleanUpFilesWithTTL(ttl);
G
groot 已提交
490

491
    ENGINE_LOG_TRACE << " Background compaction thread exit";
G
groot 已提交
492
}
X
Xu Peng 已提交
493

P
peng.xu 已提交
494
void DBImpl::StartBuildIndexTask(bool force) {
G
groot 已提交
495 496
    static uint64_t index_clock_tick = 0;
    index_clock_tick++;
P
peng.xu 已提交
497
    if(!force && (index_clock_tick%INDEX_ACTION_INTERVAL != 0)) {
G
groot 已提交
498 499 500
        return;
    }

G
groot 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513
    //build index has been finished?
    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();
        }
    }

    //add new build index task
    if(index_thread_results_.empty()) {
        index_thread_results_.push_back(
                index_thread_pool_.enqueue(&DBImpl::BackgroundBuildIndex, this));
    }
X
Xu Peng 已提交
514 515
}

P
peng.xu 已提交
516
Status DBImpl::BuildIndex(const std::string& table_id) {
P
peng.xu 已提交
517 518 519 520 521
    bool has = false;
    meta_ptr_->HasNonIndexFiles(table_id, has);
    int times = 1;

    while (has) {
G
groot 已提交
522
        ENGINE_LOG_DEBUG << "Non index files detected in " << table_id << "! Will build index " << times;
P
peng.xu 已提交
523
        meta_ptr_->UpdateTableFilesToIndex(table_id);
524
        /* StartBuildIndexTask(true); */
P
peng.xu 已提交
525 526 527 528 529
        std::this_thread::sleep_for(std::chrono::milliseconds(std::min(10*1000, times*100)));
        meta_ptr_->HasNonIndexFiles(table_id, has);
        times++;
    }
    return Status::OK();
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
}

Status DBImpl::CreateIndex(const std::string& table_id, const TableIndex& index) {
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);

        //step 1: check index difference
        TableIndex old_index;
        auto status = DescribeIndex(table_id, old_index);
        if(!status.ok()) {
            ENGINE_LOG_ERROR << "Failed to get table index info";
            return status;
        }

        if(utils::IsSameIndex(old_index, index)) {
            ENGINE_LOG_DEBUG << "Same index setting, no need to create index again";
            return Status::OK();
        }

        //step 2: drop old index files
        DropIndex(table_id);

G
groot 已提交
552
        if(index.engine_type_ == (int)EngineType::FAISS_IDMAP) {
G
groot 已提交
553 554 555 556
            ENGINE_LOG_DEBUG << "index type = IDMAP, no need to build index";
            return Status::OK();
        }

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
        //step 3: update index info

        status = meta_ptr_->UpdateTableIndexParam(table_id, index);
        if (!status.ok()) {
            ENGINE_LOG_ERROR << "Failed to update table index info";
            return status;
        }
    }

    bool has = false;
    auto status = meta_ptr_->HasNonIndexFiles(table_id, has);
    int times = 1;

    while (has) {
        ENGINE_LOG_DEBUG << "Non index files detected! Will build index " << times;
        status = meta_ptr_->UpdateTableFilesToIndex(table_id);
        /* StartBuildIndexTask(true); */
        std::this_thread::sleep_for(std::chrono::milliseconds(std::min(10*1000, times*100)));
        status = meta_ptr_->HasNonIndexFiles(table_id, has);
        times++;
    }
    return Status::OK();
}

Status DBImpl::DescribeIndex(const std::string& table_id, TableIndex& index) {
    return meta_ptr_->DescribeTableIndex(table_id, index);
}

Status DBImpl::DropIndex(const std::string& table_id) {
    return meta_ptr_->DropTableIndex(table_id);
P
peng.xu 已提交
587 588
}

G
groot 已提交
589
Status DBImpl::BuildIndex(const meta::TableFileSchema& file) {
G
groot 已提交
590 591 592
    ExecutionEnginePtr to_index =
            EngineFactory::Build(file.dimension_, file.location_, (EngineType)file.engine_type_,
                    (MetricType)file.metric_type_, file.nlist_);
G
groot 已提交
593
    if(to_index == nullptr) {
G
groot 已提交
594
        ENGINE_LOG_ERROR << "Invalid engine type";
G
groot 已提交
595 596
        return Status::Error("Invalid engine type");
    }
597

G
groot 已提交
598
    try {
G
groot 已提交
599
        //step 1: load index
G
groot 已提交
600
        to_index->Load(options_.insert_cache_immediately_);
G
groot 已提交
601 602 603 604 605

        //step 2: create table file
        meta::TableFileSchema table_file;
        table_file.table_id_ = file.table_id_;
        table_file.date_ = file.date_;
606
        table_file.file_type_ = meta::TableFileSchema::NEW_INDEX; //for multi-db-path, distribute index file averagely to each path
G
groot 已提交
607 608
        Status status = meta_ptr_->CreateTableFile(table_file);
        if (!status.ok()) {
G
groot 已提交
609
            ENGINE_LOG_ERROR << "Failed to create table: " << status.ToString();
G
groot 已提交
610 611 612 613
            return status;
        }

        //step 3: build index
614 615 616
        std::shared_ptr<ExecutionEngine> index;

        try {
Y
Yu Kun 已提交
617
            server::CollectBuildIndexMetrics metrics;
G
groot 已提交
618
            index = to_index->BuildIndex(table_file.location_, (EngineType)table_file.engine_type_);
619 620 621 622 623 624 625 626 627 628 629 630 631
        } catch (std::exception& ex) {
            //typical error: out of gpu memory
            std::string msg = "BuildIndex encounter exception" + std::string(ex.what());
            ENGINE_LOG_ERROR << msg;

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

            std::cout << "ERROR: failed to build index, index file is too large or gpu memory is not enough" << std::endl;

            return Status::Error(msg);
        }
632

G
groot 已提交
633 634 635 636 637 638 639 640 641
        //step 4: if table has been deleted, dont save index file
        bool has_table = false;
        meta_ptr_->HasTable(file.table_id_, has_table);
        if(!has_table) {
            meta_ptr_->DeleteTableFiles(file.table_id_);
            return Status::OK();
        }

        //step 5: save index file
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        try {
            index->Serialize();
        } catch (std::exception& ex) {
            //typical error: out of disk space or permition denied
            std::string msg = "Serialize index encounter exception" + std::string(ex.what());
            ENGINE_LOG_ERROR << msg;

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

            std::cout << "ERROR: failed to persist index file: " << table_file.location_
                << ", possible out of disk space" << std::endl;

            return Status::Error(msg);
        }
G
groot 已提交
658 659

        //step 6: update meta
G
groot 已提交
660
        table_file.file_type_ = meta::TableFileSchema::INDEX;
661 662
        table_file.file_size_ = index->PhysicalSize();
        table_file.row_count_ = index->Count();
X
Xu Peng 已提交
663

664 665
        auto origin_file = file;
        origin_file.file_type_ = meta::TableFileSchema::BACKUP;
X
Xu Peng 已提交
666

667
        meta::TableFilesSchema update_files = {table_file, origin_file};
668 669 670 671
        status = meta_ptr_->UpdateTableFiles(update_files);
        if(status.ok()) {
            ENGINE_LOG_DEBUG << "New index file " << table_file.file_id_ << " of size "
                             << index->PhysicalSize() << " bytes"
672
                             << " from file " << origin_file.file_id_;
X
Xu Peng 已提交
673

674 675 676 677 678
            if(options_.insert_cache_immediately_) {
                index->Cache();
            }
        } else {
            //failed to update meta, mark the new file as to_delete, don't delete old file
679 680 681
            origin_file.file_type_ = meta::TableFileSchema::TO_INDEX;
            status = meta_ptr_->UpdateTableFile(origin_file);
            ENGINE_LOG_DEBUG << "Failed to update file to index, mark file: " << origin_file.file_id_ << " to to_index";
682 683 684 685

            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";
G
groot 已提交
686
        }
G
groot 已提交
687 688

    } catch (std::exception& ex) {
G
groot 已提交
689 690 691
        std::string msg = "Build index encounter exception" + std::string(ex.what());
        ENGINE_LOG_ERROR << msg;
        return Status::Error(msg);
G
groot 已提交
692
    }
X
Xu Peng 已提交
693

X
Xu Peng 已提交
694 695 696
    return Status::OK();
}

G
groot 已提交
697
void DBImpl::BackgroundBuildIndex() {
698
    ENGINE_LOG_TRACE << " Background build index thread start";
G
groot 已提交
699

P
peng.xu 已提交
700
    std::unique_lock<std::mutex> lock(build_index_mutex_);
701
    meta::TableFilesSchema to_index_files;
G
groot 已提交
702
    meta_ptr_->FilesToIndex(to_index_files);
X
Xu Peng 已提交
703 704
    Status status;
    for (auto& file : to_index_files) {
X
Xu Peng 已提交
705
        status = BuildIndex(file);
X
Xu Peng 已提交
706
        if (!status.ok()) {
G
groot 已提交
707
            ENGINE_LOG_ERROR << "Building index for " << file.id_ << " failed: " << status.ToString();
X
Xu Peng 已提交
708
            return;
X
Xu Peng 已提交
709
        }
710

G
groot 已提交
711
        if (shutting_down_.load(std::memory_order_acquire)){
G
groot 已提交
712
            ENGINE_LOG_DEBUG << "Server will shutdown, skip build index action";
G
groot 已提交
713
            break;
X
Xu Peng 已提交
714
        }
715
    }
G
groot 已提交
716

717
    ENGINE_LOG_TRACE << " Background build index thread exit";
X
Xu Peng 已提交
718 719
}

G
groot 已提交
720
Status DBImpl::DropAll() {
G
groot 已提交
721
    return meta_ptr_->DropAll();
X
Xu Peng 已提交
722 723
}

G
groot 已提交
724
Status DBImpl::Size(uint64_t& result) {
G
groot 已提交
725
    return  meta_ptr_->Size(result);
X
Xu Peng 已提交
726 727
}

G
groot 已提交
728
DBImpl::~DBImpl() {
G
groot 已提交
729
    shutting_down_.store(true, std::memory_order_release);
X
Xu Peng 已提交
730
    bg_timer_thread_.join();
G
groot 已提交
731
    std::set<std::string> ids;
G
groot 已提交
732
    mem_mgr_->Serialize(ids);
X
Xu Peng 已提交
733 734
}

X
Xu Peng 已提交
735
} // namespace engine
J
jinhai 已提交
736
} // namespace milvus
X
Xu Peng 已提交
737
} // namespace zilliz