Coverage Report

Created: 2025-04-15 14:42

/root/doris/be/src/olap/delta_writer.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "olap/delta_writer.h"
19
20
#include <brpc/controller.h>
21
#include <butil/errno.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/internal_service.pb.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <filesystem>
27
#include <ostream>
28
#include <string>
29
#include <utility>
30
31
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
32
#include "common/compiler_util.h" // IWYU pragma: keep
33
#include "common/config.h"
34
#include "common/logging.h"
35
#include "common/status.h"
36
#include "exec/tablet_info.h"
37
#include "gutil/strings/numbers.h"
38
#include "io/fs/file_writer.h" // IWYU pragma: keep
39
#include "olap/memtable_flush_executor.h"
40
#include "olap/olap_define.h"
41
#include "olap/rowset/beta_rowset.h"
42
#include "olap/rowset/beta_rowset_writer.h"
43
#include "olap/rowset/rowset_meta.h"
44
#include "olap/rowset/segment_v2/inverted_index_desc.h"
45
#include "olap/rowset_builder.h"
46
#include "olap/schema_change.h"
47
#include "olap/storage_engine.h"
48
#include "olap/tablet_manager.h"
49
#include "olap/txn_manager.h"
50
#include "runtime/exec_env.h"
51
#include "service/backend_options.h"
52
#include "util/brpc_client_cache.h"
53
#include "util/mem_info.h"
54
#include "util/ref_count_closure.h"
55
#include "util/stopwatch.hpp"
56
#include "util/time.h"
57
#include "vec/core/block.h"
58
59
namespace doris {
60
using namespace ErrorCode;
61
62
BaseDeltaWriter::BaseDeltaWriter(const WriteRequest& req, RuntimeProfile* profile,
63
                                 const UniqueId& load_id)
64
15
        : _req(req), _memtable_writer(new MemTableWriter(req)) {
65
15
    _init_profile(profile);
66
15
}
67
68
DeltaWriter::DeltaWriter(StorageEngine& engine, const WriteRequest& req, RuntimeProfile* profile,
69
                         const UniqueId& load_id)
70
15
        : BaseDeltaWriter(req, profile, load_id), _engine(engine) {
71
15
    _rowset_builder = std::make_unique<RowsetBuilder>(_engine, req, profile);
72
15
}
73
74
15
void BaseDeltaWriter::_init_profile(RuntimeProfile* profile) {
75
15
    _profile = profile->create_child(fmt::format("DeltaWriter {}", _req.tablet_id), true, true);
76
15
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
77
15
    _wait_flush_limit_timer = ADD_TIMER(_profile, "WaitFlushLimitTime");
78
15
}
79
80
0
void DeltaWriter::_init_profile(RuntimeProfile* profile) {
81
0
    BaseDeltaWriter::_init_profile(profile);
82
0
    _commit_txn_timer = ADD_TIMER(_profile, "CommitTxnTime");
83
0
}
84
85
15
BaseDeltaWriter::~BaseDeltaWriter() {
86
15
    if (!_is_init) {
87
0
        return;
88
0
    }
89
90
    // cancel and wait all memtables in flush queue to be finished
91
15
    static_cast<void>(_memtable_writer->cancel());
92
93
15
    if (_rowset_builder->tablet() != nullptr) {
94
15
        const FlushStatistic& stat = _memtable_writer->get_flush_token_stats();
95
15
        _rowset_builder->tablet()->flush_bytes->increment(stat.flush_size_bytes);
96
15
        _rowset_builder->tablet()->flush_finish_count->increment(stat.flush_finish_count);
97
15
    }
98
15
}
99
100
15
DeltaWriter::~DeltaWriter() = default;
101
102
15
Status BaseDeltaWriter::init() {
103
15
    if (_is_init) {
104
0
        return Status::OK();
105
0
    }
106
15
    RETURN_IF_ERROR(_rowset_builder->init());
107
15
    RETURN_IF_ERROR(_memtable_writer->init(
108
15
            _rowset_builder->rowset_writer(), _rowset_builder->tablet_schema(),
109
15
            _rowset_builder->get_partial_update_info(), nullptr,
110
15
            _rowset_builder->tablet()->enable_unique_key_merge_on_write()));
111
15
    ExecEnv::GetInstance()->memtable_memory_limiter()->register_writer(_memtable_writer);
112
15
    _is_init = true;
113
15
    return Status::OK();
114
15
}
115
116
20
Status DeltaWriter::write(const vectorized::Block* block, const std::vector<uint32_t>& row_idxs) {
117
20
    if (UNLIKELY(row_idxs.empty())) {
118
0
        return Status::OK();
119
0
    }
120
20
    _lock_watch.start();
121
20
    std::lock_guard<std::mutex> l(_lock);
122
20
    _lock_watch.stop();
123
20
    if (!_is_init && !_is_cancelled) {
124
12
        RETURN_IF_ERROR(init());
125
12
    }
126
20
    {
127
20
        SCOPED_TIMER(_wait_flush_limit_timer);
128
20
        while (_memtable_writer->flush_running_count() >=
129
20
               config::memtable_flush_running_count_limit) {
130
0
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
131
0
        }
132
20
    }
133
20
    return _memtable_writer->write(block, row_idxs);
134
20
}
135
136
9
Status BaseDeltaWriter::wait_flush() {
137
9
    return _memtable_writer->wait_flush();
138
9
}
139
140
15
Status DeltaWriter::close() {
141
15
    _lock_watch.start();
142
15
    std::lock_guard<std::mutex> l(_lock);
143
15
    _lock_watch.stop();
144
15
    if (!_is_init && !_is_cancelled) {
145
        // if this delta writer is not initialized, but close() is called.
146
        // which means this tablet has no data loaded, but at least one tablet
147
        // in same partition has data loaded.
148
        // so we have to also init this DeltaWriter, so that it can create an empty rowset
149
        // for this tablet when being closed.
150
3
        RETURN_IF_ERROR(init());
151
3
    }
152
15
    return _memtable_writer->close();
153
15
}
154
155
15
Status BaseDeltaWriter::build_rowset() {
156
15
    SCOPED_TIMER(_close_wait_timer);
157
15
    RETURN_IF_ERROR(_memtable_writer->close_wait(_profile));
158
15
    return _rowset_builder->build_rowset();
159
15
}
160
161
15
Status DeltaWriter::build_rowset() {
162
15
    std::lock_guard<std::mutex> l(_lock);
163
15
    DCHECK(_is_init)
164
0
            << "delta writer is supposed be to initialized before build_rowset() being called";
165
15
    return BaseDeltaWriter::build_rowset();
166
15
}
167
168
9
Status BaseDeltaWriter::submit_calc_delete_bitmap_task() {
169
9
    return _rowset_builder->submit_calc_delete_bitmap_task();
170
9
}
171
172
9
Status BaseDeltaWriter::wait_calc_delete_bitmap() {
173
9
    return _rowset_builder->wait_calc_delete_bitmap();
174
9
}
175
176
15
RowsetBuilder* DeltaWriter::rowset_builder() {
177
15
    return static_cast<RowsetBuilder*>(_rowset_builder.get());
178
15
}
179
180
15
Status DeltaWriter::commit_txn(const PSlaveTabletNodes& slave_tablet_nodes) {
181
15
    std::lock_guard<std::mutex> l(_lock);
182
15
    SCOPED_TIMER(_commit_txn_timer);
183
15
    RETURN_IF_ERROR(rowset_builder()->commit_txn());
184
185
15
    for (auto&& node_info : slave_tablet_nodes.slave_nodes()) {
186
0
        _request_slave_tablet_pull_rowset(node_info);
187
0
    }
188
15
    return Status::OK();
189
15
}
190
191
bool DeltaWriter::check_slave_replicas_done(
192
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
193
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
194
0
    if (_unfinished_slave_node.empty()) {
195
0
        success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
196
0
        return true;
197
0
    }
198
0
    return false;
199
0
}
200
201
void DeltaWriter::add_finished_slave_replicas(
202
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
203
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
204
0
    success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
205
0
}
206
207
0
Status BaseDeltaWriter::cancel() {
208
0
    return cancel_with_status(Status::Cancelled("already cancelled"));
209
0
}
210
211
0
Status BaseDeltaWriter::cancel_with_status(const Status& st) {
212
0
    if (_is_cancelled) {
213
0
        return Status::OK();
214
0
    }
215
0
    RETURN_IF_ERROR(_memtable_writer->cancel_with_status(st));
216
0
    _is_cancelled = true;
217
0
    return Status::OK();
218
0
}
219
220
0
Status DeltaWriter::cancel_with_status(const Status& st) {
221
0
    std::lock_guard<std::mutex> l(_lock);
222
0
    return BaseDeltaWriter::cancel_with_status(st);
223
0
}
224
225
0
int64_t BaseDeltaWriter::mem_consumption(MemType mem) {
226
0
    return _memtable_writer->mem_consumption(mem);
227
0
}
228
229
0
void DeltaWriter::_request_slave_tablet_pull_rowset(const PNodeInfo& node_info) {
230
0
    std::shared_ptr<PBackendService_Stub> stub =
231
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
232
0
                    node_info.host(), node_info.async_internal_port());
233
0
    if (stub == nullptr) {
234
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica. get rpc stub failed, "
235
0
                        "slave host="
236
0
                     << node_info.host() << ", port=" << node_info.async_internal_port()
237
0
                     << ", tablet_id=" << _req.tablet_id << ", txn_id=" << _req.txn_id;
238
0
        return;
239
0
    }
240
241
0
    _engine.txn_manager()->add_txn_tablet_delta_writer(_req.txn_id, _req.tablet_id, this);
242
0
    {
243
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
244
0
        _unfinished_slave_node.insert(node_info.id());
245
0
    }
246
247
0
    std::vector<std::pair<int64_t, std::string>> indices_ids;
248
0
    auto cur_rowset = _rowset_builder->rowset();
249
0
    auto tablet_schema = cur_rowset->rowset_meta()->tablet_schema();
250
0
    if (!tablet_schema->skip_write_index_on_load()) {
251
0
        for (auto& column : tablet_schema->columns()) {
252
0
            const TabletIndex* index_meta = tablet_schema->inverted_index(*column);
253
0
            if (index_meta) {
254
0
                indices_ids.emplace_back(index_meta->index_id(), index_meta->get_index_suffix());
255
0
            }
256
0
        }
257
0
    }
258
259
0
    auto request = std::make_shared<PTabletWriteSlaveRequest>();
260
0
    auto* request_mutable_rs_meta = request->mutable_rowset_meta();
261
0
    *request_mutable_rs_meta = cur_rowset->rowset_meta()->get_rowset_pb();
262
0
    if (request_mutable_rs_meta != nullptr && request_mutable_rs_meta->has_partition_id() &&
263
0
        request_mutable_rs_meta->partition_id() == 0) {
264
        // TODO(dx): remove log after fix partition id eq 0 bug
265
0
        request_mutable_rs_meta->set_partition_id(_req.partition_id);
266
0
        LOG(WARNING) << "cant get partition id from local rs pb, get from _req, partition_id="
267
0
                     << _req.partition_id;
268
0
    }
269
0
    request->set_host(BackendOptions::get_localhost());
270
0
    request->set_http_port(config::webserver_port);
271
0
    const auto& tablet_path = cur_rowset->tablet_path();
272
0
    request->set_rowset_path(tablet_path);
273
0
    request->set_token(ExecEnv::GetInstance()->token());
274
0
    request->set_brpc_port(config::brpc_port);
275
0
    request->set_node_id(node_info.id());
276
0
    for (int segment_id = 0; segment_id < cur_rowset->rowset_meta()->num_segments(); segment_id++) {
277
0
        auto seg_path =
278
0
                local_segment_path(tablet_path, cur_rowset->rowset_id().to_string(), segment_id);
279
0
        int64_t segment_size = std::filesystem::file_size(seg_path);
280
0
        request->mutable_segments_size()->insert({segment_id, segment_size});
281
0
        auto index_path_prefix = InvertedIndexDescriptor::get_index_file_path_prefix(seg_path);
282
0
        if (!indices_ids.empty()) {
283
0
            if (tablet_schema->get_inverted_index_storage_format() ==
284
0
                InvertedIndexStorageFormatPB::V1) {
285
0
                for (auto index_meta : indices_ids) {
286
0
                    std::string inverted_index_file =
287
0
                            InvertedIndexDescriptor::get_index_file_path_v1(
288
0
                                    index_path_prefix, index_meta.first, index_meta.second);
289
0
                    int64_t size = std::filesystem::file_size(inverted_index_file);
290
0
                    PTabletWriteSlaveRequest::IndexSize index_size;
291
0
                    index_size.set_indexid(index_meta.first);
292
0
                    index_size.set_size(size);
293
0
                    index_size.set_suffix_path(index_meta.second);
294
                    // Fetch the map value for the current segment_id.
295
                    // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
296
0
                    auto& index_size_map_value =
297
0
                            (*(request->mutable_inverted_indices_size()))[segment_id];
298
                    // Add the new index size to the map value.
299
0
                    *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
300
0
                }
301
0
            } else {
302
0
                std::string inverted_index_file =
303
0
                        InvertedIndexDescriptor::get_index_file_path_v2(index_path_prefix);
304
0
                int64_t size = std::filesystem::file_size(inverted_index_file);
305
0
                PTabletWriteSlaveRequest::IndexSize index_size;
306
                // special id for non-V1 format
307
0
                index_size.set_indexid(0);
308
0
                index_size.set_size(size);
309
0
                index_size.set_suffix_path("");
310
                // Fetch the map value for the current segment_id.
311
                // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
312
0
                auto& index_size_map_value =
313
0
                        (*(request->mutable_inverted_indices_size()))[segment_id];
314
                // Add the new index size to the map value.
315
0
                *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
316
0
            }
317
0
        }
318
0
    }
319
320
0
    auto pull_callback = DummyBrpcCallback<PTabletWriteSlaveResult>::create_shared();
321
0
    auto closure = AutoReleaseClosure<
322
0
            PTabletWriteSlaveRequest,
323
0
            DummyBrpcCallback<PTabletWriteSlaveResult>>::create_unique(request, pull_callback);
324
0
    closure->cntl_->set_timeout_ms(config::slave_replica_writer_rpc_timeout_sec * 1000);
325
0
    closure->cntl_->ignore_eovercrowded();
326
0
    stub->request_slave_tablet_pull_rowset(closure->cntl_.get(), closure->request_.get(),
327
0
                                           closure->response_.get(), closure.get());
328
329
0
    closure.release();
330
0
    pull_callback->join();
331
0
    if (pull_callback->cntl_->Failed()) {
332
0
        if (!ExecEnv::GetInstance()->brpc_internal_client_cache()->available(
333
0
                    stub, node_info.host(), node_info.async_internal_port())) {
334
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
335
0
                    pull_callback->cntl_->remote_side());
336
0
        }
337
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica, error="
338
0
                     << berror(pull_callback->cntl_->ErrorCode())
339
0
                     << ", error_text=" << pull_callback->cntl_->ErrorText()
340
0
                     << ". slave host: " << node_info.host() << ", tablet_id=" << _req.tablet_id
341
0
                     << ", txn_id=" << _req.txn_id;
342
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
343
0
        _unfinished_slave_node.erase(node_info.id());
344
0
    }
345
0
}
346
347
0
void DeltaWriter::finish_slave_tablet_pull_rowset(int64_t node_id, bool is_succeed) {
348
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
349
0
    if (is_succeed) {
350
0
        _success_slave_node_ids.add_slave_node_ids(node_id);
351
0
        VLOG_CRITICAL << "record successful slave replica for txn [" << _req.txn_id
352
0
                      << "], tablet_id=" << _req.tablet_id << ", node_id=" << node_id;
353
0
    }
354
0
    _unfinished_slave_node.erase(node_id);
355
0
}
356
357
0
int64_t BaseDeltaWriter::num_rows_filtered() const {
358
0
    auto rowset_writer = _rowset_builder->rowset_writer();
359
0
    return rowset_writer == nullptr ? 0 : rowset_writer->num_rows_filtered();
360
0
}
361
362
} // namespace doris