Coverage Report

Created: 2026-03-15 20:53

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
8
                                AppendFunc cb) {
99
8
    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
8
    KafkaConsumerPipePtr pipe = nullptr;
104
8
    auto iter = _planned_tables.find(table);
105
8
    if (iter != _planned_tables.end()) {
106
2
        pipe = std::static_pointer_cast<io::KafkaConsumerPipe>(iter->second->pipe);
107
2
        RETURN_NOT_OK_STATUS_WITH_WARN((pipe.get()->*cb)(data, size),
108
2
                                       "append failed in planned kafka pipe");
109
6
    } else {
110
6
        iter = _unplanned_tables.find(table);
111
6
        if (iter == _unplanned_tables.end()) {
112
3
            std::shared_ptr<StreamLoadContext> ctx =
113
3
                    std::make_shared<StreamLoadContext>(doris::ExecEnv::GetInstance());
114
3
            ctx->id = UniqueId::gen_uid();
115
3
            pipe = std::make_shared<io::KafkaConsumerPipe>();
116
3
            ctx->pipe = pipe;
117
#ifndef BE_TEST
118
            RETURN_NOT_OK_STATUS_WITH_WARN(
119
                    doris::ExecEnv::GetInstance()->new_load_stream_mgr()->put(ctx->id, ctx),
120
                    "put stream load ctx error");
121
#endif
122
3
            _unplanned_tables.emplace(table, ctx);
123
3
            LOG(INFO) << "create new unplanned table ctx, table: " << table
124
3
                      << "load id: " << ctx->id << ", txn id: " << _ctx->txn_id;
125
3
        } else {
126
3
            pipe = std::static_pointer_cast<io::KafkaConsumerPipe>(iter->second->pipe);
127
3
        }
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
6
        ++_unplanned_row_cnt;
134
6
        auto pipe_current_capacity = pipe->current_capacity();
135
6
        auto pipe_max_capacity = pipe->max_capacity();
136
6
        if (_unplanned_row_cnt >= _row_threshold ||
137
6
            _unplanned_tables.size() >= _wait_tables_threshold ||
138
6
            pipe_current_capacity + size > pipe_max_capacity) {
139
2
            LOG(INFO) << fmt::format(
140
2
                                 "unplanned row cnt={} reach row_threshold={} or "
141
2
                                 "wait_plan_table_threshold={}, or the sum of "
142
2
                                 "pipe_current_capacity {} "
143
2
                                 "and size {} is greater than pipe_max_capacity {}, "
144
2
                                 "plan them",
145
2
                                 _unplanned_row_cnt, _row_threshold, _wait_tables_threshold,
146
2
                                 pipe_current_capacity, size, pipe_max_capacity)
147
2
                      << ", ctx: " << _ctx->brief();
148
2
            Status st = request_and_exec_plans();
149
2
            _unplanned_row_cnt = 0;
150
2
            if (!st.ok()) {
151
0
                return st;
152
0
            }
153
2
        }
154
155
6
        RETURN_NOT_OK_STATUS_WITH_WARN((pipe.get()->*cb)(data, size),
156
6
                                       "append failed in unplanned kafka pipe");
157
6
    }
158
159
8
    return Status::OK();
160
8
}
161
162
#ifndef BE_TEST
163
Status MultiTablePipe::request_and_exec_plans() {
164
    if (_unplanned_tables.empty()) {
165
        return Status::OK();
166
    }
167
168
    fmt::memory_buffer log_buffer;
169
    log_buffer.clear();
170
    fmt::format_to(log_buffer, "request plans for {} tables: [ ", _unplanned_tables.size());
171
    for (auto& pair : _unplanned_tables) {
172
        fmt::format_to(log_buffer, "{} ", pair.first);
173
    }
174
    fmt::format_to(log_buffer, "]");
175
    LOG(INFO) << fmt::to_string(log_buffer);
176
177
    Status st;
178
    for (auto& pair : _unplanned_tables) {
179
        TStreamLoadPutRequest request;
180
        set_request_auth(&request, _ctx->auth);
181
        std::vector<std::string> tables;
182
        tables.push_back(pair.first);
183
        request.db = _ctx->db;
184
        request.table_names = tables;
185
        request.__isset.table_names = true;
186
        request.txnId = _ctx->txn_id;
187
        request.formatType = _ctx->format;
188
        request.__set_compress_type(_ctx->compress_type);
189
        request.__set_header_type(_ctx->header_type);
190
        request.__set_loadId((pair.second->id).to_thrift());
191
        request.fileType = TFileType::FILE_STREAM;
192
        request.__set_thrift_rpc_timeout_ms(config::thrift_rpc_timeout_ms);
193
        request.__set_memtable_on_sink_node(_ctx->memtable_on_sink_node);
194
        request.__set_user(_ctx->qualified_user);
195
        request.__set_cloud_cluster(_ctx->cloud_cluster);
196
        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
        ExecEnv* exec_env = doris::ExecEnv::GetInstance();
201
        TNetworkAddress master_addr = exec_env->cluster_info()->master_fe_addr;
202
        int64_t stream_load_put_start_time = MonotonicNanos();
203
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
204
                master_addr.hostname, master_addr.port,
205
                [&request, this](FrontendServiceConnection& client) {
206
                    client->streamLoadMultiTablePut(_ctx->multi_table_put_result, request);
207
                }));
