Coverage Report

Created: 2026-07-23 16:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/group_commit/wal/wal_table.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 "load/group_commit/wal/wal_table.h"
19
20
#include <absl/strings/str_split.h>
21
#include <thrift/protocol/TDebugProtocol.h>
22
23
#include "io/fs/local_file_system.h"
24
#include "io/fs/stream_load_pipe.h"
25
#include "load/group_commit/wal/wal_manager.h"
26
#include "runtime/fragment_mgr.h"
27
#include "service/http/action/http_stream.h"
28
#include "service/http/action/stream_load.h"
29
#include "service/http/ev_http_server.h"
30
#include "service/http/http_common.h"
31
#include "service/http/http_headers.h"
32
#include "service/http/utils.h"
33
#include "util/client_cache.h"
34
#include "util/path_util.h"
35
#include "util/thrift_rpc_helper.h"
36
37
namespace doris {
38
39
bvar::Adder<uint64_t> wal_fail("group_commit_wal_fail");
40
41
WalTable::WalTable(ExecEnv* exec_env, int64_t db_id, int64_t table_id)
42
1
        : _exec_env(exec_env), _db_id(db_id), _table_id(table_id) {
43
1
    _http_stream_action = std::make_shared<HttpStreamAction>(exec_env);
44
1
}
45
1
WalTable::~WalTable() {}
46
47
1
void WalTable::add_wal(int64_t wal_id, std::string wal) {
48
1
    std::lock_guard<std::mutex> lock(_replay_wal_lock);
49
1
    LOG(INFO) << "add replay wal=" << wal;
50
1
    auto wal_info = std::make_shared<WalInfo>(wal_id, wal, 0, UnixMillis());
51
1
    _replay_wal_map.emplace(wal, wal_info);
52
1
}
53
54
2
void WalTable::_pick_relay_wals() {
55
2
    std::lock_guard<std::mutex> lock(_replay_wal_lock);
56
2
    std::vector<std::string> need_replay_wals;
57
2
    std::vector<std::string> need_erase_wals;
58
2
    for (const auto& [wal_path, wal_info] : _replay_wal_map) {
59
2
        if (config::group_commit_wait_replay_wal_finish &&
60
2
            wal_info->get_retry_num() >= config::group_commit_replay_wal_retry_num) {
61
0
            LOG(WARNING) << "failed to replay wal=" << wal_path << " after retry "
62
0
                         << wal_info->get_retry_num() << " times";
63
0
            [[maybe_unused]] auto st = _exec_env->wal_mgr()->rename_to_tmp_path(
64
0
                    wal_path, _table_id, wal_info->get_wal_id());
65
0
            auto notify_st = _exec_env->wal_mgr()->notify_relay_wal(wal_info->get_wal_id());
66
0
            if (!notify_st.ok()) {
67
0
                LOG(WARNING) << "notify wal " << wal_info->get_wal_id() << " fail";
68
0
            }
69
0
            need_erase_wals.push_back(wal_path);
70
0
            continue;
71
0
        }
72
2
        if (_need_replay(wal_info)) {
73
2
            need_replay_wals.push_back(wal_path);
74
2
        }
75
2
    }
76
2
    for (const auto& wal : need_erase_wals) {
77
0
        _replay_wal_map.erase(wal);
78
0
    }
79
2
    std::sort(need_replay_wals.begin(), need_replay_wals.end());
80
2
    for (const auto& wal : need_replay_wals) {
81
2
        _replaying_queue.emplace_back(_replay_wal_map[wal]);
82
2
        _replay_wal_map.erase(wal);
83
2
    }
84
2
}
85
86
2
Status WalTable::_relay_wal_one_by_one() {
87
2
    std::vector<std::shared_ptr<WalInfo>> need_retry_wals;
88
2
    for (auto wal_info : _replaying_queue) {
89
2
        wal_info->add_retry_num();
90
2
        Status st;
91
2
        int64_t file_size = 0;
92
2
        std::filesystem::path file_path(wal_info->get_wal_path());
93
2
        if (!std::filesystem::exists(file_path)) {
94
0
            st = Status::InternalError("wal file {} does not exist", wal_info->get_wal_path());
95
2
        } else {
96
2
            file_size = std::filesystem::file_size(file_path);
97
2
            st = _replay_wal_internal(wal_info->get_wal_path());
98
2
        }
99
2
        auto msg = st.msg();
100
2
        if (st.ok() || st.is<ErrorCode::PUBLISH_TIMEOUT>() || st.is<ErrorCode::NOT_FOUND>() ||
101
2
            st.is<ErrorCode::DATA_QUALITY_ERROR>() ||
102
2
            (msg.find("has already been used") != msg.npos &&
103
1
             (msg.find("COMMITTED") != msg.npos || msg.find("VISIBLE") != msg.npos))) {
104
1
            LOG(INFO) << "succeed to replay wal=" << wal_info->get_wal_path()
105
1
                      << ", st=" << st.to_string() << ", file size=" << file_size;
106
            // delete wal
107
1
            WARN_IF_ERROR(_exec_env->wal_mgr()->delete_wal(_table_id, wal_info->get_wal_id()),
108
1
                          "failed to delete wal=" + wal_info->get_wal_path());
109
1
            if (config::group_commit_wait_replay_wal_finish) {
110
0
                RETURN_IF_ERROR(_exec_env->wal_mgr()->notify_relay_wal(wal_info->get_wal_id()));
111
0
            }
112
1
        } else {
113
1
            doris::wal_fail << 1;
114
1
            LOG(WARNING) << "failed to replay wal=" << wal_info->get_wal_path()
115
1
                         << ", st=" << st.to_string();
116
1
            {
117
1
                std::lock_guard<std::mutex> lock(_replay_wal_lock);
118
1
                _last_replay_wal_failed_reason =
119
1
                        "failed to replay wal=" + wal_info->get_wal_path() +
120
1
                        ", st=" + st.to_string().substr(0, 100);
121
1
            }
122
1
            need_retry_wals.push_back(wal_info);
123
1
        }
124
2
    }
125
2
    {
126
2
        std::lock_guard<std::mutex> lock(_replay_wal_lock);
127
2
        _replaying_queue.clear();
128
2
        for (auto retry_wal_info : need_retry_wals) {
129
1
            _replay_wal_map.emplace(retry_wal_info->get_wal_path(), retry_wal_info);
130
1
        }
131
2
        if (_replay_wal_map.empty()) {
132
1
            _last_replay_wal_failed_reason.clear();
133
1
        }
134
2
    }
135
2
    return Status::OK();
136
2
}
137
138
2
Status WalTable::replay_wals() {
139
2
    {
140
2
        std::lock_guard<std::mutex> lock(_replay_wal_lock);
141
2
        if (_replay_wal_map.empty()) {
142
0
            LOG(INFO) << "_replay_wal_map is empty, skip relaying for table_id=" << _table_id;
143
0
            return Status::OK();
144
0
        }
145
2
        if (!_replaying_queue.empty()) {
146
0
            LOG(INFO) << "_replaying_queue is not empty, skip relaying for table_id=" << _table_id;
147
0
            return Status::OK();
148
0
        }
149
2
    }
150
2
    VLOG_DEBUG << "Start replay wals for db=" << _db_id << ", table=" << _table_id
151
0
               << ", wal size=" << _replay_wal_map.size();
152
2
    _pick_relay_wals();
153
2
    RETURN_IF_ERROR(_relay_wal_one_by_one());
154
2
    return Status::OK();
155
2
}
156
157
2
bool WalTable::_need_replay(std::shared_ptr<WalInfo> wal_info) {
158
2
    if (config::group_commit_wait_replay_wal_finish) {
159
0
        return true;
160
0
    }
161
#ifndef BE_TEST
162
    int64_t replay_interval = 0;
163
    if (wal_info->get_retry_num() >= config::group_commit_replay_wal_retry_num) {
164
        replay_interval =
165
                int64_t(pow(2, config::group_commit_replay_wal_retry_num) *
166
                                config::group_commit_replay_wal_retry_interval_seconds * 1000 +
167
                        (wal_info->get_retry_num() - config::group_commit_replay_wal_retry_num) *
168
                                config::group_commit_replay_wal_retry_interval_max_seconds * 1000);
169
    } else {
170
        replay_interval = int64_t(pow(2, wal_info->get_retry_num()) *
171
                                  config::group_commit_replay_wal_retry_interval_seconds * 1000);
172
    }
173
    return UnixMillis() - wal_info->get_start_time_ms() >= replay_interval;
174
#else
175
2
    return true;
176
2
#endif
177
2
}
178
179
0
Status WalTable::_try_abort_txn(int64_t db_id, std::string& label) {
180
0
    TLoadTxnRollbackRequest request;
181
    // this is a fake, fe not check it now
182
    // should be removed in 3.1, use token instead
183
0
    request.__set_auth_code(0);
184
0
    request.__set_token(_exec_env->cluster_info()->curr_auth_token);
185
0
    request.__set_db_id(db_id);
186
0
    request.__set_label(label);
187
0
    request.__set_reason("relay wal with label " + label);
188
0
    TLoadTxnRollbackResult result;
189
0
    TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
190
0
    auto st = ThriftRpcHelper::rpc<FrontendServiceClient>(
191
0
            master_addr.hostname, master_addr.port,
192
0
            [&request, &result](FrontendServiceConnection& client) {
193
0
                client->loadTxnRollback(result, request);
194
0
            });
195
0
    if (st.ok()) {
196
0
        auto result_status = Status::create<false>(result.status);
197
0
        LOG(INFO) << "abort label " << label << ", result_status:" << result_status;
198
0
        return result_status;
199
0
    } else {
200
0
        LOG(WARNING) << "abort label " << label << ", rpc error:" << st;
201
0
        return st;
202
0
    }
203
0
}
204
205
2
Status WalTable::_replay_wal_internal(const std::string& wal) {
206
2
    LOG(INFO) << "start replay wal=" << wal;
207
2
    int64_t version = -1;
208
2
    int64_t backend_id = -1;
209
2
    int64_t wal_id = -1;
210
2
    std::string label = "";
211
2
    io::Path wal_path = wal;
212
2
    auto file_name = wal_path.filename().string();
213
2
    RETURN_IF_ERROR(WalManager::parse_wal_path(file_name, version, backend_id, wal_id, label));
214
#ifndef BE_TEST
215
    if (!config::group_commit_wait_replay_wal_finish) {
216
        [[maybe_unused]] auto st = _try_abort_txn(_db_id, label);
217
    }
218
#endif
219
2
    DBUG_EXECUTE_IF("WalTable.replay_wals.stop",
220
2
                    { return Status::InternalError("WalTable.replay_wals.stop"); });
221
1
    return _replay_one_wal_with_streamload(wal_id, wal, label);
222
2
}
223
224
Status WalTable::_construct_sql_str(const std::string& wal, const std::string& label,
225
0
                                    std::string& sql_str) {
226
0
    std::string columns;
227
0
    RETURN_IF_ERROR(_read_wal_header(wal, columns));
228
0
    std::vector<std::string> column_id_vector =
229
0
            absl::StrSplit(columns, ",", absl::SkipWhitespace());
230
0
    std::map<int64_t, std::string> column_info_map;
231
0
    RETURN_IF_ERROR(_get_column_info(_db_id, _table_id, column_info_map));
232
0
    std::stringstream ss_name;
233
0
    for (auto column_id_str : column_id_vector) {
234
0
        try {
235
0
            int64_t column_id = std::strtoll(column_id_str.c_str(), NULL, 10);
236
0
            auto it = column_info_map.find(column_id);
237
0
            if (it != column_info_map.end()) {
238
0
                ss_name << "`" << it->second << "`,";
239
0
                column_info_map.erase(column_id);
240
0
            }
241
0
        } catch (const std::invalid_argument& e) {
242
0
            return Status::InvalidArgument("Invalid format, {}", e.what());
243
0
        }
244
0
    }
245
0
    auto name = ss_name.str().substr(0, ss_name.str().size() - 1);
246
0
    std::stringstream ss;
247
0
    ss << "insert into doris_internal_table_id(" << _table_id << ") WITH LABEL " << label << " ("
248
0
       << name << ") select " << name << " from http_stream(\"format\" = \"wal\", \"table_id\" = \""
249
0
       << std::to_string(_table_id) << "\")";
250
0
    sql_str = ss.str().data();
251
0
    return Status::OK();
252
0
}
253
254
Status WalTable::_handle_stream_load(int64_t wal_id, const std::string& wal,
255
0
                                     const std::string& label) {
256
0
    std::string sql_str;
257
0
    RETURN_IF_ERROR(_construct_sql_str(wal, label, sql_str));
258
0
    std::shared_ptr<StreamLoadContext> ctx = std::make_shared<StreamLoadContext>(_exec_env);
259
0
    ctx->sql_str = sql_str;
260
0
    ctx->db_id = _db_id;
261
0
    ctx->table_id = _table_id;
262
0
    ctx->wal_id = wal_id;
263
0
    ctx->label = label;
264
0
    ctx->need_commit_self = false;
265
0
    ctx->auth.token = _exec_env->cluster_info()->curr_auth_token;
266
0
    ctx->auth.user = "admin";
267
0
    ctx->group_commit = false;
268
0
    ctx->load_type = TLoadType::MANUL_LOAD;
269
0
    ctx->load_src_type = TLoadSourceType::RAW;
270
0
    ctx->max_filter_ratio = 1;
271
0
    auto st = _http_stream_action->process_put(nullptr, ctx);
272
0
    DBUG_EXECUTE_IF("WalTable::_handle_stream_load.fail",
273
0
                    { st = Status::InternalError("WalTable::_handle_stream_load.fail"); });
274
0
    if (st.ok()) {
275
        // wait stream load finish
276
0
        RETURN_IF_ERROR(ctx->load_status_future.get());
277
0
        if (ctx->status.ok()) {
278
            // deprecated and should be removed in 3.1, use token instead.
279
0
            ctx->auth.auth_code = wal_id;
280
0
            st = _exec_env->stream_load_executor()->commit_txn(ctx.get());
281
0
        } else {
282
0
            st = ctx->status;
283
0
        }
284
0
    }
285
0
    if (!st.ok()) {
286
0
        _exec_env->stream_load_executor()->rollback_txn(ctx.get());
287
0
    }
288
0
    return st;
289
0
}
290
291
Status WalTable::_replay_one_wal_with_streamload(int64_t wal_id, const std::string& wal,
292
1
                                                 const std::string& label) {
293
#ifndef BE_TEST
294
    return _handle_stream_load(wal_id, wal, label);
295
#else
296
1
    return Status::OK();
297
1
#endif
298
1
}
299
300
0
void WalTable::stop() {
301
0
    do {
302
0
        {
303
0
            std::lock_guard<std::mutex> lock(_replay_wal_lock);
304
0
            if (_replay_wal_map.empty() && _replaying_queue.empty()) {
305
0
                break;
306
0
            }
307
0
            LOG(INFO) << "stopping wal_table,wait for relay wal task done, now "
308
0
                      << _replay_wal_map.size() << " wals wait to replay, "
309
0
                      << _replaying_queue.size() << " wals are replaying";
310
0
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
311
0
        }
312
0
    } while (true);
313
0
}
314
315
0
size_t WalTable::size() {
316
0
    std::lock_guard<std::mutex> lock(_replay_wal_lock);
317
0
    return _replay_wal_map.size() + _replaying_queue.size();
318
0
}
319
320
2
std::string WalTable::get_last_replay_wal_failed_reason() const {
321
2
    std::lock_guard<std::mutex> lock(_replay_wal_lock);
322
2
    return _last_replay_wal_failed_reason;
323
2
}
324
325
Status WalTable::_get_column_info(int64_t db_id, int64_t tb_id,
326
0
                                  std::map<int64_t, std::string>& column_info_map) {
327
0
    TGetColumnInfoRequest request;
328
0
    request.__set_db_id(db_id);
329
0
    request.__set_table_id(tb_id);
330
0
    TGetColumnInfoResult result;
331
0
    Status status;
332
0
    TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
333
0
    if (master_addr.hostname.empty() || master_addr.port == 0) {
334
0
        status = Status::InternalError<false>("Have not get FE Master heartbeat yet");
335
0
    } else {
336
0
        RETURN_IF_ERROR(ThriftRpcHelper::rpc<FrontendServiceClient>(
337
0
                master_addr.hostname, master_addr.port,
338
0
                [&request, &result](FrontendServiceConnection& client) {
339
0
                    client->getColumnInfo(result, request);
340
0
                }));
341
0
        status = Status::create<false>(result.status);
342
0
        if (!status.ok()) {
343
0
            return status;
344
0
        }
345
0
        std::vector<TColumnInfo> column_element = result.columns;
346
0
        for (auto column : column_element) {
347
0
            auto column_name = column.column_name;
348
0
            auto column_id = column.column_id;
349
0
            column_info_map.emplace(column_id, column_name);
350
0
        }
351
0
    }
352
0
    return status;
353
0
}
354
355
0
Status WalTable::_read_wal_header(const std::string& wal_path, std::string& columns) {
356
0
    std::shared_ptr<doris::WalFileReader> wal_reader =
357
0
            std::make_shared<doris::WalFileReader>(wal_path);
358
0
    RETURN_IF_ERROR(wal_reader->init());
359
0
    uint32_t version = 0;
360
0
    RETURN_IF_ERROR(wal_reader->read_header(version, columns));
361
0
    VLOG_DEBUG << "wal=" << wal_path << ",version=" << std::to_string(version)
362
0
               << ",columns=" << columns;
363
0
    RETURN_IF_ERROR(wal_reader->finalize());
364
0
    return Status::OK();
365
0
}
366
367
} // namespace doris