Coverage Report

Created: 2026-08-06 12:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/multi_table_pipe.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 "io/fs/multi_table_pipe.h"
19
20
#include <gen_cpp/FrontendService.h>
21
#include <gen_cpp/FrontendService_types.h>
22
#include <gen_cpp/HeartbeatService_types.h>
23
#include <gen_cpp/PaloInternalService_types.h>
24
#include <gen_cpp/Types_types.h>
25
#include <thrift/protocol/TDebugProtocol.h>
26
27
#include <type_traits>
28
29
#include "common/status.h"
30
#include "load/stream_load/new_load_stream_mgr.h"
31
#include "runtime/cluster_info.h"
32
#include "runtime/exec_env.h"
33
#include "runtime/fragment_mgr.h"
34
#include "runtime/runtime_state.h"
35
#include "util/client_cache.h"
36
#include "util/debug_points.h"
37
#include "util/thrift_rpc_helper.h"
38
#include "util/thrift_util.h"
39
#include "util/time.h"
40
41
namespace doris {
42
namespace io {
43
44
6
Status MultiTablePipe::append_with_line_delimiter(const char* data, size_t size) {
45
6
    const std::string& table = parse_dst_table(data, size);
46
6
    if (table.empty()) {
47
0
        return Status::InternalError("table name is empty");
48
0
    }
49
6
    size_t prefix_len = table.length() + 1;
50
6
    AppendFunc cb = &KafkaConsumerPipe::append_with_line_delimiter;
51
6
    return dispatch(table, data + prefix_len, size - prefix_len, cb);
52
6
}
53
54
11
Status MultiTablePipe::append_json(const char* data, size_t size) {
55
11
    const std::string& table = parse_dst_table(data, size);
56
11
    if (table.empty()) {
57
0
        return Status::InternalError("table name is empty");
58
0
    }
59
11
    size_t prefix_len = table.length() + 1;
60
11
    AppendFunc cb = &KafkaConsumerPipe::append_json;
61
11
    return dispatch(table, data + prefix_len, size - prefix_len, cb);
62
11
}
63
64
5
KafkaConsumerPipePtr MultiTablePipe::get_pipe_by_table(const std::string& table) {
65
5
    auto pair = _planned_tables.find(table);
66
5
    DCHECK(pair != _planned_tables.end());
67
5
    return std::static_pointer_cast<io::KafkaConsumerPipe>(pair->second->pipe);
68
5
}
69
70
17
static std::string_view get_first_part(const char* dat, char delimiter) {
71
17
    const char* delimiterPos = std::strchr(dat, delimiter);
72
73
17
    if (delimiterPos != nullptr) {
74
17
        std::ptrdiff_t length = delimiterPos - dat;
75
17
        return std::string_view(dat, length);
76
17
    } else {
77
0
        return std::string_view(dat);
78
0
    }
79
17
}
80
81
11
Status MultiTablePipe::finish() {
82
11
    for (auto& pair : _planned_tables) {
83
8
        RETURN_IF_ERROR(pair.second->pipe->finish());
84
8
    }
85
11
    return Status::OK();
86
11
}
87
88
1
void MultiTablePipe::cancel(const std::string& reason) {
89
1
    for (auto& pair : _planned_tables) {
90
0
        pair.second->pipe->cancel(reason);
91
0
    }
92
1
}
93
94
17
std::string MultiTablePipe::parse_dst_table(const char* data, size_t size) {
95
17
    return std::string(get_first_part(data, '|'));
96
17
}
97
98
Status MultiTablePipe::dispatch(const std::string& table, const char* data, size_t size,
99
9
                                AppendFunc cb) {
100
9
    if (size == 0) {
101
0
        LOG(WARNING) << "empty data for table: " << table << ", ctx: " << _ctx->brief();
102
0
        return Status::InternalError("empty data");
103
0
    }
104
9
    KafkaConsumerPipePtr pipe = nullptr;
105
9
    auto iter = _planned_tables.find(table);
106
9
    if (iter != _planned_tables.end()) {
107
0
        pipe = std::static_pointer_cast<io::KafkaConsumerPipe>(iter->second->pipe);
108
0
        RETURN_NOT_OK_STATUS_WITH_WARN((pipe.get()->*cb)(data, size),
109
0
                                       "append failed in planned kafka pipe");
110
9
    } else {
111
9
        iter = _unplanned_tables.find(table);
112
9
        if (iter == _unplanned_tables.end()) {
113
9
            std::shared_ptr<StreamLoadContext> ctx =
114
9
                    std::make_shared<StreamLoadContext>(doris::ExecEnv::GetInstance());
115
9
            ctx->id = UniqueId::gen_uid();
116
9
            pipe = std::make_shared<io::KafkaConsumerPipe>();
117
9
            ctx->pipe = pipe;
118
9
#ifndef BE_TEST
119
9
            RETURN_NOT_OK_STATUS_WITH_WARN(
120
9
                    doris::ExecEnv::GetInstance()->new_load_stream_mgr()->put(ctx->id, ctx),
121
9
                    "put stream load ctx error");
122
9
#endif
123
9
            _unplanned_tables.emplace(table, ctx);
124
9
            LOG(INFO) << "create new unplanned table ctx, table: " << table
125
9
                      << "load id: " << ctx->id << ", txn id: " << _ctx->txn_id;
126
9
        } else {
127
0
            pipe = std::static_pointer_cast<io::KafkaConsumerPipe>(iter->second->pipe);
128
0
        }
129
130
        // It is necessary to determine whether the sum of pipe_current_capacity and size is greater than pipe_max_capacity,
131
        // otherwise the following situation may occur:
132
        // the pipe is full but still cannot trigger the request and exec plan condition,
133
        // causing one stream multi table load can not finish
134
9
        ++_unplanned_row_cnt;
135
9
        auto pipe_current_capacity = pipe->current_capacity();
136
9
        auto pipe_max_capacity = pipe->max_capacity();
137
9
        if (_unplanned_row_cnt >= _row_threshold ||
138
9
            _unplanned_tables.size() >= _wait_tables_threshold ||
139
9
            pipe_current_capacity + size > pipe_max_capacity) {
140
0
            LOG(INFO) << fmt::format(
141
0
                                 "unplanned row cnt={} reach row_threshold={} or "
142
0
                                 "wait_plan_table_threshold={}, or the sum of "
143
0
                                 "pipe_current_capacity {} "
144
0
                                 "and size {} is greater than pipe_max_capacity {}, "
145
0
                                 "plan them",
146
0
                                 _unplanned_row_cnt, _row_threshold, _wait_tables_threshold,
147
0
                                 pipe_current_capacity, size, pipe_max_capacity)
148
0
                      << ", ctx: " << _ctx->brief();
149
0
            Status st = request_and_exec_plans();
150
0
            _unplanned_row_cnt = 0;
151
0
            if (!st.ok()) {
152
0
                return st;
153
0
            }
154
0
        }
155
156
9
        RETURN_NOT_OK_STATUS_WITH_WARN((pipe.get()->*cb)(data, size),
157
9
                                       "append failed in unplanned kafka pipe");
158
9
    }
159
160
9
    return Status::OK();
161
9
}
162
163
#ifndef BE_TEST
164
6
Status MultiTablePipe::request_and_exec_plans() {
165
6
    if (_unplanned_tables.empty()) {
166
0
        return Status::OK();
167
0
    }
168
169
6
    fmt::memory_buffer log_buffer;
170
6
    log_buffer.clear();
171
6
    fmt::format_to(log_buffer, "request plans for {} tables: [ ", _unplanned_tables.size());
172
9
    for (auto& pair : _unplanned_tables) {
173
9
        fmt::format_to(log_buffer, "{} ", pair.first);
174
9
    }
175
6
    fmt::format_to(log_buffer, "]");
176
6
    LOG(INFO) << fmt::to_string(log_buffer);
177
178
6
    Status st;
179
9
    for (auto& pair : _unplanned_tables) {
180
9
        TStreamLoadPutRequest request;
181
9
        set_request_auth(&request, _ctx->auth);
182
9
        std::vector<std::string> tables;
183
9
        tables.push_back(pair.first);
184
9
        request.db = _ctx->db;
185
9
        request.table_names = tables;
186
9
        request.__isset.table_names = true;
187
9
        request.txnId = _ctx->txn_id;
188
9
        request.formatType = _ctx->format;
189
9
        request.__set_compress_type(_ctx->compress_type);
190
9
        request.__set_header_type(_ctx->header_type);
191
9
        request.__set_loadId((pair.second->id).to_thrift());
192
9
        request.fileType = TFileType::FILE_STREAM;
193
9
        request.__set_thrift_rpc_timeout_ms(config::thrift_rpc_timeout_ms);
194
9
        request.__set_memtable_on_sink_node(_ctx->memtable_on_sink_node);
195
9
        request.__set_user(_ctx->qualified_user);
196
9
        request.__set_cloud_cluster(_ctx->cloud_cluster);
197
9
        request.__set_max_filter_ratio(1.0);
198
        // no need to register new_load_stream_mgr coz it is already done in routineload submit task
199
200
        // plan this load
201
9
        ExecEnv* exec_env = doris::ExecEnv::GetInstance();
202
9
        TNetworkAddress master_addr = exec_env->cluster_info()->master_fe_addr;
203
9
        int64_t stream_load_put_start_time = MonotonicNanos();
204
9
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
205
9
                master_addr.hostname, master_addr.port,
206
9
                [&request, this](FrontendServiceConnection& client) {
207
9
                    client->streamLoadMultiTablePut(_ctx->multi_table_put_result, request);
208
9
                }));
209
9
        _ctx->stream_load_put_cost_nanos = MonotonicNanos() - stream_load_put_start_time;
210
211
9
        Status plan_status(Status::create(_ctx->multi_table_put_result.status));
212
9
        if (!plan_status.ok()) {
213
1
            LOG(WARNING) << "plan streaming load failed. errmsg=" << plan_status << _ctx->brief();
214
1
            return plan_status;
215
1
        }
216
217
8
        if (_ctx->multi_table_put_result.__isset.pipeline_params) {
218
8
            st = exec_plans(exec_env, _ctx->multi_table_put_result.pipeline_params);
219
8
        } else {
220
0
            return Status::Aborted("too many or too few params are set in multi_table_put_result.");
221
0
        }
222
8
        if (!st.ok()) {
223
0
            return st;
224
0
        }
225
8
    }
226
5
    _unplanned_tables.clear();
227
5
    return st;
228
6
}
229
230
Status MultiTablePipe::exec_plans(ExecEnv* exec_env,
231
8
                                  const std::vector<TPipelineFragmentParams>& params) {
232
    // put unplanned pipes into planned pipes and clear unplanned pipes
233
14
    for (auto& pair : _unplanned_tables) {
234
14
        _ctx->table_list.push_back(pair.first);
235
14
        _planned_tables.emplace(pair.first, pair.second);
236
14
    }
237
8
    LOG(INFO) << fmt::format("{} tables plan complete, planned table cnt={}, returned plan cnt={}",
238
8
                             _unplanned_tables.size(), _planned_tables.size(), params.size())
239
8
              << ", ctx: " << _ctx->brief();
240
241
8
    for (auto& plan : params) {
242
8
        DBUG_EXECUTE_IF("MultiTablePipe.exec_plans.failed",
243
8
                        { return Status::Aborted("MultiTablePipe.exec_plans.failed"); });
244
8
        if (!plan.__isset.table_name ||
245
8
            _unplanned_tables.find(plan.table_name) == _unplanned_tables.end()) {
246
0
            return Status::Aborted("Missing vital param: table_name");
247
0
        }
248
249
8
        _inflight_cnt++;
250
8
        TPipelineFragmentParamsList mocked;
251
8
        RETURN_IF_ERROR(exec_env->fragment_mgr()->exec_plan_fragment(
252
8
                plan, QuerySource::ROUTINE_LOAD,
253
8
                [this, plan](RuntimeState* state, Status* status) {
254
8
                    DCHECK(state);
255
8
                    auto pair = _planned_tables.find(plan.table_name);
256
8
                    if (pair == _planned_tables.end()) {
257
8
                        LOG(WARNING) << "failed to get ctx, table: " << plan.table_name;
258
8
                    } else {
259
8
                        doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(
260
8
                                pair->second->id);
261
8
                    }
262
263
8
                    {
264
8
                        std::lock_guard<std::mutex> l(_tablet_commit_infos_lock);
265
8
                        auto commit_infos = state->tablet_commit_infos();
266
8
                        _tablet_commit_infos.insert(_tablet_commit_infos.end(),
267
8
                                                    commit_infos.begin(), commit_infos.end());
268
8
                    }
269
8
                    _number_total_rows += state->num_rows_load_total();
270
8
                    _number_loaded_rows += state->num_rows_load_success();
271
8
                    _number_filtered_rows += state->num_rows_load_filtered();
272
8
                    _number_unselected_rows += state->num_rows_load_unselected();
273
274
                    // if any of the plan fragment exec failed, set the status to the first failed plan
275
8
                    {
276
8
                        std::lock_guard<std::mutex> l(_callback_lock);
277
8
                        if (!state->get_error_log_file_path().empty()) {
278
8
                            _ctx->error_url =
279
8
                                    to_load_error_http_path(state->get_error_log_file_path());
280
8
                        }
281
8
                        if (!state->get_first_error_msg().empty()) {
282
8
                            _ctx->first_error_msg = state->get_first_error_msg();
283
8
                        }
284
8
                        if (!status->ok()) {
285
8
                            LOG(WARNING) << "plan fragment exec failed. errmsg=" << *status
286
8
                                         << _ctx->brief();
287
8
                            _status = *status;
288
8
                        }
289
8
                    }
290
291
8
                    auto inflight_cnt = _inflight_cnt.fetch_sub(1);
292
8
                    if (inflight_cnt == 1 && is_consume_finished()) {
293
8
                        _handle_consumer_finished();
294
8
                    }
295
8
                },
296
8
                mocked));
297
8
    }
298
299
8
    return Status::OK();
300
8
}
301
302
#else
303
Status MultiTablePipe::request_and_exec_plans() {
304
    // put unplanned pipes into planned pipes
305
    for (auto& pipe : _unplanned_tables) {
306
        _planned_tables.emplace(pipe.first, pipe.second);
307
    }
308
    LOG(INFO) << fmt::format("{} tables plan complete, planned table cnt={}",
309
                             _unplanned_tables.size(), _planned_tables.size());
310
    _unplanned_tables.clear();
311
    return Status::OK();
312
}
313
314
Status MultiTablePipe::exec_plans(ExecEnv* exec_env,
315
                                  const std::vector<TPipelineFragmentParams>& params) {
316
    return Status::OK();
317
}
318
319
#endif
320
321
6
void MultiTablePipe::_handle_consumer_finished() {
322
6
    _ctx->number_total_rows = _number_total_rows;
323
6
    _ctx->number_loaded_rows = _number_loaded_rows;
324
6
    _ctx->number_filtered_rows = _number_filtered_rows;
325
6
    _ctx->number_unselected_rows = _number_unselected_rows;
326
6
    _ctx->commit_infos = _tablet_commit_infos;
327
328
    // remove ctx to avoid memory leak.
329
8
    for (const auto& pair : _planned_tables) {
330
8
        if (pair.second) {
331
8
            doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(pair.second->id);
332
8
        }
333
8
    }
334
6
    for (const auto& pair : _unplanned_tables) {
335
1
        if (pair.second) {
336
1
            doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(pair.second->id);
337
1
        }
338
1
    }
339
340
    LOG(INFO) << "all plan for multi-table load complete. number_total_rows="
341
6
              << _ctx->number_total_rows << " number_loaded_rows=" << _ctx->number_loaded_rows
342
6
              << " number_filtered_rows=" << _ctx->number_filtered_rows
343
6
              << " number_unselected_rows=" << _ctx->number_unselected_rows
344
6
              << ", ctx: " << _ctx->brief();
345
6
    _ctx->load_status_promise.set_value(_status); // when all done, finish the routine load task
346
6
}
347
348
} // namespace io
349
} // namespace doris