Coverage Report

Created: 2026-03-12 17:07

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