MemTable.cpp 14.2 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/insert/MemTable.h"
Z
zhiru 已提交
13

14 15
#include <algorithm>
#include <chrono>
S
starlord 已提交
16 17
#include <memory>
#include <string>
18 19
#include <unordered_map>

20
#include "cache/CpuCacheMgr.h"
21 22
#include "db/OngoingFileChecker.h"
#include "db/Utils.h"
23
#include "segment/SegmentReader.h"
24
#include "utils/Log.h"
25
#include "wrapper/VecIndex.h"
Z
update  
zhiru 已提交
26

Z
zhiru 已提交
27 28 29
namespace milvus {
namespace engine {

S
starlord 已提交
30 31
MemTable::MemTable(const std::string& table_id, const meta::MetaPtr& meta, const DBOptions& options)
    : table_id_(table_id), meta_(meta), options_(options) {
32 33
    SetIdentity("MemTable");
    AddCacheInsertDataListener();
Z
zhiru 已提交
34 35
}

S
starlord 已提交
36
Status
37
MemTable::Add(const VectorSourcePtr& source) {
Z
zhiru 已提交
38
    while (!source->AllAdded()) {
S
starlord 已提交
39
        MemTableFilePtr current_mem_table_file;
Z
zhiru 已提交
40
        if (!mem_table_file_list_.empty()) {
Z
update  
zhiru 已提交
41
            current_mem_table_file = mem_table_file_list_.back();
Z
zhiru 已提交
42
        }
Z
update  
zhiru 已提交
43

Z
zhiru 已提交
44
        Status status;
Z
update  
zhiru 已提交
45
        if (mem_table_file_list_.empty() || current_mem_table_file->IsFull()) {
S
starlord 已提交
46
            MemTableFilePtr new_mem_table_file = std::make_shared<MemTableFile>(table_id_, meta_, options_);
G
groot 已提交
47
            status = new_mem_table_file->Add(source);
Z
zhiru 已提交
48
            if (status.ok()) {
Z
update  
zhiru 已提交
49
                mem_table_file_list_.emplace_back(new_mem_table_file);
Z
zhiru 已提交
50
            }
Z
update  
zhiru 已提交
51
        } else {
G
groot 已提交
52
            status = current_mem_table_file->Add(source);
Z
zhiru 已提交
53
        }
Z
update  
zhiru 已提交
54

Z
zhiru 已提交
55
        if (!status.ok()) {
S
starlord 已提交
56
            std::string err_msg = "Insert failed: " + status.ToString();
Z
update  
zhiru 已提交
57
            ENGINE_LOG_ERROR << err_msg;
S
starlord 已提交
58
            return Status(DB_ERROR, err_msg);
Z
zhiru 已提交
59 60 61 62 63
        }
    }
    return Status::OK();
}

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
Status
MemTable::Delete(segment::doc_id_t doc_id) {
    // Locate which table file the doc id lands in
    for (auto& table_file : mem_table_file_list_) {
        table_file->Delete(doc_id);
    }
    // Add the id to delete list so it can be applied to other segments on disk during the next flush
    doc_ids_to_delete_.insert(doc_id);

    return Status::OK();
}

Status
MemTable::Delete(const std::vector<segment::doc_id_t>& doc_ids) {
    // Locate which table file the doc id lands in
    for (auto& table_file : mem_table_file_list_) {
        table_file->Delete(doc_ids);
    }
    // Add the id to delete list so it can be applied to other segments on disk during the next flush
    for (auto& id : doc_ids) {
        doc_ids_to_delete_.insert(id);
    }

    return Status::OK();
}

S
starlord 已提交
90
void
S
starlord 已提交
91
MemTable::GetCurrentMemTableFile(MemTableFilePtr& mem_table_file) {
Z
zhiru 已提交
92
    mem_table_file = mem_table_file_list_.back();
Z
zhiru 已提交
93 94
}

S
starlord 已提交
95 96
size_t
MemTable::GetTableFileCount() {
Z
zhiru 已提交
97 98 99
    return mem_table_file_list_.size();
}

S
starlord 已提交
100
Status
Z
Zhiru Zhu 已提交
101
MemTable::Serialize(uint64_t wal_lsn, bool apply_delete) {
102 103
    auto start = std::chrono::high_resolution_clock::now();

Z
Zhiru Zhu 已提交
104
    if (!doc_ids_to_delete_.empty() && apply_delete) {
105 106 107 108 109 110
        auto status = ApplyDeletes();
        if (!status.ok()) {
            return Status(DB_ERROR, status.message());
        }
    }

Z
update  
zhiru 已提交
111
    for (auto mem_table_file = mem_table_file_list_.begin(); mem_table_file != mem_table_file_list_.end();) {
112
        auto status = (*mem_table_file)->Serialize(wal_lsn);
Z
zhiru 已提交
113
        if (!status.ok()) {
114
            return status;
Z
zhiru 已提交
115
        }
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

        ENGINE_LOG_DEBUG << "Flushed segment " << (*mem_table_file)->GetSegmentId();

        {
            std::lock_guard<std::mutex> lock(mutex_);
            mem_table_file = mem_table_file_list_.erase(mem_table_file);
        }
    }

    // Update flush lsn
    auto status = meta_->UpdateTableFlushLSN(table_id_, wal_lsn);
    if (!status.ok()) {
        std::string err_msg = "Failed to write flush lsn to meta: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
Z
zhiru 已提交
131
    }
132 133 134 135 136

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    ENGINE_LOG_DEBUG << "Finished flushing for table " << table_id_ << " in " << diff.count() << " s";

Z
zhiru 已提交
137
    return Status::OK();
Z
zhiru 已提交
138 139
}

S
starlord 已提交
140 141
bool
MemTable::Empty() {
142
    return mem_table_file_list_.empty() && doc_ids_to_delete_.empty();
Z
zhiru 已提交
143 144
}

S
starlord 已提交
145
const std::string&
S
starlord 已提交
146
MemTable::GetTableId() const {
Z
zhiru 已提交
147 148 149
    return table_id_;
}

S
starlord 已提交
150 151
size_t
MemTable::GetCurrentMem() {
Z
zhiru 已提交
152
    std::lock_guard<std::mutex> lock(mutex_);
Z
update  
zhiru 已提交
153
    size_t total_mem = 0;
S
starlord 已提交
154
    for (auto& mem_table_file : mem_table_file_list_) {
Z
update  
zhiru 已提交
155
        total_mem += mem_table_file->GetCurrentMem();
Z
zhiru 已提交
156
    }
Z
update  
zhiru 已提交
157
    return total_mem;
Z
zhiru 已提交
158 159
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
Status
MemTable::ApplyDeletes() {
    // Applying deletes to other segments on disk and their corresponding cache:
    // For each segment in table:
    //     Load its bloom filter
    //     For each id in delete list:
    //         If present, add the uid to segment's uid list
    // For each segment
    //     Get its cache if exists
    //     Load its uids file.
    //     Scan the uids, if any uid in segment's uid list exists:
    //         add its offset to deletedDoc
    //         remove the id from bloom filter
    //         set black list in cache
    //     Serialize segment's deletedDoc TODO(zhiru): append directly to previous file for now, may have duplicates
    //     Serialize bloom filter

    ENGINE_LOG_DEBUG << "Applying " << doc_ids_to_delete_.size() << " deletes in table: " << table_id_;

    auto start_total = std::chrono::high_resolution_clock::now();

J
JinHai-CN 已提交
181
    //    auto start = std::chrono::high_resolution_clock::now();
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221

    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;
    auto status = meta_->FilesByType(table_id_, file_types, table_files);
    if (!status.ok()) {
        std::string err_msg = "Failed to apply deletes: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    OngoingFileChecker::GetInstance().MarkOngoingFiles(table_files);

    std::unordered_map<size_t, std::vector<segment::doc_id_t>> ids_to_check_map;

    for (size_t i = 0; i < table_files.size(); ++i) {
        auto& table_file = table_files[i];
        std::string segment_dir;
        utils::GetParentPath(table_file.location_, segment_dir);

        segment::SegmentReader segment_reader(segment_dir);
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        segment_reader.LoadBloomFilter(id_bloom_filter_ptr);

        for (auto& id : doc_ids_to_delete_) {
            if (id_bloom_filter_ptr->Check(id)) {
                ids_to_check_map[i].emplace_back(id);
            }
        }
    }

    meta::TableFilesSchema files_to_check;
    for (auto& kv : ids_to_check_map) {
        files_to_check.emplace_back(table_files[kv.first]);
    }

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(table_files);

    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_check);

J
JinHai-CN 已提交
222 223 224
    auto time0 = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff0 = time0 - start_total;
    ENGINE_LOG_DEBUG << "Found " << ids_to_check_map.size() << " segment to apply deletes in " << diff0.count() << " s";
225 226 227 228 229 230 231

    meta::TableFilesSchema table_files_to_update;

    for (auto& kv : ids_to_check_map) {
        auto& table_file = table_files[kv.first];
        ENGINE_LOG_DEBUG << "Applying deletes in segment: " << table_file.segment_id_;

J
JinHai-CN 已提交
232
        auto time1 = std::chrono::high_resolution_clock::now();
233 234 235 236 237

        std::string segment_dir;
        utils::GetParentPath(table_file.location_, segment_dir);
        segment::SegmentReader segment_reader(segment_dir);

Z
update  
Zhiru Zhu 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
        auto& segment_id = table_file.segment_id_;
        meta::TableFilesSchema segment_files;
        status = meta_->GetTableFilesBySegmentId(segment_id, segment_files);
        if (!status.ok()) {
            break;
        }

        // Get all index that contains blacklist in cache
        std::vector<VecIndexPtr> indexes;
        std::vector<faiss::ConcurrentBitsetPtr> blacklists;
        for (auto& file : segment_files) {
            auto index =
                std::static_pointer_cast<VecIndex>(cache::CpuCacheMgr::GetInstance()->GetIndex(file.location_));
            faiss::ConcurrentBitsetPtr blacklist = nullptr;
            if (index != nullptr) {
                index->GetBlacklist(blacklist);
                if (blacklist != nullptr) {
                    indexes.emplace_back(index);
                    blacklists.emplace_back(blacklist);
                }
            }
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        }

        std::vector<segment::doc_id_t> uids;
        status = segment_reader.LoadUids(uids);
        if (!status.ok()) {
            break;
        }
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        status = segment_reader.LoadBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            break;
        }

        auto& ids_to_check = kv.second;

        segment::DeletedDocsPtr deleted_docs = std::make_shared<segment::DeletedDocs>();

J
JinHai-CN 已提交
276 277 278
        auto time2 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff1 = time2 - time1;
        ENGINE_LOG_DEBUG << "Loading uids and deleted docs took " << diff1.count() << " s";
279 280 281

        std::sort(ids_to_check.begin(), ids_to_check.end());

J
JinHai-CN 已提交
282 283 284
        auto time3 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff2 = time3 - time2;
        ENGINE_LOG_DEBUG << "Sorting " << ids_to_check.size() << " ids took " << diff2.count() << " s";
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

        size_t delete_count = 0;
        auto find_diff = std::chrono::duration<double>::zero();
        auto set_diff = std::chrono::duration<double>::zero();

        for (size_t i = 0; i < uids.size(); ++i) {
            auto find_start = std::chrono::high_resolution_clock::now();

            auto found = std::binary_search(ids_to_check.begin(), ids_to_check.end(), uids[i]);

            auto find_end = std::chrono::high_resolution_clock::now();
            find_diff += (find_end - find_start);

            if (found) {
                auto set_start = std::chrono::high_resolution_clock::now();

                delete_count++;

                deleted_docs->AddDeletedDoc(i);

                if (id_bloom_filter_ptr->Check(uids[i])) {
                    id_bloom_filter_ptr->Remove(uids[i]);
                }

Z
update  
Zhiru Zhu 已提交
309
                for (auto& blacklist : blacklists) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323
                    if (!blacklist->test(i)) {
                        blacklist->set(i);
                    }
                }

                auto set_end = std::chrono::high_resolution_clock::now();
                set_diff += (set_end - set_start);
            }
        }

        ENGINE_LOG_DEBUG << "Finding " << ids_to_check.size() << " uids in " << uids.size() << " uids took "
                         << find_diff.count() << " s in total";
        ENGINE_LOG_DEBUG << "Setting deleted docs and bloom filter took " << set_diff.count() << " s in total";

J
JinHai-CN 已提交
324
        auto time4 = std::chrono::high_resolution_clock::now();
J
Test  
JinHai-CN 已提交
325

Z
update  
Zhiru Zhu 已提交
326 327
        for (auto i = 0; i < indexes.size(); ++i) {
            indexes[i]->SetBlacklist(blacklists[i]);
328 329
        }

J
JinHai-CN 已提交
330
        //        start = std::chrono::high_resolution_clock::now();
331 332 333 334 335 336 337 338

        segment::Segment tmp_segment;
        segment::SegmentWriter segment_writer(segment_dir);
        status = segment_writer.WriteDeletedDocs(deleted_docs);
        if (!status.ok()) {
            break;
        }

J
JinHai-CN 已提交
339 340
        auto time5 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff4 = time5 - time4;
341
        ENGINE_LOG_DEBUG << "Appended " << deleted_docs->GetSize()
J
JinHai-CN 已提交
342
                         << " offsets to deleted docs in segment: " << table_file.segment_id_ << " in " << diff4.count()
343 344
                         << " s";

J
JinHai-CN 已提交
345
        //        start = std::chrono::high_resolution_clock::now();
346 347 348 349 350

        status = segment_writer.WriteBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            break;
        }
J
JinHai-CN 已提交
351 352 353
        auto time6 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff5 = time6 - time5;
        ENGINE_LOG_DEBUG << "Updated bloom filter in segment: " << table_file.segment_id_ << " in " << diff5.count()
354 355 356 357 358 359 360 361 362 363
                         << " s";

