Coverage Report

Created: 2024-11-22 12:31

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