Coverage Report

Created: 2026-03-12 14:02

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
0
Status MultiTablePipe::append_with_line_delimiter(const char* data, size_t size) {
44
0
    const std::string& table = parse_dst_table(data, size);
45
0
    if (table.empty()) {
46
0
        return Status::InternalError("table name is empty");
47
0
    }
48
0
    size_t prefix_len = table.length() + 1;
49
0
    AppendFunc cb = &KafkaConsumerPipe::append_with_line_delimiter;
50
0
    return dispatch(table, data + prefix_len, size - prefix_len, cb);
51
0
}
52
53
8
Status MultiTablePipe::append_json(const char* data, size_t size) {
54
8
    const std::string& table = parse_dst_table(data, size);
55
8
    if (table.empty()) {
56
0
        return Status::InternalError("table name is empty");
57
0
    }
58
8
    size_t prefix_len = table.length() + 1;
59
8
    AppendFunc cb = &KafkaConsumerPipe::append_json;
60
8
    return dispatch(table, data + prefix_len, size - prefix_len, cb);
61
8
}
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
8
static std::string_view get_first_part(const char* dat, char delimiter) {
70
8
    const char* delimiterPos = std::strchr(dat, delimiter);
71
72
8
    if (delimiterPos != nullptr) {
73
8
        std::ptrdiff_t length = delimiterPos - dat;
74
8
        return std::string_view(dat, length);
75
8
    } else {
76
0
        return std::string_view(dat);
77
0
    }
78
8
}
79
80
0
Status MultiTablePipe::finish() {
81
0
    for (auto& pair : _planned_tables) {
82
0
        RETURN_IF_ERROR(pair.second->pipe->finish());
83
0
    }
84
0
    return Status::OK();
85
0
}
86
87
0
void MultiTablePipe::cancel(const std::string& reason) {
88
0
    for (auto& pair : _planned_tables) {
89
0
        pair.second->pipe->cancel(reason);
90
0
    }
91
0
}
92
93
8
std::string MultiTablePipe::parse_dst_table(const char* data, size_t size) {
94
8
    return std::string(get_first_part(data, '|'));
95
8
}
96
97
Status MultiTablePipe::dispatch(const std::string& table, const char* data, size_t size,
98
0
                                AppendFunc cb) {
99
0
    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
0
    KafkaConsumerPipePtr pipe = nullptr;
104
0
    auto iter = _planned_tables.find(table);
105
0
    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
0
    } else {
110
0
        iter = _unplanned_tables.find(table);
111
0
        if (iter == _unplanned_tables.end()) {
112
0
            std::shared_ptr<StreamLoadContext> ctx =
113
0
                    std::make_shared<StreamLoadContext>(doris::ExecEnv::GetInstance());
114
0
            ctx->id = UniqueId::gen_uid();
115
0
            pipe = std::make_shared<io::KafkaConsumerPipe>();
116
0
            ctx->pipe = pipe;
117
0
#ifndef BE_TEST
118
0
            RETURN_NOT_OK_STATUS_WITH_WARN(
119
0
                    doris::ExecEnv::GetInstance()->new_load_stream_mgr()->put(ctx->id, ctx),
120
0
                    "put stream load ctx error");
121
0
#endif
122
0
            _unplanned_tables.emplace(table, ctx);
123
0
            LOG(INFO) << "create new unplanned table ctx, table: " << table
124
0
                      << "load id: " << ctx->id << ", txn id: " << _ctx->txn_id;
125
0
        } 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
0
        ++_unplanned_row_cnt;
134
0
        auto pipe_current_capacity = pipe->current_capacity();
135
0
        auto pipe_max_capacity = pipe->max_capacity();
136
0
        if (_unplanned_row_cnt >= _row_threshold ||
137
0
            _unplanned_tables.size() >= _wait_tables_threshold ||
138
0
            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
0
        RETURN_NOT_OK_STATUS_WITH_WARN((pipe.get()->*cb)(data, size),
156
0
                                       "append failed in unplanned kafka pipe");
157
0
    }
158
159
0
    return Status::OK();
160
0
}
161
162
#ifndef BE_TEST
163
0
Status MultiTablePipe::request_and_exec_plans() {
164
0
    if (_unplanned_tables.empty()) {
165
0
        return Status::OK();
166
0
    }
167
168
0
    fmt::memory_buffer log_buffer;
169
0
    log_buffer.clear();
170
0
    fmt::format_to(log_buffer, "request plans for {} tables: [ ", _unplanned_tables.size());
171
0
    for (auto& pair : _unplanned_tables) {
172
0
        fmt::format_to(log_buffer, "{} ", pair.first);
173
0
    }
174
0
    fmt::format_to(log_buffer, "]");
175
0
    LOG(INFO) << fmt::to_string(log_buffer);
176
177
0
    Status st;
178
0
    for (auto& pair : _unplanned_tables) {
179
0
        TStreamLoadPutRequest request;
180
0
        set_request_auth(&request, _ctx->auth);
181
0
        std::vector<std::string> tables;
182
0
        tables.push_back(pair.first);
183
0
        request.db = _ctx->db;
184
0
        request.table_names = tables;
185
0
        request.__isset.table_names = true;
186
0
        request.txnId = _ctx->txn_id;
187
0
        request.formatType = _ctx->format;
188
0
        request.__set_compress_type(_ctx->compress_type);
189
0
        request.__set_header_type(_ctx->header_type);
190
0
        request.__set_loadId((pair.second->id).to_thrift());
191
0
        request.fileType = TFileType::FILE_STREAM;
192
0
        request.__set_thrift_rpc_timeout_ms(config::thrift_rpc_timeout_ms);
193
0
        request.__set_memtable_on_sink_node(_ctx->memtable_on_sink_node);
194
0
        request.__set_user(_ctx->qualified_user);
195
0
        request.__set_cloud_cluster(_ctx->cloud_cluster);
196
0
        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
0
        ExecEnv* exec_env = doris::ExecEnv::GetInstance();
201
0
        TNetworkAddress master_addr = exec_env->cluster_info()->master_fe_addr;
202
0
        int64_t stream_load_put_start_time = MonotonicNanos();
203
0
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
204
0
                master_addr.hostname, master_addr.port,
205
0
                [&request, this](FrontendServiceConnection& client) {
206
0
                    client->streamLoadMultiTablePut(_ctx->multi_table_put_result, request);
207
0
                }));
