DBImpl.cpp 14.0 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 7
#ifndef DBIMPL_CPP__
#define DBIMPL_CPP__
X
Xu Peng 已提交
8

X
Xu Peng 已提交
9
#include <assert.h>
X
Xu Peng 已提交
10
#include <chrono>
X
Xu Peng 已提交
11
#include <thread>
12
#include <iostream>
X
xj.lin 已提交
13
#include <cstring>
14
#include <easylogging++.h>
X
Xu Peng 已提交
15
#include <cache/CpuCacheMgr.h>
16

X
Xu Peng 已提交
17 18 19
#include "DBImpl.h"
#include "DBMetaImpl.h"
#include "Env.h"
X
Xu Peng 已提交
20

X
Xu Peng 已提交
21 22 23
namespace zilliz {
namespace vecwise {
namespace engine {
X
Xu Peng 已提交
24

25 26
template<typename EngineT>
DBImpl<EngineT>::DBImpl(const Options& options)
X
Xu Peng 已提交
27 28
    : _env(options.env),
      _options(options),
29
      _bg_compaction_scheduled(false),
X
Xu Peng 已提交
30
      _shutting_down(false),
X
Xu Peng 已提交
31
      bg_build_index_started_(false),
X
Xu Peng 已提交
32
      _pMeta(new meta::DBMetaImpl(_options.meta)),
33
      _pMemMgr(new MemManager<EngineT>(_pMeta, _options)) {
X
Xu Peng 已提交
34
    start_timer_task(_options.memory_sync_interval);
X
Xu Peng 已提交
35 36
}

37
template<typename EngineT>
38
Status DBImpl<EngineT>::add_group(meta::TableSchema& group_info) {
39
    return _pMeta->add_group(group_info);
40 41
}

42
template<typename EngineT>
43
Status DBImpl<EngineT>::get_group(meta::TableSchema& group_info) {
44
    return _pMeta->get_group(group_info);
45 46
}

X
Xu Peng 已提交
47 48 49 50 51 52
template<typename EngineT>
Status DBImpl<EngineT>::delete_vectors(const std::string& group_id,
        const meta::DatesT& dates) {
    return _pMeta->delete_group_partitions(group_id, dates);
}

53 54
template<typename EngineT>
Status DBImpl<EngineT>::has_group(const std::string& group_id_, bool& has_or_not_) {
55 56 57
    return _pMeta->has_group(group_id_, has_or_not_);
}

58 59
template<typename EngineT>
Status DBImpl<EngineT>::get_group_files(const std::string& group_id,
X
Xu Peng 已提交
60
                               const int date_delta,
61
                               meta::GroupFilesSchema& group_files_info) {
X
Xu Peng 已提交
62
    return _pMeta->get_group_files(group_id, date_delta, group_files_info);
63

X
Xu Peng 已提交
64 65
}

66 67
template<typename EngineT>
Status DBImpl<EngineT>::add_vectors(const std::string& group_id_,
68
        size_t n, const float* vectors, IDNumbers& vector_ids_) {
X
Xu Peng 已提交
69 70 71 72 73 74
    Status status = _pMemMgr->add_vectors(group_id_, n, vectors, vector_ids_);
    if (!status.ok()) {
        return status;
    }
}

75 76
template<typename EngineT>
Status DBImpl<EngineT>::search(const std::string &group_id, size_t k, size_t nq,
X
xj.lin 已提交
77
                      const float *vectors, QueryResults &results) {
X
Xu Peng 已提交
78 79 80 81
    meta::DatesT dates = {meta::Meta::GetDate()};
    return search(group_id, k, nq, vectors, dates, results);
}

82 83
template<typename EngineT>
Status DBImpl<EngineT>::search(const std::string& group_id, size_t k, size_t nq,
X
Xu Peng 已提交
84 85
        const float* vectors, const meta::DatesT& dates, QueryResults& results) {

X
xj.lin 已提交
86
    meta::DatePartionedGroupFilesSchema files;
X
Xu Peng 已提交
87
    auto status = _pMeta->files_to_search(group_id, dates, files);
X
xj.lin 已提交
88 89
    if (!status.ok()) { return status; }

G
groot 已提交
90
    LOG(DEBUG) << "Search DateT Size=" << files.size();
X
Xu Peng 已提交
91

X
xj.lin 已提交
92 93 94 95
    meta::GroupFilesSchema index_files;
    meta::GroupFilesSchema raw_files;
    for (auto &day_files : files) {
        for (auto &file : day_files.second) {
96
            file.file_type == meta::TableFileSchema::INDEX ?
X
xj.lin 已提交
97
            index_files.push_back(file) : raw_files.push_back(file);
X
xj.lin 已提交
98 99 100
        }
    }

X
xj.lin 已提交
101 102 103 104 105 106
    int dim = 0;
    if (!index_files.empty()) {
        dim = index_files[0].dimension;
    } else if (!raw_files.empty()) {
        dim = raw_files[0].dimension;
    } else {
G
groot 已提交
107
        LOG(DEBUG) << "no files to search";
X
xj.lin 已提交
108 109
        return Status::OK();
    }
X
xj.lin 已提交
110 111

    {
X
xj.lin 已提交
112 113 114 115
        // [{ids, distence}, ...]
        using SearchResult = std::pair<std::vector<long>, std::vector<float>>;
        std::vector<SearchResult> batchresult(nq); // allocate nq cells.

X
xj.lin 已提交
116
        auto cluster = [&](long *nns, float *dis, const int& k) -> void {
X
xj.lin 已提交
117 118 119 120 121 122 123 124 125
            for (int i = 0; i < nq; ++i) {
                auto f_begin = batchresult[i].first.cbegin();
                auto s_begin = batchresult[i].second.cbegin();
                batchresult[i].first.insert(f_begin, nns + i * k, nns + i * k + k);
                batchresult[i].second.insert(s_begin, dis + i * k, dis + i * k + k);
            }
        };

        // Allocate Memory
X
xj.lin 已提交
126 127
        float *output_distence;
        long *output_ids;
X
xj.lin 已提交
128 129 130 131
        output_distence = (float *) malloc(k * nq * sizeof(float));
        output_ids = (long *) malloc(k * nq * sizeof(long));
        memset(output_distence, 0, k * nq * sizeof(float));
        memset(output_ids, 0, k * nq * sizeof(long));
X
xj.lin 已提交
132

X
Xu Peng 已提交
133 134
        long search_set_size = 0;

X
xj.lin 已提交
135 136
        auto search_in_index = [&](meta::GroupFilesSchema& file_vec) -> void {
            for (auto &file : file_vec) {
137
                EngineT index(file.dimension, file.location);
138 139
                index.Load();
                auto file_size = index.PhysicalSize()/(1024*1024);
X
Xu Peng 已提交
140
                search_set_size += file_size;
X
Xu Peng 已提交
141
                LOG(DEBUG) << "Search file_type " << file.file_type << " Of Size: "
X
Xu Peng 已提交
142
                    << file_size << " M";
X
xj.lin 已提交
143 144 145 146

                int inner_k = index.Count() < k ? index.Count() : k;
                index.Search(nq, vectors, inner_k, output_distence, output_ids);
                cluster(output_ids, output_distence, inner_k); // cluster to each query
X
xj.lin 已提交
147 148
                memset(output_distence, 0, k * nq * sizeof(float));
                memset(output_ids, 0, k * nq * sizeof(long));
X
Xu Peng 已提交
149
            }
X
xj.lin 已提交
150
        };
X
xj.lin 已提交
151

X
xj.lin 已提交
152 153 154 155
        auto topk_cpu = [](const std::vector<float> &input_data,
                           const int &k,
                           float *output_distence,
                           long *output_ids) -> void {
X
xj.lin 已提交
156
            std::map<float, std::vector<int>> inverted_table;
X
xj.lin 已提交
157
            for (int i = 0; i < input_data.size(); ++i) {
X
xj.lin 已提交
158 159 160 161 162 163 164
                if (inverted_table.count(input_data[i]) == 1) {
                    auto& ori_vec = inverted_table[input_data[i]];
                    ori_vec.push_back(i);
                }
                else {
                    inverted_table[input_data[i]] = std::vector<int>{i};
                }
X
xj.lin 已提交
165 166 167
            }

            int count = 0;
X
xj.lin 已提交
168 169 170 171 172
            for (auto &item : inverted_table){
                if (count == k) break;
                for (auto &id : item.second){
                    output_distence[count] = item.first;
                    output_ids[count] = id;
X
xj.lin 已提交
173
                    if (++count == k) break;
X
xj.lin 已提交
174
                }
X
xj.lin 已提交
175 176
            }
        };
X
xj.lin 已提交
177 178 179 180 181
        auto cluster_topk = [&]() -> void {
            QueryResult res;
            for (auto &result_pair : batchresult) {
                auto &dis = result_pair.second;
                auto &nns = result_pair.first;
X
xj.lin 已提交
182

X
xj.lin 已提交
183
                topk_cpu(dis, k, output_distence, output_ids);
X
xj.lin 已提交
184 185 186

                int inner_k = dis.size() < k ? dis.size() : k;
                for (int i = 0; i < inner_k; ++i) {
X
xj.lin 已提交
187 188 189 190
                    res.emplace_back(nns[output_ids[i]]); // mapping
                }
                results.push_back(res); // append to result list
                res.clear();
X
xj.lin 已提交
191 192
                memset(output_distence, 0, k * nq * sizeof(float));
                memset(output_ids, 0, k * nq * sizeof(long));
X
xj.lin 已提交
193 194
            }
        };
X
xj.lin 已提交
195 196 197

        search_in_index(raw_files);
        search_in_index(index_files);
X
Xu Peng 已提交
198 199

        LOG(DEBUG) << "Search Overall Set Size=" << search_set_size << " M";
X
xj.lin 已提交
200
        cluster_topk();
X
xj.lin 已提交
201 202 203 204 205

        free(output_distence);
        free(output_ids);
    }

X
xj.lin 已提交
206 207 208
    if (results.empty()) {
        return Status::NotFound("Group " + group_id + ", search result not found!");
    }
X
Xu Peng 已提交
209 210 211
    return Status::OK();
}

212 213
template<typename EngineT>
void DBImpl<EngineT>::start_timer_task(int interval_) {
X
Xu Peng 已提交
214
    bg_timer_thread_ = std::thread(&DBImpl<EngineT>::background_timer_task, this, interval_);
X
Xu Peng 已提交
215 216
}

217 218
template<typename EngineT>
void DBImpl<EngineT>::background_timer_task(int interval_) {
X
Xu Peng 已提交
219 220 221 222 223 224 225 226 227
    Status status;
    while (true) {
        if (!_bg_error.ok()) break;
        if (_shutting_down.load(std::memory_order_acquire)) break;

        std::this_thread::sleep_for(std::chrono::seconds(interval_));

        try_schedule_compaction();
    }
228 229
}

230 231
template<typename EngineT>
void DBImpl<EngineT>::try_schedule_compaction() {
X
Xu Peng 已提交
232 233 234 235
    if (_bg_compaction_scheduled) return;
    if (!_bg_error.ok()) return;

    _bg_compaction_scheduled = true;
236
    _env->schedule(&DBImpl<EngineT>::BGWork, this);
X
Xu Peng 已提交
237 238
}

239 240
template<typename EngineT>
void DBImpl<EngineT>::BGWork(void* db_) {
X
Xu Peng 已提交
241 242 243
    reinterpret_cast<DBImpl*>(db_)->background_call();
}

244 245
template<typename EngineT>
void DBImpl<EngineT>::background_call() {
X
Xu Peng 已提交
246 247 248
    std::lock_guard<std::mutex> lock(_mutex);
    assert(_bg_compaction_scheduled);

249 250
    if (!_bg_error.ok() || _shutting_down.load(std::memory_order_acquire))
        return ;
X
Xu Peng 已提交
251 252

    background_compaction();
X
Xu Peng 已提交
253 254 255

    _bg_compaction_scheduled = false;
    _bg_work_finish_signal.notify_all();
X
Xu Peng 已提交
256 257
}

258

259 260
template<typename EngineT>
Status DBImpl<EngineT>::merge_files(const std::string& group_id, const meta::DateT& date,
261
        const meta::GroupFilesSchema& files) {
262
    meta::TableFileSchema group_file;
X
Xu Peng 已提交
263 264 265
    group_file.group_id = group_id;
    group_file.date = date;
    Status status = _pMeta->add_group_file(group_file);
X
Xu Peng 已提交
266

267
    if (!status.ok()) {
268
        LOG(INFO) << status.ToString() << std::endl;
269 270 271
        return status;
    }

272
    EngineT index(group_file.dimension, group_file.location);
273 274

    meta::GroupFilesSchema updated;
X
Xu Peng 已提交
275
    long  index_size = 0;
276 277

    for (auto& file : files) {
X
Xu Peng 已提交
278
        index.Merge(file.location);
279
        auto file_schema = file;
280
        file_schema.file_type = meta::TableFileSchema::TO_DELETE;
281
        updated.push_back(file_schema);
X
Xu Peng 已提交
282
        LOG(DEBUG) << "Merging file " << file_schema.file_id;
X
Xu Peng 已提交
283
        index_size = index.Size();
X
Xu Peng 已提交
284 285

        if (index_size >= _options.index_trigger_size) break;
286 287
    }

X
Xu Peng 已提交
288
    index.Serialize();
X
Xu Peng 已提交
289 290

    if (index_size >= _options.index_trigger_size) {
291
        group_file.file_type = meta::TableFileSchema::TO_INDEX;
X
Xu Peng 已提交
292
    } else {
293
        group_file.file_type = meta::TableFileSchema::RAW;
X
Xu Peng 已提交
294
    }
295
    group_file.size = index_size;
296 297
    updated.push_back(group_file);
    status = _pMeta->update_files(updated);
X
Xu Peng 已提交
298 299
    LOG(DEBUG) << "New merged file " << group_file.file_id <<
        " of size=" << index.PhysicalSize()/(1024*1024) << " M";
300

X
Xu Peng 已提交
301
    index.Cache();
X
Xu Peng 已提交
302

303 304 305
    return status;
}

306 307
template<typename EngineT>
Status DBImpl<EngineT>::background_merge_files(const std::string& group_id) {
308
    meta::DatePartionedGroupFilesSchema raw_files;
X
Xu Peng 已提交
309 310 311 312
    auto status = _pMeta->files_to_merge(group_id, raw_files);
    if (!status.ok()) {
        return status;
    }
313

314 315 316
    /* if (raw_files.size() == 0) { */
    /*     return Status::OK(); */
    /* } */
317

X
Xu Peng 已提交
318 319
    bool has_merge = false;

320
    for (auto& kv : raw_files) {
X
Xu Peng 已提交
321
        auto files = kv.second;
X
Xu Peng 已提交
322
        if (files.size() <= _options.merge_trigger_number) {
X
Xu Peng 已提交
323 324
            continue;
        }
X
Xu Peng 已提交
325
        has_merge = true;
326 327
        merge_files(group_id, kv.first, kv.second);
    }
X
Xu Peng 已提交
328

329
    _pMeta->archive_files();
330

331
    try_build_index();
X
Xu Peng 已提交
332

X
Xu Peng 已提交
333 334
    _pMeta->cleanup_ttl_files(1);

X
Xu Peng 已提交
335 336 337
    return Status::OK();
}

338
template<typename EngineT>
339 340
Status DBImpl<EngineT>::build_index(const meta::TableFileSchema& file) {
    meta::TableFileSchema group_file;
X
Xu Peng 已提交
341 342 343
    group_file.group_id = file.group_id;
    group_file.date = file.date;
    Status status = _pMeta->add_group_file(group_file);
X
Xu Peng 已提交
344 345 346 347
    if (!status.ok()) {
        return status;
    }

348
    EngineT to_index(file.dimension, file.location);
349 350 351 352

    to_index.Load();
    auto index = to_index.BuildIndex(group_file.location);

353
    group_file.file_type = meta::TableFileSchema::INDEX;
354
    group_file.size = index->Size();
X
Xu Peng 已提交
355

X
Xu Peng 已提交
356
    auto to_remove = file;
357
    to_remove.file_type = meta::TableFileSchema::TO_DELETE;
X
Xu Peng 已提交
358

X
Xu Peng 已提交
359 360
    meta::GroupFilesSchema update_files = {to_remove, group_file};
    _pMeta->update_files(update_files);
X
Xu Peng 已提交
361

X
Xu Peng 已提交
362 363 364 365
    LOG(DEBUG) << "New index file " << group_file.file_id << " of size "
        << index->PhysicalSize()/(1024*1024) << " M"
        << " from file " << to_remove.file_id;

366
    index->Cache();
367
    _pMeta->archive_files();
X
Xu Peng 已提交
368

X
Xu Peng 已提交
369 370 371
    return Status::OK();
}

372 373
template<typename EngineT>
void DBImpl<EngineT>::background_build_index() {
X
Xu Peng 已提交
374
    std::lock_guard<std::mutex> lock(build_index_mutex_);
X
Xu Peng 已提交
375 376
    assert(bg_build_index_started_);
    meta::GroupFilesSchema to_index_files;
X
Xu Peng 已提交
377
    _pMeta->files_to_index(to_index_files);
X
Xu Peng 已提交
378 379
    Status status;
    for (auto& file : to_index_files) {
X
Xu Peng 已提交
380
        /* LOG(DEBUG) << "Buiding index for " << file.location; */
X
Xu Peng 已提交
381 382 383
        status = build_index(file);
        if (!status.ok()) {
            _bg_error = status;
X
Xu Peng 已提交
384
            return;
X
Xu Peng 已提交
385 386
        }
    }
X
Xu Peng 已提交
387
    /* LOG(DEBUG) << "All Buiding index Done"; */
X
Xu Peng 已提交
388 389

    bg_build_index_started_ = false;
X
Xu Peng 已提交
390
    bg_build_index_finish_signal_.notify_all();
X
Xu Peng 已提交
391 392
}

393 394
template<typename EngineT>
Status DBImpl<EngineT>::try_build_index() {
X
Xu Peng 已提交
395
    if (bg_build_index_started_) return Status::OK();
X
Xu Peng 已提交
396
    if (_shutting_down.load(std::memory_order_acquire)) return Status::OK();
X
Xu Peng 已提交
397
    bg_build_index_started_ = true;
398
    std::thread build_index_task(&DBImpl<EngineT>::background_build_index, this);
X
Xu Peng 已提交
399
    build_index_task.detach();
X
Xu Peng 已提交
400
    return Status::OK();
401 402
}

403 404
template<typename EngineT>
void DBImpl<EngineT>::background_compaction() {
405 406
    std::vector<std::string> group_ids;
    _pMemMgr->serialize(group_ids);
407

X
Xu Peng 已提交
408 409 410 411 412 413 414
    Status status;
    for (auto group_id : group_ids) {
        status = background_merge_files(group_id);
        if (!status.ok()) {
            _bg_error = status;
            return;
        }
415
    }
X
Xu Peng 已提交
416 417
}

418 419
template<typename EngineT>
Status DBImpl<EngineT>::drop_all() {
X
Xu Peng 已提交
420 421 422
    return _pMeta->drop_all();
}

423 424
template<typename EngineT>
Status DBImpl<EngineT>::count(const std::string& group_id, long& result) {
X
Xu Peng 已提交
425 426 427
    return _pMeta->count(group_id, result);
}

X
Xu Peng 已提交
428 429 430 431 432
template<typename EngineT>
Status DBImpl<EngineT>::size(long& result) {
    return  _pMeta->size(result);
}

433 434
template<typename EngineT>
DBImpl<EngineT>::~DBImpl() {
X
Xu Peng 已提交
435 436 437 438 439 440 441 442 443 444 445 446
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _shutting_down.store(true, std::memory_order_release);
        while (_bg_compaction_scheduled) {
            _bg_work_finish_signal.wait(lock);
        }
    }
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);
        while (bg_build_index_started_) {
            bg_build_index_finish_signal_.wait(lock);
        }
X
Xu Peng 已提交
447
    }
X
Xu Peng 已提交
448
    bg_timer_thread_.join();
X
Xu Peng 已提交
449 450
    std::vector<std::string> ids;
    _pMemMgr->serialize(ids);
X
Xu Peng 已提交
451
    _env->Stop();
X
Xu Peng 已提交
452 453
}

X
Xu Peng 已提交
454 455 456
} // namespace engine
} // namespace vecwise
} // namespace zilliz
457 458

#endif