        // Update table file row count
        for (auto& file : segment_files) {
            if (file.file_type_ == meta::TableFileSchema::RAW || file.file_type_ == meta::TableFileSchema::TO_INDEX ||
                file.file_type_ == meta::TableFileSchema::INDEX || file.file_type_ == meta::TableFileSchema::BACKUP) {
                file.row_count_ -= delete_count;
                table_files_to_update.emplace_back(file);
            }
        }
J
JinHai-CN 已提交
364 365 366
        auto time7 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff6 = time7 - time6;
        diff6 = time6 - time5;
J
JinHai-CN 已提交
367 368
        ENGINE_LOG_DEBUG << "Update table file row count in vector of segment: " << table_file.segment_id_ << " in "
                         << diff6.count() << " s";
369 370
    }

J
Test  
JinHai-CN 已提交
371 372
    auto time7 = std::chrono::high_resolution_clock::now();

373
    status = meta_->UpdateTableFilesRowCount(table_files_to_update);
374 375 376 377 378 379 380 381 382 383

    if (!status.ok()) {
        std::string err_msg = "Failed to apply deletes: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    doc_ids_to_delete_.clear();

    auto end_total = std::chrono::high_resolution_clock::now();
J
JinHai-CN 已提交
384 385
    std::chrono::duration<double> diff7 = end_total - time7;
    ENGINE_LOG_DEBUG << "Update deletes to meta in table " << table_id_ << " in " << diff7.count() << " s";
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    std::chrono::duration<double> diff_total = end_total - start_total;
    ENGINE_LOG_DEBUG << "Finished applying deletes in table " << table_id_ << " in " << diff_total.count() << " s";

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_check);

    return Status::OK();
}

uint64_t
MemTable::GetLSN() {
    return lsn_;
}

void
MemTable::SetLSN(uint64_t lsn) {
    lsn_ = lsn;
}

404 405 406 407 408
void
MemTable::OnCacheInsertDataChanged(bool value) {
    options_.insert_cache_immediately_ = value;
}

S
starlord 已提交
409 410
}  // namespace engine
}  // namespace milvus