MemTable.cpp 12.9 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 16 17 18 19
#include <cache/CpuCacheMgr.h>
#include <segment/SegmentReader.h>
#include <wrapper/VecIndex.h>

#include <algorithm>
#include <chrono>
S
starlord 已提交
20 21
#include <memory>
#include <string>
22 23 24 25 26
#include <unordered_map>

#include "db/OngoingFileChecker.h"
#include "db/Utils.h"
#include "utils/Log.h"
Z
update  
zhiru 已提交
27

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

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

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

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

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

63 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
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 已提交
89
void
S
starlord 已提交
90
MemTable::GetCurrentMemTableFile(MemTableFilePtr& mem_table_file) {
Z
zhiru 已提交
91
    mem_table_file = mem_table_file_list_.back();
Z
zhiru 已提交
92 93
}

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

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

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

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

        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 已提交
130
    }
131 132 133 134 135

    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 已提交
136
    return Status::OK();
Z
zhiru 已提交
137 138
}

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

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

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

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 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 222 223 224 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 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 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
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();

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

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

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    ENGINE_LOG_DEBUG << "Found " << ids_to_check_map.size() << " segment to apply deletes in " << diff.count() << " s";

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

        start = std::chrono::high_resolution_clock::now();

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

        auto index =
            std::static_pointer_cast<VecIndex>(cache::CpuCacheMgr::GetInstance()->GetIndex(table_file.location_));
        faiss::ConcurrentBitsetPtr blacklist = nullptr;
        if (index != nullptr) {
            status = index->GetBlacklist(blacklist);
        }

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

        end = std::chrono::high_resolution_clock::now();
        diff = end - start;
        ENGINE_LOG_DEBUG << "Loading uids and deleted docs took " << diff.count() << " s";

        start = std::chrono::high_resolution_clock::now();

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

        end = std::chrono::high_resolution_clock::now();
        diff = end - start;
        ENGINE_LOG_DEBUG << "Sorting " << ids_to_check.size() << " ids took " << diff.count() << " s";

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

                if (blacklist != nullptr) {
                    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";

        if (index != nullptr) {
            index->SetBlacklist(blacklist);
        }

        start = std::chrono::high_resolution_clock::now();

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

        end = std::chrono::high_resolution_clock::now();
        diff = end - start;
        ENGINE_LOG_DEBUG << "Appended " << deleted_docs->GetSize()
                         << " offsets to deleted docs in segment: " << table_file.segment_id_ << " in " << diff.count()
                         << " s";

        start = std::chrono::high_resolution_clock::now();

        status = segment_writer.WriteBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            break;
        }
        end = std::chrono::high_resolution_clock::now();
        diff = end - start;
        ENGINE_LOG_DEBUG << "Updated bloom filter in segment: " << table_file.segment_id_ << " in " << diff.count()
                         << " s";

        // Update table file row count
        auto& segment_id = table_file.segment_id_;
        meta::TableFilesSchema segment_files;
        status = meta_->GetTableFilesBySegmentId(segment_id, segment_files);
        if (!status.ok()) {
            break;
        }
        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);
            }
        }
    }

    status = meta_->UpdateTableFiles(table_files_to_update);

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

S
starlord 已提交
384 385
}  // namespace engine
}  // namespace milvus