MemSegment.cpp 8.8 KB
Newer Older
G
groot 已提交
1 2 3 4 5 6 7 8 9 10 11
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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
//
// 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.

G
groot 已提交
12
#include "db/insert/MemSegment.h"
G
groot 已提交
13 14 15 16 17

#include <algorithm>
#include <cmath>
#include <iterator>
#include <string>
18
#include <utility>
G
groot 已提交
19 20
#include <vector>

W
Wang XiangYu 已提交
21
#include "config/ServerConfig.h"
G
groot 已提交
22
#include "db/Types.h"
G
groot 已提交
23 24 25
#include "db/Utils.h"
#include "db/snapshot/Operations.h"
#include "db/snapshot/Snapshots.h"
26
#include "db/wal/WalManager.h"
C
Cai Yudong 已提交
27
#include "knowhere/index/vector_index/helpers/IndexParameter.h"
G
groot 已提交
28
#include "metrics/Metrics.h"
29
#include "utils/CommonUtil.h"
G
groot 已提交
30 31 32 33 34
#include "utils/Log.h"

namespace milvus {
namespace engine {

G
groot 已提交
35
MemSegment::MemSegment(int64_t collection_id, int64_t partition_id, const DBOptions& options)
G
groot 已提交
36 37 38 39
    : collection_id_(collection_id), partition_id_(partition_id), options_(options) {
}

Status
40 41 42 43 44 45 46 47 48 49 50
MemSegment::Add(const DataChunkPtr& chunk, idx_t op_id) {
    if (chunk == nullptr) {
        return Status::OK();
    }

    MemAction action;
    action.op_id_ = op_id;
    action.insert_data_ = chunk;
    actions_.emplace_back(action);

    current_mem_ += utils::GetSizeOfChunk(chunk);
51
    total_row_count_ += chunk->count_;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

    return Status::OK();
}

Status
MemSegment::Delete(const std::vector<idx_t>& ids, idx_t op_id) {
    if (ids.empty()) {
        return Status::OK();
    }

    MemAction action;
    action.op_id_ = op_id;
    for (auto& id : ids) {
        action.delete_ids_.insert(id);
    }
    actions_.emplace_back(action);

    return Status::OK();
}

Status
MemSegment::Serialize() {
    int64_t size = GetCurrentMem();
    server::CollectSerializeMetrics metrics(size);

    // delete in mem
    STATUS_CHECK(ApplyDeleteToMem());

    // create new segment and serialize
G
groot 已提交
81 82 83
    snapshot::ScopedSnapshotT ss;
    auto status = snapshot::Snapshots::GetInstance().GetSnapshot(ss, collection_id_);
    if (!status.ok()) {
84
        std::string err_msg = "Failed to get latest snapshot: " + status.ToString();
G
groot 已提交
85 86 87 88
        LOG_ENGINE_ERROR_ << err_msg;
        return status;
    }

89 90 91 92 93 94 95 96 97 98 99 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
    std::shared_ptr<snapshot::NewSegmentOperation> new_seg_operation;
    segment::SegmentWriterPtr segment_writer;
    status = CreateNewSegment(ss, new_seg_operation, segment_writer);
    if (!status.ok()) {
        LOG_ENGINE_ERROR_ << "Failed to create new segment";
        return status;
    }

    status = PutChunksToWriter(segment_writer);
    if (!status.ok()) {
        LOG_ENGINE_ERROR_ << "Failed to copy data to segment writer";
        return status;
    }

    // delete action could delete all entities of the segment
    // no need to serialize empty segment
    if (segment_writer->RowCount() == 0) {
        return Status::OK();
    }

    int64_t seg_id = 0;
    segment_writer->GetSegmentID(seg_id);
    status = segment_writer->Serialize();
    if (!status.ok()) {
        LOG_ENGINE_ERROR_ << "Failed to serialize segment: " << seg_id;
        return status;
    }

    STATUS_CHECK(new_seg_operation->CommitRowCount(segment_writer->RowCount()));
    STATUS_CHECK(new_seg_operation->Push());
    LOG_ENGINE_DEBUG_ << "New segment " << seg_id << " of collection " << collection_id_ << " serialized";

    // notify wal the max operation id is done
    idx_t max_op_id = 0;
    for (auto& action : actions_) {
        if (action.op_id_ > max_op_id) {
            max_op_id = action.op_id_;
        }
    }
    WalManager::GetInstance().OperationDone(ss->GetName(), max_op_id);

    return Status::OK();
}

Status
MemSegment::CreateNewSegment(snapshot::ScopedSnapshotT& ss, std::shared_ptr<snapshot::NewSegmentOperation>& operation,
                             segment::SegmentWriterPtr& writer) {
G
groot 已提交
136
    // create segment
137
    snapshot::SegmentPtr segment;
G
groot 已提交
138 139
    snapshot::OperationContext context;
    context.prev_partition = ss->GetResource<snapshot::Partition>(partition_id_);
140 141
    operation = std::make_shared<snapshot::NewSegmentOperation>(context, ss);
    auto status = operation->CommitNewSegment(segment);
G
groot 已提交
142
    if (!status.ok()) {
G
groot 已提交
143
        std::string err_msg = "MemSegment::CreateSegment failed: " + status.ToString();
G
groot 已提交
144 145 146 147
        LOG_ENGINE_ERROR_ << err_msg;
        return status;
    }

G
groot 已提交
148 149 150 151 152 153
    // create segment raw files (placeholder)
    auto names = ss->GetFieldNames();
    for (auto& name : names) {
        snapshot::SegmentFileContext sf_context;
        sf_context.collection_id = collection_id_;
        sf_context.partition_id = partition_id_;
154
        sf_context.segment_id = segment->GetID();
G
groot 已提交
155
        sf_context.field_name = name;
G
groot 已提交
156
        sf_context.field_element_name = engine::ELEMENT_RAW_DATA;
G
groot 已提交
157 158

        snapshot::SegmentFilePtr seg_file;
159
        status = operation->CommitNewSegmentFile(sf_context, seg_file);
G
groot 已提交
160
        if (!status.ok()) {
G
groot 已提交
161
            std::string err_msg = "MemSegment::CreateSegment failed: " + status.ToString();
G
groot 已提交
162 163 164 165 166 167 168 169 170 171
            LOG_ENGINE_ERROR_ << err_msg;
            return status;
        }
    }

    // create deleted_doc and bloom_filter files (placeholder)
    {
        snapshot::SegmentFileContext sf_context;
        sf_context.collection_id = collection_id_;
        sf_context.partition_id = partition_id_;
172
        sf_context.segment_id = segment->GetID();
G
groot 已提交
173 174
        sf_context.field_name = engine::FIELD_UID;
        sf_context.field_element_name = engine::ELEMENT_DELETED_DOCS;
G
groot 已提交
175 176

        snapshot::SegmentFilePtr delete_doc_file, bloom_filter_file;
177
        status = operation->CommitNewSegmentFile(sf_context, delete_doc_file);
G
groot 已提交
178
        if (!status.ok()) {
G
groot 已提交
179
            std::string err_msg = "MemSegment::CreateSegment failed: " + status.ToString();
G
groot 已提交
180 181 182 183
            LOG_ENGINE_ERROR_ << err_msg;
            return status;
        }

G
groot 已提交
184
        sf_context.field_element_name = engine::ELEMENT_BLOOM_FILTER;
185
        status = operation->CommitNewSegmentFile(sf_context, bloom_filter_file);
G
groot 已提交
186
        if (!status.ok()) {
G
groot 已提交
187
            std::string err_msg = "MemSegment::CreateSegment failed: " + status.ToString();
G
groot 已提交
188 189 190 191 192
            LOG_ENGINE_ERROR_ << err_msg;
            return status;
        }
    }

193
    auto ctx = operation->GetContext();
G
groot 已提交
194 195 196
    auto visitor = SegmentVisitor::Build(ss, ctx.new_segment, ctx.new_segment_files);

    // create segment writer
197
    writer = std::make_shared<segment::SegmentWriter>(options_.meta_.path_, visitor);
G
groot 已提交
198 199

    return Status::OK();
G
groot 已提交
200 201
}

G
groot 已提交
202
Status
203 204 205 206 207 208 209
MemSegment::ApplyDeleteToMem() {
    auto outer_iter = actions_.begin();
    for (; outer_iter != actions_.end(); ++outer_iter) {
        MemAction& action = (*outer_iter);
        if (action.delete_ids_.empty()) {
            continue;
        }
G
groot 已提交
210

211 212 213 214 215 216
        auto inner_iter = actions_.begin();
        for (; inner_iter != outer_iter; ++inner_iter) {
            MemAction& insert_action = (*inner_iter);
            if (insert_action.insert_data_ == nullptr) {
                continue;
            }
G
groot 已提交
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231
            DataChunkPtr& chunk = insert_action.insert_data_;
            // load chunk uids
            auto iter = chunk->fixed_fields_.find(FIELD_UID);
            if (iter == chunk->fixed_fields_.end()) {
                continue;  // no uid field?
            }

            BinaryDataPtr& uid_data = iter->second;
            if (uid_data == nullptr) {
                continue;  // no uid data?
            }
            if (uid_data->data_.size() / sizeof(idx_t) != chunk->count_) {
                continue;  // invalid uid data?
            }
C
chen qingxiang 已提交
232
            auto uid = reinterpret_cast<idx_t*>(uid_data->data_.data());
G
groot 已提交
233

234 235 236 237 238 239
            // calculte delete offsets
            std::vector<offset_t> offsets;
            for (int64_t i = 0; i < chunk->count_; ++i) {
                if (action.delete_ids_.find(uid[i]) != action.delete_ids_.end()) {
                    offsets.push_back(i);
                }
G
groot 已提交
240
            }
241 242 243 244 245 246 247

            // delete entities from chunks
            Segment temp_set;
            STATUS_CHECK(temp_set.SetFields(collection_id_));
            STATUS_CHECK(temp_set.AddChunk(chunk));
            temp_set.DeleteEntity(offsets);
            chunk->count_ = temp_set.GetRowCount();
G
groot 已提交
248
        }
G
groot 已提交
249 250
    }

G
groot 已提交
251
    return Status::OK();
G
groot 已提交
252 253 254
}

Status
255 256 257
MemSegment::PutChunksToWriter(const segment::SegmentWriterPtr& writer) {
    if (writer == nullptr) {
        return Status(DB_ERROR, "Segment writer is null pointer");
G
groot 已提交
258 259
    }

260 261 262
    for (auto& action : actions_) {
        DataChunkPtr chunk = action.insert_data_;
        if (chunk == nullptr || chunk->count_ == 0) {
G
groot 已提交
263
            continue;
G
groot 已提交
264
        }
G
groot 已提交
265

266 267
        // copy data to writer
        writer->AddChunk(chunk);
G
groot 已提交
268 269
    }

C
Cai Yudong 已提交
270
    return Status::OK();
G
groot 已提交
271 272 273 274
}

}  // namespace engine
}  // namespace milvus