208
0
        _ctx->stream_load_put_cost_nanos = MonotonicNanos() - stream_load_put_start_time;
209
210
0
        Status plan_status(Status::create(_ctx->multi_table_put_result.status));
211
0
        if (!plan_status.ok()) {
212
0
            LOG(WARNING) << "plan streaming load failed. errmsg=" << plan_status << _ctx->brief();
213
0
            return plan_status;
214
0
        }
215
216
0
        if (_ctx->multi_table_put_result.__isset.pipeline_params) {
217
0
            st = exec_plans(exec_env, _ctx->multi_table_put_result.pipeline_params);
218
0
        } else {
219
0
            return Status::Aborted("too many or too few params are set in multi_table_put_result.");
220
0
        }
221
0
        if (!st.ok()) {
222
0
            return st;
223
0
        }
224
0
    }
225
0
    _unplanned_tables.clear();
226
0
    return st;
227
0
}
228
229
Status MultiTablePipe::exec_plans(ExecEnv* exec_env,
230
0
                                  const std::vector<TPipelineFragmentParams>& params) {
231
    // put unplanned pipes into planned pipes and clear unplanned pipes
232
0
    for (auto& pair : _unplanned_tables) {
233
0
        _ctx->table_list.push_back(pair.first);
234
0
        _planned_tables.emplace(pair.first, pair.second);
235
0
    }
236
0
    LOG(INFO) << fmt::format("{} tables plan complete, planned table cnt={}, returned plan cnt={}",
237
0
                             _unplanned_tables.size(), _planned_tables.size(), params.size())
238
0
              << ", ctx: " << _ctx->brief();
239
240
0
    for (auto& plan : params) {
241
0
        DBUG_EXECUTE_IF("MultiTablePipe.exec_plans.failed",
242
0
                        { return Status::Aborted("MultiTablePipe.exec_plans.failed"); });
243
0
        if (!plan.__isset.table_name ||
244
0
            _unplanned_tables.find(plan.table_name) == _unplanned_tables.end()) {
245
0
            return Status::Aborted("Missing vital param: table_name");
246
0
        }
247
248
0
        _inflight_cnt++;
249
0
        TPipelineFragmentParamsList mocked;
250
0
        RETURN_IF_ERROR(exec_env->fragment_mgr()->exec_plan_fragment(
251
0
                plan, QuerySource::ROUTINE_LOAD,
252
0
                [this, plan](RuntimeState* state, Status* status) {
253
0
                    DCHECK(state);
254
0
                    auto pair = _planned_tables.find(plan.table_name);
255
0
                    if (pair == _planned_tables.end()) {
256
0
                        LOG(WARNING) << "failed to get ctx, table: " << plan.table_name;
257
0
                    } else {
258
0
                        doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(
259
0
                                pair->second->id);
260
0
                    }
261
262
0
                    {
263
0
                        std::lock_guard<std::mutex> l(_tablet_commit_infos_lock);
264
0
                        auto commit_infos = state->tablet_commit_infos();
265
0
                        _tablet_commit_infos.insert(_tablet_commit_infos.end(),
266
0
                                                    commit_infos.begin(), commit_infos.end());
267
0
                    }
268
0
                    _number_total_rows += state->num_rows_load_total();
269
0
                    _number_loaded_rows += state->num_rows_load_success();
270
0
                    _number_filtered_rows += state->num_rows_load_filtered();
271
0
                    _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
0
                    {
275
0
                        std::lock_guard<std::mutex> l(_callback_lock);
276
0
                        if (!state->get_error_log_file_path().empty()) {
277
0
                            _ctx->error_url =
278
0
                                    to_load_error_http_path(state->get_error_log_file_path());
279
0
                        }
280
0
                        if (!state->get_first_error_msg().empty()) {
281
0
                            _ctx->first_error_msg = state->get_first_error_msg();
282
0
                        }
283
0
                        if (!status->ok()) {
284
0
                            LOG(WARNING) << "plan fragment exec failed. errmsg=" << *status
285
0
                                         << _ctx->brief();
286
0
                            _status = *status;
287
0
                        }
288
0
                    }
289
290
0
                    auto inflight_cnt = _inflight_cnt.fetch_sub(1);
291
0
                    if (inflight_cnt == 1 && is_consume_finished()) {
292
0
                        _handle_consumer_finished();
293
0
                    }
294
0
                },
295
0
                mocked));
296
0
    }
297
298
0
    return Status::OK();
299
0
}
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
0
void MultiTablePipe::_handle_consumer_finished() {
321
0
    _ctx->number_total_rows = _number_total_rows;
322
0
    _ctx->number_loaded_rows = _number_loaded_rows;
323
0
    _ctx->number_filtered_rows = _number_filtered_rows;
324
0
    _ctx->number_unselected_rows = _number_unselected_rows;
325
0
    _ctx->commit_infos = _tablet_commit_infos;
326
327
    // remove ctx to avoid memory leak.
328
0
    for (const auto& pair : _planned_tables) {
329
0
        if (pair.second) {
330
0
            doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(pair.second->id);
331
0
        }
332
0
    }
333
0
    for (const auto& pair : _unplanned_tables) {
334
0
        if (pair.second) {
335
0
            doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(pair.second->id);
336
0
        }
337
0
    }
338
339
    LOG(INFO) << "all plan for multi-table load complete. number_total_rows="
340
0
              << _ctx->number_total_rows << " number_loaded_rows=" << _ctx->number_loaded_rows
341
0
              << " number_filtered_rows=" << _ctx->number_filtered_rows
342
0
              << " number_unselected_rows=" << _ctx->number_unselected_rows
343
0
              << ", ctx: " << _ctx->brief();
344
0
    _ctx->load_status_promise.set_value(_status); // when all done, finish the routine load task
345
0
}
346
347
} // namespace io
348
} // namespace doris