Coverage Report

Created: 2026-08-06 13:04

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