Coverage Report

Created: 2025-04-26 11:22

/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/brpc_closure.h"
54
#include "util/mem_info.h"
55
#include "util/stopwatch.hpp"
56
#include "util/time.h"
57
#include "vec/core/block.h"
58
59
namespace doris {
60
#include "common/compile_check_begin.h"
61
using namespace ErrorCode;
62
63
BaseDeltaWriter::BaseDeltaWriter(const WriteRequest& req, RuntimeProfile* profile,
64
                                 const UniqueId& load_id)
65
15
        : _req(req), _memtable_writer(new MemTableWriter(req)) {
66
15
    _init_profile(profile);
67
15
}
68
69
DeltaWriter::DeltaWriter(StorageEngine& engine, const WriteRequest& req, RuntimeProfile* profile,
70
                         const UniqueId& load_id)
71
15
        : BaseDeltaWriter(req, profile, load_id), _engine(engine) {
72
15
    _rowset_builder = std::make_unique<RowsetBuilder>(_engine, req, profile);
73
15
}
74
75
15
void BaseDeltaWriter::_init_profile(RuntimeProfile* profile) {
76
15
    _profile = profile->create_child(fmt::format("DeltaWriter {}", _req.tablet_id), true, true);
77
15
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
78
15
    _wait_flush_limit_timer = ADD_TIMER(_profile, "WaitFlushLimitTime");
79
15
}
80
81
0
void DeltaWriter::_init_profile(RuntimeProfile* profile) {
82
0
    BaseDeltaWriter::_init_profile(profile);
83
0
    _commit_txn_timer = ADD_TIMER(_profile, "CommitTxnTime");
84
0
}
85
86
15
BaseDeltaWriter::~BaseDeltaWriter() {
87
15
    if (!_is_init) {
88
0
        return;
89
0
    }
90
91
    // cancel and wait all memtables in flush queue to be finished
92
15
    static_cast<void>(_memtable_writer->cancel());
93
94
15
    if (_rowset_builder->tablet() != nullptr) {
95
15
        const FlushStatistic& stat = _memtable_writer->get_flush_token_stats();
96
15
        _rowset_builder->tablet()->flush_bytes->increment(stat.flush_size_bytes);
97
15
        _rowset_builder->tablet()->flush_finish_count->increment(stat.flush_finish_count);
98
15
    }
99
15
}
100
101
15
DeltaWriter::~DeltaWriter() = default;
102
103
15
Status BaseDeltaWriter::init() {
104
15
    if (_is_init) {
105
0
        return Status::OK();
106
0
    }
107
15
    auto* t_ctx = doris::thread_context(true);
108
15
    std::shared_ptr<WorkloadGroup> wg_sptr = nullptr;
109
15
    if (t_ctx && t_ctx->is_attach_task()) {
110
0
        wg_sptr = t_ctx->resource_ctx()->workload_group();
111
0
    }
112
15
    RETURN_IF_ERROR(_rowset_builder->init());
113
15
    RETURN_IF_ERROR(_memtable_writer->init(
114
15
            _rowset_builder->rowset_writer(), _rowset_builder->tablet_schema(),
115
15
            _rowset_builder->get_partial_update_info(), wg_sptr,
116
15
            _rowset_builder->tablet()->enable_unique_key_merge_on_write()));
117
15
    ExecEnv::GetInstance()->memtable_memory_limiter()->register_writer(_memtable_writer);
118
15
    _is_init = true;
119
15
    return Status::OK();
120
15
}
121
122
20
Status DeltaWriter::write(const vectorized::Block* block, const DorisVector<uint32_t>& row_idxs) {
123
20
    if (UNLIKELY(row_idxs.empty())) {
124
0
        return Status::OK();
125
0
    }
126
20
    _lock_watch.start();
127
20
    std::lock_guard<std::mutex> l(_lock);
128
20
    _lock_watch.stop();
129
20
    if (!_is_init && !_is_cancelled) {
130
12
        RETURN_IF_ERROR(init());
131
12
    }
132
20
    {
133
20
        SCOPED_TIMER(_wait_flush_limit_timer);
134
20
        while (_memtable_writer->flush_running_count() >=
135
20
               config::memtable_flush_running_count_limit) {
136
0
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
137
0
        }
138
20
    }
139
20
    return _memtable_writer->write(block, row_idxs);
140
20
}
141
142
9
Status BaseDeltaWriter::wait_flush() {
143
9
    return _memtable_writer->wait_flush();
144
9
}
145
146
15
Status DeltaWriter::close() {
147
15
    _lock_watch.start();
148
15
    std::lock_guard<std::mutex> l(_lock);
149
15
    _lock_watch.stop();
150
15
    if (!_is_init && !_is_cancelled) {
151
        // if this delta writer is not initialized, but close() is called.
152
        // which means this tablet has no data loaded, but at least one tablet
153
        // in same partition has data loaded.
154
        // so we have to also init this DeltaWriter, so that it can create an empty rowset
155
        // for this tablet when being closed.
156
3
        RETURN_IF_ERROR(init());
157
3
    }
158
15
    return _memtable_writer->close();
159
15
}
160
161
15
Status BaseDeltaWriter::build_rowset() {
162
15
    SCOPED_TIMER(_close_wait_timer);
163
15
    RETURN_IF_ERROR(_memtable_writer->close_wait(_profile));
164
15
    return _rowset_builder->build_rowset();
165
15
}
166
167
15
Status DeltaWriter::build_rowset() {
168
15
    std::lock_guard<std::mutex> l(_lock);
169
15
    DCHECK(_is_init)
170
0
            << "delta writer is supposed be to initialized before build_rowset() being called";
171
15
    return BaseDeltaWriter::build_rowset();
172
15
}
173
174
9
Status BaseDeltaWriter::submit_calc_delete_bitmap_task() {
175
9
    return _rowset_builder->submit_calc_delete_bitmap_task();
176
9
}
177
178
9
Status BaseDeltaWriter::wait_calc_delete_bitmap() {
179
9
    return _rowset_builder->wait_calc_delete_bitmap();
180
9
}
181
182
15
RowsetBuilder* DeltaWriter::rowset_builder() {
183
15
    return static_cast<RowsetBuilder*>(_rowset_builder.get());
184
15
}
185
186
15
Status DeltaWriter::commit_txn(const PSlaveTabletNodes& slave_tablet_nodes) {
187
15
    std::lock_guard<std::mutex> l(_lock);
188
15
    SCOPED_TIMER(_commit_txn_timer);
189
15
    RETURN_IF_ERROR(rowset_builder()->commit_txn());
190
191
15
    for (auto&& node_info : slave_tablet_nodes.slave_nodes()) {
192
0
        _request_slave_tablet_pull_rowset(node_info);
193
0
    }
194
15
    return Status::OK();
195
15
}
196
197
bool DeltaWriter::check_slave_replicas_done(
198
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
199
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
200
0
    if (_unfinished_slave_node.empty()) {
201
0
        success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
202
0
        return true;
203
0
    }
204
0
    return false;
205
0
}
206
207
void DeltaWriter::add_finished_slave_replicas(
208
0
        google::protobuf::Map<int64_t, PSuccessSlaveTabletNodeIds>* success_slave_tablet_node_ids) {
209
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
210
0
    success_slave_tablet_node_ids->insert({_req.tablet_id, _success_slave_node_ids});
211
0
}
212
213
0
Status BaseDeltaWriter::cancel() {
214
0
    return cancel_with_status(Status::Cancelled("already cancelled"));
215
0
}
216
217
0
Status BaseDeltaWriter::cancel_with_status(const Status& st) {
218
0
    if (_is_cancelled) {
219
0
        return Status::OK();
220
0
    }
221
0
    RETURN_IF_ERROR(_memtable_writer->cancel_with_status(st));
222
0
    _is_cancelled = true;
223
0
    return Status::OK();
224
0
}
225
226
0
Status DeltaWriter::cancel_with_status(const Status& st) {
227
0
    std::lock_guard<std::mutex> l(_lock);
228
0
    return BaseDeltaWriter::cancel_with_status(st);
229
0
}
230
231
0
int64_t BaseDeltaWriter::mem_consumption(MemType mem) {
232
0
    return _memtable_writer->mem_consumption(mem);
233
0
}
234
235
0
void DeltaWriter::_request_slave_tablet_pull_rowset(const PNodeInfo& node_info) {
236
0
    std::shared_ptr<PBackendService_Stub> stub =
237
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
238
0
                    node_info.host(), node_info.async_internal_port());
239
0
    if (stub == nullptr) {
240
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica. get rpc stub failed, "
241
0
                        "slave host="
242
0
                     << node_info.host() << ", port=" << node_info.async_internal_port()
243
0
                     << ", tablet_id=" << _req.tablet_id << ", txn_id=" << _req.txn_id;
244
0
        return;
245
0
    }
246
247
0
    _engine.txn_manager()->add_txn_tablet_delta_writer(_req.txn_id, _req.tablet_id, this);
248
0
    {
249
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
250
0
        _unfinished_slave_node.insert(node_info.id());
251
0
    }
252
253
0
    std::vector<std::pair<int64_t, std::string>> indices_ids;
254
0
    auto cur_rowset = _rowset_builder->rowset();
255
0
    auto tablet_schema = cur_rowset->rowset_meta()->tablet_schema();
256
0
    if (!tablet_schema->skip_write_index_on_load()) {
257
0
        for (auto& column : tablet_schema->columns()) {
258
0
            const TabletIndex* index_meta = tablet_schema->inverted_index(*column);
259
0
            if (index_meta) {
260
0
                indices_ids.emplace_back(index_meta->index_id(), index_meta->get_index_suffix());
261
0
            }
262
0
        }
263
0
    }
264
265
0
    auto request = std::make_shared<PTabletWriteSlaveRequest>();
266
0
    auto* request_mutable_rs_meta = request->mutable_rowset_meta();
267
0
    *request_mutable_rs_meta = cur_rowset->rowset_meta()->get_rowset_pb();
268
0
    if (request_mutable_rs_meta != nullptr && request_mutable_rs_meta->has_partition_id() &&
269
0
        request_mutable_rs_meta->partition_id() == 0) {
270
        // TODO(dx): remove log after fix partition id eq 0 bug
271
0
        request_mutable_rs_meta->set_partition_id(_req.partition_id);
272
0
        LOG(WARNING) << "cant get partition id from local rs pb, get from _req, partition_id="
273
0
                     << _req.partition_id;
274
0
    }
275
0
    request->set_host(BackendOptions::get_localhost());
276
0
    request->set_http_port(config::webserver_port);
277
0
    const auto& tablet_path = cur_rowset->tablet_path();
278
0
    request->set_rowset_path(tablet_path);
279
0
    request->set_token(ExecEnv::GetInstance()->token());
280
0
    request->set_brpc_port(config::brpc_port);
281
0
    request->set_node_id(static_cast<int32_t>(node_info.id()));
282
0
    for (int segment_id = 0; segment_id < cur_rowset->rowset_meta()->num_segments(); segment_id++) {
283
0
        auto seg_path =
284
0
                local_segment_path(tablet_path, cur_rowset->rowset_id().to_string(), segment_id);
285
0
        int64_t segment_size = std::filesystem::file_size(seg_path);
286
0
        request->mutable_segments_size()->insert({segment_id, segment_size});
287
0
        auto index_path_prefix = InvertedIndexDescriptor::get_index_file_path_prefix(seg_path);
288
0
        if (!indices_ids.empty()) {
289
0
            if (tablet_schema->get_inverted_index_storage_format() ==
290
0
                InvertedIndexStorageFormatPB::V1) {
291
0
                for (auto index_meta : indices_ids) {
292
0
                    std::string inverted_index_file =
293
0
                            InvertedIndexDescriptor::get_index_file_path_v1(
294
0
                                    index_path_prefix, index_meta.first, index_meta.second);
295
0
                    int64_t size = std::filesystem::file_size(inverted_index_file);
296
0
                    PTabletWriteSlaveRequest::IndexSize index_size;
297
0
                    index_size.set_indexid(index_meta.first);
298
0
                    index_size.set_size(size);
299
0
                    index_size.set_suffix_path(index_meta.second);
300
                    // Fetch the map value for the current segment_id.
301
                    // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
302
0
                    auto& index_size_map_value =
303
0
                            (*(request->mutable_inverted_indices_size()))[segment_id];
304
                    // Add the new index size to the map value.
305
0
                    *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
306
0
                }
307
0
            } else {
308
0
                std::string inverted_index_file =
309
0
                        InvertedIndexDescriptor::get_index_file_path_v2(index_path_prefix);
310
0
                int64_t size = std::filesystem::file_size(inverted_index_file);
311
0
                PTabletWriteSlaveRequest::IndexSize index_size;
312
                // special id for non-V1 format
313
0
                index_size.set_indexid(0);
314
0
                index_size.set_size(size);
315
0
                index_size.set_suffix_path("");
316
                // Fetch the map value for the current segment_id.
317
                // If it doesn't exist, this will insert a new default-constructed IndexSizeMapValue
318
0
                auto& index_size_map_value =
319
0
                        (*(request->mutable_inverted_indices_size()))[segment_id];
320
                // Add the new index size to the map value.
321
0
                *index_size_map_value.mutable_index_sizes()->Add() = std::move(index_size);
322
0
            }
323
0
        }
324
0
    }
325
326
0
    auto pull_callback = DummyBrpcCallback<PTabletWriteSlaveResult>::create_shared();
327
0
    auto closure = AutoReleaseClosure<
328
0
            PTabletWriteSlaveRequest,
329
0
            DummyBrpcCallback<PTabletWriteSlaveResult>>::create_unique(request, pull_callback);
330
0
    closure->cntl_->set_timeout_ms(config::slave_replica_writer_rpc_timeout_sec * 1000);
331
0
    closure->cntl_->ignore_eovercrowded();
332
0
    stub->request_slave_tablet_pull_rowset(closure->cntl_.get(), closure->request_.get(),
333
0
                                           closure->response_.get(), closure.get());
334
335
0
    closure.release();
336
0
    pull_callback->join();
337
0
    if (pull_callback->cntl_->Failed()) {
338
0
        if (!ExecEnv::GetInstance()->brpc_internal_client_cache()->available(
339
0
                    stub, node_info.host(), node_info.async_internal_port())) {
340
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
341
0
                    pull_callback->cntl_->remote_side());
342
0
        }
343
0
        LOG(WARNING) << "failed to send pull rowset request to slave replica, error="
344
0
                     << berror(pull_callback->cntl_->ErrorCode())
345
0
                     << ", error_text=" << pull_callback->cntl_->ErrorText()
346
0
                     << ". slave host: " << node_info.host() << ", tablet_id=" << _req.tablet_id
347
0
                     << ", txn_id=" << _req.txn_id;
348
0
        std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
349
0
        _unfinished_slave_node.erase(node_info.id());
350
0
    }
351
0
}
352
353
0
void DeltaWriter::finish_slave_tablet_pull_rowset(int64_t node_id, bool is_succeed) {
354
0
    std::lock_guard<std::shared_mutex> lock(_slave_node_lock);
355
0
    if (is_succeed) {
356
0
        _success_slave_node_ids.add_slave_node_ids(node_id);
357
0
        VLOG_CRITICAL << "record successful slave replica for txn [" << _req.txn_id
358
0
                      << "], tablet_id=" << _req.tablet_id << ", node_id=" << node_id;
359
0
    }
360
0
    _unfinished_slave_node.erase(node_id);
361
0
}
362
363
0
int64_t BaseDeltaWriter::num_rows_filtered() const {
364
0
    auto rowset_writer = _rowset_builder->rowset_writer();
365
0
    return rowset_writer == nullptr ? 0 : rowset_writer->num_rows_filtered();
366
0
}
367
368
#include "common/compile_check_end.h"
369
} // namespace doris