Coverage Report

Created: 2026-06-09 21:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_tablets_channel.cpp
Line
Count
Source
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 "cloud/cloud_tablets_channel.h"
19
20
#include <mutex>
21
22
#include "cloud/cloud_delta_writer.h"
23
#include "cloud/cloud_meta_mgr.h"
24
#include "cloud/cloud_storage_engine.h"
25
#include "cloud/config.h"
26
#include "load/channel/tablets_channel.h"
27
#include "load/delta_writer/delta_writer.h"
28
#include "storage/tablet_info.h"
29
30
namespace doris {
31
32
CloudTabletsChannel::CloudTabletsChannel(CloudStorageEngine& engine, const TabletsChannelKey& key,
33
                                         const UniqueId& load_id, bool is_high_priority,
34
                                         RuntimeProfile* profile)
35
0
        : BaseTabletsChannel(key, load_id, is_high_priority, profile), _engine(engine) {}
36
37
0
CloudTabletsChannel::~CloudTabletsChannel() = default;
38
39
std::unique_ptr<BaseDeltaWriter> CloudTabletsChannel::create_delta_writer(
40
0
        const WriteRequest& request) {
41
0
    return std::make_unique<CloudDeltaWriter>(_engine, request, _profile, _load_id);
42
0
}
43
44
Status CloudTabletsChannel::add_batch(const PTabletWriterAddBlockRequest& request,
45
0
                                      PTabletWriterAddBlockResult* response) {
46
0
    if (_schema != nullptr && _schema->row_binlog_index_schema() != nullptr) {
47
0
        return Status::NotSupported("cloud mode does not support binlog<row> now");
48
0
    }
49
    // FIXME(plat1ko): Too many duplicate code with `TabletsChannel`
50
0
    SCOPED_TIMER(_add_batch_timer);
51
0
    int64_t cur_seq = 0;
52
0
    if (_add_batch_number_counter != nullptr) {
53
0
        _add_batch_number_counter->update(1);
54
0
    }
55
56
0
    auto status = _get_current_seq(cur_seq, request);
57
0
    if (UNLIKELY(!status.ok())) {
58
0
        return status;
59
0
    }
60
61
0
    if (request.packet_seq() < cur_seq) {
62
0
        LOG(INFO) << "packet has already recept before, expect_seq=" << cur_seq
63
0
                  << ", recept_seq=" << request.packet_seq();
64
0
        return Status::OK();
65
0
    }
66
67
0
    if (request.is_receiver_side_random_bucket()) {
68
0
        std::unordered_map<int64_t, DorisVector<uint32_t>> partition_to_rowidxs;
69
0
        RETURN_IF_ERROR(_build_partition_to_rowidxs_for_receiver_side_random_bucket(
70
0
                request, &partition_to_rowidxs));
71
0
        if (!partition_to_rowidxs.empty()) {
72
0
            std::unordered_set<int64_t> partition_ids;
73
0
            partition_ids.reserve(partition_to_rowidxs.size());
74
0
            for (const auto& [partition_id, _] : partition_to_rowidxs) {
75
0
                partition_ids.insert(partition_id);
76
0
            }
77
0
            {
78
0
                std::lock_guard<std::mutex> l(_tablet_writers_lock);
79
0
                RETURN_IF_ERROR(_init_writers_by_partition_ids(partition_ids));
80
0
            }
81
0
        }
82
0
        return _write_block_data_for_receiver_side_random_bucket(request, cur_seq,
83
0
                                                                 partition_to_rowidxs, response);
84
0
    }
85
86
0
    std::unordered_map<int64_t, DorisVector<uint32_t>> tablet_to_rowidxs;
87
0
    _build_tablet_to_rowidxs(request, &tablet_to_rowidxs);
88
89
0
    std::unordered_set<int64_t> partition_ids;
90
0
    std::vector<CloudDeltaWriter*> writers;
91
0
    {
92
        // add_batch may concurrency with inc_open but not under _lock.
93
        // so need to protect it with _tablet_writers_lock.
94
0
        std::lock_guard<std::mutex> l(_tablet_writers_lock);
95
0
        for (auto& [tablet_id, _] : tablet_to_rowidxs) {
96
0
            auto tablet_writer_it = _tablet_writers.find(tablet_id);
97
0
            if (tablet_writer_it == _tablet_writers.end()) {
98
0
                return Status::InternalError("unknown tablet to append data, tablet={}", tablet_id);
99
0
            }
100
0
            partition_ids.insert(tablet_writer_it->second->partition_id());
101
0
            writers.push_back(static_cast<CloudDeltaWriter*>(tablet_writer_it->second.get()));
102
0
        }
103
0
        if (config::skip_writing_empty_rowset_metadata && !writers.empty()) {
104
0
            RETURN_IF_ERROR(CloudDeltaWriter::batch_init(writers));
105
0
        } else if (!partition_ids.empty()) {
106
0
            RETURN_IF_ERROR(_init_writers_by_partition_ids(partition_ids));
107
0
        }
108
0
    }
109
110
0
    return _write_block_data(request, cur_seq, tablet_to_rowidxs, response);
111
0
}
112
113
Status CloudTabletsChannel::_init_writers_by_partition_ids(
114
0
        const std::unordered_set<int64_t>& partition_ids) {
115
0
    std::vector<CloudDeltaWriter*> writers;
116
0
    for (auto&& [tablet_id, base_writer] : _tablet_writers) {
117
0
        auto* writer = static_cast<CloudDeltaWriter*>(base_writer.get());
118
0
        if (partition_ids.contains(writer->partition_id()) && !writer->is_init()) {
119
0
            writers.push_back(writer);
120
0
        }
121
0
    }
122
0
    if (!writers.empty()) {
123
0
        RETURN_IF_ERROR(CloudDeltaWriter::batch_init(writers));
124
0
    }
125
0
    return Status::OK();
126
0
}
127
128
Status CloudTabletsChannel::close(LoadChannel* parent, const PTabletWriterAddBlockRequest& req,
129
0
                                  PTabletWriterAddBlockResult* res, bool* finished) {
130
    // FIXME(plat1ko): Too many duplicate code with `TabletsChannel`
131
0
    std::lock_guard l(_lock);
132
0
    if (_state == kFinished) {
133
0
        return _close_status;
134
0
    }
135
136
0
    auto sender_id = req.sender_id();
137
0
    if (_closed_senders.Get(sender_id)) {
138
        // Double close from one sender, just return OK
139
0
        *finished = (_num_remaining_senders == 0);
140
0
        return _close_status;
141
0
    }
142
143
0
    for (auto pid : req.partition_ids()) {
144
0
        _partition_ids.emplace(pid);
145
0
    }
146
147
0
    _closed_senders.Set(sender_id, true);
148
0
    _num_remaining_senders--;
149
0
    *finished = (_num_remaining_senders == 0);
150
151
0
    LOG(INFO) << "close tablets channel: " << _key << ", sender id: " << sender_id
152
0
              << ", backend id: " << req.backend_id()
153
0
              << " remaining sender: " << _num_remaining_senders;
154
155
0
    if (!*finished) {
156
0
        return Status::OK();
157
0
    }
158
159
0
    auto* tablet_errors = res->mutable_tablet_errors();
160
0
    auto* tablet_vec = res->mutable_tablet_vec();
161
0
    _state = kFinished;
162
163
    // All senders are closed
164
    // 1. close all delta writers. under _lock.
165
0
    std::vector<CloudDeltaWriter*> writers_to_commit;
166
0
    writers_to_commit.reserve(_tablet_writers.size());
167
0
    bool success = true;
168
169
0
    for (auto&& [tablet_id, base_writer] : _tablet_writers) {
170
0
        auto* writer = static_cast<CloudDeltaWriter*>(base_writer.get());
171
        // ATTN: the strict mode means strict filtering of column type conversions during import.
172
        // Sometimes all inputs are filtered, but the partition ID is still set, and the writer is
173
        // not initialized.
174
0
        if (_partition_ids.contains(writer->partition_id())) {
175
0
            if (!success) { // Already failed, cancel all remain writers
176
0
                static_cast<void>(writer->cancel());
177
0
                continue;
178
0
            }
179
180
0
            if (writer->is_init()) {
181
0
                auto st = writer->close();
182
0
                if (!st.ok()) {
183
0
                    LOG(WARNING) << "close tablet writer failed, tablet_id=" << tablet_id
184
0
                                 << ", txn_id=" << _txn_id << ", err=" << st;
185
0
                    PTabletError* tablet_error = tablet_errors->Add();
186
0
                    tablet_error->set_tablet_id(tablet_id);
187
0
                    tablet_error->set_msg(st.to_string());
188
0
                    success = false;
189
0
                    _close_status = std::move(st);
190
0
                    continue;
191
0
                }
192
0
            }
193
194
            // to make sure tablet writer in `_broken_tablets` won't call `close_wait` method.
195
0
            if (_is_broken_tablet(writer->tablet_id())) {
196
0
                LOG(WARNING) << "SHOULD NOT HAPPEN, tablet writer is broken but not cancelled"
197
0
                             << ", tablet_id=" << tablet_id << ", transaction_id=" << _txn_id;
198
0
                continue;
199
0
            }
200
201
0
            writers_to_commit.push_back(writer);
202
0
        } else {
203
0
            auto st = writer->cancel();
204
0
            if (!st.ok()) {
205
0
                LOG(WARNING) << "cancel tablet writer failed, tablet_id=" << tablet_id
206
0
                             << ", txn_id=" << _txn_id;
207
                // just skip this tablet(writer) and continue to close others
208
0
                continue;
209
0
            }
210
0
        }
211
0
    }
212
213
0
    if (!success) {
214
0
        return _close_status;
215
0
    }
216
217
    // 2. wait delta writers
218
0
    using namespace std::chrono;
219
0
    auto build_start = steady_clock::now();
220
0
    for (auto* writer : writers_to_commit) {
221
0
        if (!writer->is_init()) {
222
0
            continue;
223
0
        }
224
225
0
        auto st = writer->build_rowset();
226
0
        if (!st.ok()) {
227
0
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
228
0
                         << ", err=" << st;
229
0
            PTabletError* tablet_error = tablet_errors->Add();
230
0
            tablet_error->set_tablet_id(writer->tablet_id());
231
0
            tablet_error->set_msg(st.to_string());
232
0
            _close_status = std::move(st);
233
0
            return _close_status;
234
0
        }
235
0
    }
236
0
    int64_t build_latency = duration_cast<milliseconds>(steady_clock::now() - build_start).count();
237
238
    // 3. commit rowsets to meta-service
239
0
    auto commit_start = steady_clock::now();
240
0
    std::vector<std::function<Status()>> tasks;
241
0
    tasks.reserve(writers_to_commit.size());
242
0
    for (auto* writer : writers_to_commit) {
243
0
        tasks.emplace_back([writer] { return writer->commit_rowset(); });
244
0
    }
245
0
    _close_status = cloud::bthread_fork_join(tasks, 10);
246
0
    if (!_close_status.ok()) {
247
0
        return _close_status;
248
0
    }
249
250
0
    int64_t commit_latency =
251
0
            duration_cast<milliseconds>(steady_clock::now() - commit_start).count();
252
253
    // 4. calculate delete bitmap for Unique Key MoW tables
254
0
    for (auto* writer : writers_to_commit) {
255
0
        auto st = writer->submit_calc_delete_bitmap_task();
256
0
        if (!st.ok()) {
257
0
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
258
0
                         << ", err=" << st;
259
0
            _add_error_tablet(tablet_errors, writer->tablet_id(), st);
260
0
            _close_status = std::move(st);
261
0
            return _close_status;
262
0
        }
263
0
    }
264
265
    // 5. wait for delete bitmap calculation complete if necessary
266
0
    for (auto* writer : writers_to_commit) {
267
0
        auto st = writer->wait_calc_delete_bitmap();
268
0
        if (!st.ok()) {
269
0
            LOG(WARNING) << "failed to close wait DeltaWriter. tablet_id=" << writer->tablet_id()
270
0
                         << ", err=" << st;
271
0
            _add_error_tablet(tablet_errors, writer->tablet_id(), st);
272
0
            _close_status = std::move(st);
273
0
            return _close_status;
274
0
        }
275
0
    }
276
277
    // 6. set txn related info if necessary
278
0
    for (auto it = writers_to_commit.begin(); it != writers_to_commit.end();) {
279
0
        auto st = (*it)->set_txn_related_info();
280
0
        if (!st.ok()) {
281
0
            _add_error_tablet(tablet_errors, (*it)->tablet_id(), st);
282
0
            _close_status = std::move(st);
283
0
            return _close_status;
284
0
        }
285
0
        it++;
286
0
    }
287
288
0
    tablet_vec->Reserve(static_cast<int>(writers_to_commit.size()));
289
0
    for (auto* writer : writers_to_commit) {
290
0
        PTabletInfo* tablet_info = tablet_vec->Add();
291
0
        tablet_info->set_tablet_id(writer->tablet_id());
292
        // unused required field.
293
0
        tablet_info->set_schema_hash(0);
294
0
        tablet_info->set_received_rows(writer->total_received_rows());
295
0
        tablet_info->set_num_rows_filtered(writer->num_rows_filtered());
296
        // These stats may be larger than the actual value if the txn is aborted
297
0
        writer->update_tablet_stats();
298
0
    }
299
0
    res->set_build_rowset_latency_ms(build_latency);
300
0
    res->set_commit_rowset_latency_ms(commit_latency);
301
0
    return Status::OK();
302
0
}
303
304
} // namespace doris