208
        _ctx->stream_load_put_cost_nanos = MonotonicNanos() - stream_load_put_start_time;
209
210
        Status plan_status(Status::create(_ctx->multi_table_put_result.status));
211
        if (!plan_status.ok()) {
212
            LOG(WARNING) << "plan streaming load failed. errmsg=" << plan_status << _ctx->brief();
213
            return plan_status;
214
        }
215
216
        if (_ctx->multi_table_put_result.__isset.pipeline_params) {
217
            st = exec_plans(exec_env, _ctx->multi_table_put_result.pipeline_params);
218
        } else {
219
            return Status::Aborted("too many or too few params are set in multi_table_put_result.");
220
        }
221
        if (!st.ok()) {
222
            return st;
223
        }
224
    }
225
    _unplanned_tables.clear();
226
    return st;
227
}
228
229
Status MultiTablePipe::exec_plans(ExecEnv* exec_env,
230
                                  const std::vector<TPipelineFragmentParams>& params) {
231
    // put unplanned pipes into planned pipes and clear unplanned pipes
232
    for (auto& pair : _unplanned_tables) {
233
        _ctx->table_list.push_back(pair.first);
234
        _planned_tables.emplace(pair.first, pair.second);
235
    }
236
    LOG(INFO) << fmt::format("{} tables plan complete, planned table cnt={}, returned plan cnt={}",
237
                             _unplanned_tables.size(), _planned_tables.size(), params.size())
238
              << ", ctx: " << _ctx->brief();
239
240
    for (auto& plan : params) {
241
        DBUG_EXECUTE_IF("MultiTablePipe.exec_plans.failed",
242
                        { return Status::Aborted("MultiTablePipe.exec_plans.failed"); });
243
        if (!plan.__isset.table_name ||
244
            _unplanned_tables.find(plan.table_name) == _unplanned_tables.end()) {
245
            return Status::Aborted("Missing vital param: table_name");
246
        }
247
248
        _inflight_cnt++;
249
        TPipelineFragmentParamsList mocked;
250
        RETURN_IF_ERROR(exec_env->fragment_mgr()->exec_plan_fragment(
251
                plan, QuerySource::ROUTINE_LOAD,
252
                [this, plan](RuntimeState* state, Status* status) {
253
                    DCHECK(state);
254
                    auto pair = _planned_tables.find(plan.table_name);
255
                    if (pair == _planned_tables.end()) {
256
                        LOG(WARNING) << "failed to get ctx, table: " << plan.table_name;
257
                    } else {
258
                        doris::ExecEnv::GetInstance()->new_load_stream_mgr()->remove(
259
                                pair->second->id);
260
                    }
261
262
                    {
263
                        std::lock_guard<std::mutex> l(_tablet_commit_infos_lock);
264
                        auto commit_infos = state->tablet_commit_infos();
265
                        _tablet_commit_infos.insert(_tablet_commit_infos.end(),
266
                                                    commit_infos.begin(), commit_infos.end());
267
                    }
268
                    _number_total_rows += state->num_rows_load_total();
269
                    _number_loaded_rows += state->num_rows_load_success();
270
                    _number_filtered_rows += state->num_rows_load_filtered();
271
                    _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
                    {
275
                        std::lock_guard<std::mutex> l(_callback_lock);
276
                        if (!state->get_error_log_file_path().empty()) {
277
                            _ctx->error_url =
278
                                    to_load_error_http_path(state->get_error_log_file_path());
279
                        }
280
                        if (!state->get_first_error_msg().empty()) {
281
                            _ctx->first_error_msg = state->get_first_error_msg();
282
                        }
283
                        if (!status->ok()) {
284
                            LOG(WARNING) << "plan fragment exec failed. errmsg=" << *status
285
                                         << _ctx->brief();
286
                            _status = *status;
287
                        }
288
                    }
289
290
                    auto inflight_cnt = _inflight_cnt.fetch_sub(1);
291
                    if (inflight_cnt == 1 && is_consume_finished()) {
292
                        _handle_consumer_finished();
293
                    }
294
                },
295
                mocked));
296
    }
297
298
    return Status::OK();
299
}
300
301
#else
302
2
Status MultiTablePipe::request_and_exec_plans() {
303
    // put unplanned pipes into planned pipes
304
3
    for (auto& pipe : _unplanned_tables) {
305
3
        _planned_tables.emplace(pipe.first, pipe.second);
306
3
    }
307
2
    LOG(INFO) << fmt::format("{} tables plan complete, planned table cnt={}",
308
2
                             _unplanned_tables.size(), _planned_tables.size());
309
2
    _unplanned_tables.clear();
310
2
    return Status::OK();
311
2
}
312
313
Status MultiTablePipe::exec_plans(ExecEnv* exec_env,
314
0
                                  const std::vector<TPipelineFragmentParams>& params) {
315
0
    return Status::OK();
316
0
}
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