Coverage Report

Created: 2026-06-05 04:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/backend_service.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 "service/backend_service.h"
19
20
#include <absl/strings/str_split.h>
21
#include <arrow/record_batch.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/BackendService.h>
24
#include <gen_cpp/BackendService_types.h>
25
#include <gen_cpp/Data_types.h>
26
#include <gen_cpp/DorisExternalService_types.h>
27
#include <gen_cpp/FrontendService_types.h>
28
#include <gen_cpp/Metrics_types.h>
29
#include <gen_cpp/PaloInternalService_types.h>
30
#include <gen_cpp/Planner_types.h>
31
#include <gen_cpp/Status_types.h>
32
#include <gen_cpp/Types_types.h>
33
#include <sys/types.h>
34
#include <thrift/concurrency/ThreadFactory.h>
35
#include <thrift/protocol/TDebugProtocol.h>
36
#include <time.h>
37
38
#include <cstdint>
39
#include <map>
40
#include <memory>
41
#include <ostream>
42
#include <ranges>
43
#include <string>
44
#include <thread>
45
#include <utility>
46
#include <vector>
47
48
#include "absl/strings/substitute.h"
49
#include "cloud/config.h"
50
#include "common/config.h"
51
#include "common/logging.h"
52
#include "common/status.h"
53
#include "exprs/function/dictionary_factory.h"
54
#include "format/arrow/arrow_row_batch.h"
55
#include "io/fs/connectivity/storage_connectivity_tester.h"
56
#include "io/fs/local_file_system.h"
57
#include "load/routine_load/routine_load_task_executor.h"
58
#include "load/stream_load/stream_load_context.h"
59
#include "load/stream_load/stream_load_recorder.h"
60
#include "runtime/exec_env.h"
61
#include "runtime/external_scan_context_mgr.h"
62
#include "runtime/fragment_mgr.h"
63
#include "runtime/result_queue_mgr.h"
64
#include "runtime/runtime_profile.h"
65
#include "service/http/http_client.h"
66
#include "storage/olap_common.h"
67
#include "storage/olap_define.h"
68
#include "storage/rowset/beta_rowset.h"
69
#include "storage/rowset/pending_rowset_helper.h"
70
#include "storage/rowset/rowset_factory.h"
71
#include "storage/rowset/rowset_meta.h"
72
#include "storage/snapshot/snapshot_manager.h"
73
#include "storage/storage_engine.h"
74
#include "storage/tablet/tablet_manager.h"
75
#include "storage/tablet/tablet_meta.h"
76
#include "storage/txn/txn_manager.h"
77
#include "udf/python/python_env.h"
78
#include "util/defer_op.h"
79
#include "util/threadpool.h"
80
#include "util/thrift_server.h"
81
#include "util/uid_util.h"
82
#include "util/url_coding.h"
83
84
namespace apache {
85
namespace thrift {
86
class TException;
87
class TMultiplexedProcessor;
88
class TProcessor;
89
namespace transport {
90
class TTransportException;
91
} // namespace transport
92
} // namespace thrift
93
} // namespace apache
94
95
namespace doris {
96
namespace {
97
98
bvar::LatencyRecorder g_ingest_binlog_latency("doris_backend_service", "ingest_binlog");
99
100
struct IngestBinlogArg {
101
    int64_t txn_id;
102
    int64_t partition_id;
103
    int64_t local_tablet_id;
104
    TabletSharedPtr local_tablet;
105
    TIngestBinlogRequest request;
106
    TStatus* tstatus;
107
};
108
109
Status _exec_http_req(std::optional<HttpClient>& client, int retry_times, int sleep_time,
110
0
                      const std::function<Status(HttpClient*)>& callback) {
111
0
    if (client.has_value()) {
112
0
        return client->execute(retry_times, sleep_time, callback);
113
0
    } else {
114
0
        return HttpClient::execute_with_retry(retry_times, sleep_time, callback);
115
0
    }
116
0
}
117
118
Status _download_binlog_segment_file(HttpClient* client, const std::string& get_segment_file_url,
119
                                     const std::string& segment_path, uint64_t segment_file_size,
120
                                     uint64_t estimate_timeout,
121
0
                                     std::vector<std::string>& download_success_files) {
122
0
    RETURN_IF_ERROR(client->init(get_segment_file_url));
123
0
    client->set_timeout_ms(estimate_timeout * 1000);
124
0
    RETURN_IF_ERROR(client->download(segment_path));
125
0
    download_success_files.push_back(segment_path);
126
127
0
    std::string remote_file_md5;
128
0
    RETURN_IF_ERROR(client->get_content_md5(&remote_file_md5));
129
0
    LOG(INFO) << "download segment file to " << segment_path << ", remote md5: " << remote_file_md5
130
0
              << ", remote size: " << segment_file_size;
131
132
0
    std::error_code ec;
133
    // Check file length
134
0
    uint64_t local_file_size = std::filesystem::file_size(segment_path, ec);
135
0
    if (ec) {
136
0
        LOG(WARNING) << "download file error" << ec.message();
137
0
        return Status::IOError("can't retrive file_size of {}, due to {}", segment_path,
138
0
                               ec.message());
139
0
    }
140
141
0
    if (local_file_size != segment_file_size) {
142
0
        LOG(WARNING) << "download file length error"
143
0
                     << ", get_segment_file_url=" << get_segment_file_url
144
0
                     << ", file_size=" << segment_file_size
145
0
                     << ", local_file_size=" << local_file_size;
146
0
        return Status::RuntimeError("downloaded file size is not equal, local={}, remote={}",
147
0
                                    local_file_size, segment_file_size);
148
0
    }
149
150
0
    if (!remote_file_md5.empty()) { // keep compatibility
151
0
        std::string local_file_md5;
152
0
        RETURN_IF_ERROR(io::global_local_filesystem()->md5sum(segment_path, &local_file_md5));
153
0
        if (local_file_md5 != remote_file_md5) {
154
0
            LOG(WARNING) << "download file md5 error"
155
0
                         << ", get_segment_file_url=" << get_segment_file_url
156
0
                         << ", remote_file_md5=" << remote_file_md5
157
0
                         << ", local_file_md5=" << local_file_md5;
158
0
            return Status::RuntimeError("download file md5 is not equal, local={}, remote={}",
159
0
                                        local_file_md5, remote_file_md5);
160
0
        }
161
0
    }
162
163
0
    return io::global_local_filesystem()->permission(segment_path,
164
0
                                                     io::LocalFileSystem::PERMS_OWNER_RW);
165
0
}
166
167
Status _download_binlog_index_file(HttpClient* client,
168
                                   const std::string& get_segment_index_file_url,
169
                                   const std::string& local_segment_index_path,
170
                                   uint64_t segment_index_file_size, uint64_t estimate_timeout,
171
0
                                   std::vector<std::string>& download_success_files) {
172
0
    RETURN_IF_ERROR(client->init(get_segment_index_file_url));
173
0
    client->set_timeout_ms(estimate_timeout * 1000);
174
0
    RETURN_IF_ERROR(client->download(local_segment_index_path));
175
0
    download_success_files.push_back(local_segment_index_path);
176
177
0
    std::string remote_file_md5;
178
0
    RETURN_IF_ERROR(client->get_content_md5(&remote_file_md5));
179
180
0
    LOG(INFO) << "download segment index file to " << local_segment_index_path
181
0
              << ", remote md5: " << remote_file_md5
182
0
              << ", remote size: " << segment_index_file_size;
183
184
0
    std::error_code ec;
185
    // Check file length
186
0
    uint64_t local_index_file_size = std::filesystem::file_size(local_segment_index_path, ec);
187
0
    if (ec) {
188
0
        LOG(WARNING) << "download index file error" << ec.message();
189
0
        return Status::IOError("can't retrive file_size of {}, due to {}", local_segment_index_path,
190
0
                               ec.message());
191
0
    }
192
0
    if (local_index_file_size != segment_index_file_size) {
193
0
        LOG(WARNING) << "download index file length error"
194
0
                     << ", get_segment_index_file_url=" << get_segment_index_file_url
195
0
                     << ", index_file_size=" << segment_index_file_size
196
0
                     << ", local_index_file_size=" << local_index_file_size;
197
0
        return Status::RuntimeError("downloaded index file size is not equal, local={}, remote={}",
198
0
                                    local_index_file_size, segment_index_file_size);
199
0
    }
200
201
0
    if (!remote_file_md5.empty()) { // keep compatibility
202
0
        std::string local_file_md5;
203
0
        RETURN_IF_ERROR(
204
0
                io::global_local_filesystem()->md5sum(local_segment_index_path, &local_file_md5));
205
0
        if (local_file_md5 != remote_file_md5) {
206
0
            LOG(WARNING) << "download file md5 error"
207
0
                         << ", get_segment_index_file_url=" << get_segment_index_file_url
208
0
                         << ", remote_file_md5=" << remote_file_md5
209
0
                         << ", local_file_md5=" << local_file_md5;
210
0
            return Status::RuntimeError("download file md5 is not equal, local={}, remote={}",
211
0
                                        local_file_md5, remote_file_md5);
212
0
        }
213
0
    }
214
215
0
    return io::global_local_filesystem()->permission(local_segment_index_path,
216
0
                                                     io::LocalFileSystem::PERMS_OWNER_RW);
217
0
}
218
219
0
void _ingest_binlog(StorageEngine& engine, IngestBinlogArg* arg) {
220
0
    std::optional<HttpClient> client;
221
0
    if (config::enable_ingest_binlog_with_persistent_connection) {
222
        // Save the http client instance for persistent connection
223
0
        client = std::make_optional<HttpClient>();
224
0
    }
225
226
0
    auto txn_id = arg->txn_id;
227
0
    auto partition_id = arg->partition_id;
228
0
    auto local_tablet_id = arg->local_tablet_id;
229
0
    const auto& local_tablet = arg->local_tablet;
230
0
    const auto& local_tablet_uid = local_tablet->tablet_uid();
231
232
0
    std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
233
0
            MemTrackerLimiter::Type::OTHER, fmt::format("IngestBinlog#TxnId={}", txn_id));
234
0
    SCOPED_ATTACH_TASK(mem_tracker);
235
236
0
    auto& request = arg->request;
237
238
0
    MonotonicStopWatch watch(true);
239
0
    int64_t total_download_bytes = 0;
240
0
    int64_t total_download_files = 0;
241
0
    TStatus tstatus;
242
0
    std::vector<std::string> download_success_files;
243
0
    std::unordered_map<std::string_view, uint64_t> elapsed_time_map;
244
0
    Defer defer {[=, &engine, &tstatus, ingest_binlog_tstatus = arg->tstatus, &watch,
245
0
                  &total_download_bytes, &total_download_files, &elapsed_time_map]() {
246
0
        g_ingest_binlog_latency << watch.elapsed_time_microseconds();
247
0
        auto elapsed_time_ms = static_cast<int64_t>(watch.elapsed_time_milliseconds());
248
0
        double copy_rate = 0.0;
249
0
        if (elapsed_time_ms > 0) {
250
0
            copy_rate = (double)total_download_bytes / ((double)elapsed_time_ms) / 1000;
251
0
        }
252
0
        LOG(INFO) << "ingest binlog elapsed " << elapsed_time_ms << " ms, download "
253
0
                  << total_download_files << " files, total " << total_download_bytes
254
0
                  << " bytes, avg rate " << copy_rate
255
0
                  << " MB/s. result: " << apache::thrift::ThriftDebugString(tstatus);
256
0
        if (config::ingest_binlog_elapsed_threshold_ms >= 0 &&
257
0
            elapsed_time_ms > config::ingest_binlog_elapsed_threshold_ms) {
258
0
            auto elapsed_details_view =
259
0
                    elapsed_time_map | std::views::transform([](const auto& pair) {
260
0
                        return fmt::format("{}:{}", pair.first, pair.second);
261
0
                    });
262
0
            std::string elapsed_details = fmt::format("{}", fmt::join(elapsed_details_view, ", "));
263
0
            LOG(WARNING) << "ingest binlog elapsed " << elapsed_time_ms << " ms, "
264
0
                         << elapsed_details;
265
0
        }
266
0
        if (tstatus.status_code != TStatusCode::OK) {
267
            // abort txn
268
0
            engine.txn_manager()->abort_txn(partition_id, txn_id, local_tablet_id,
269
0
                                            local_tablet_uid);
270
            // delete all successfully downloaded files
271
0
            LOG(WARNING) << "will delete downloaded success files due to error " << tstatus;
272
0
            std::vector<io::Path> paths;
273
0
            for (const auto& file : download_success_files) {
274
0
                paths.emplace_back(file);
275
0
                LOG(WARNING) << "will delete downloaded success file " << file << " due to error";
276
0
            }
277
0
            static_cast<void>(io::global_local_filesystem()->batch_delete(paths));
278
0
            LOG(WARNING) << "done delete downloaded success files due to error " << tstatus;
279
0
        }
280
281
0
        if (ingest_binlog_tstatus) {
282
0
            *ingest_binlog_tstatus = std::move(tstatus);
283
0
        }
284
0
    }};
285
286
0
    auto set_tstatus = [&tstatus](TStatusCode::type code, std::string error_msg) {
287
0
        tstatus.__set_status_code(code);
288
0
        tstatus.__isset.error_msgs = true;
289
0
        tstatus.error_msgs.push_back(std::move(error_msg));
290
0
    };
291
292
0
    auto estimate_download_timeout = [](int64_t file_size) {
293
0
        uint64_t estimate_timeout = file_size / config::download_low_speed_limit_kbps / 1024;
294
0
        if (estimate_timeout < config::download_low_speed_time) {
295
0
            estimate_timeout = config::download_low_speed_time;
296
0
        }
297
0
        return estimate_timeout;
298
0
    };
299
300
    // Step 3: get binlog info
301
0
    auto binlog_api_url = fmt::format("http://{}:{}/api/_binlog/_download", request.remote_host,
302
0
                                      request.remote_port);
303
0
    constexpr int max_retry = 3;
304
305
0
    auto get_binlog_info_url =
306
0
            fmt::format("{}?method={}&tablet_id={}&binlog_version={}", binlog_api_url,
307
0
                        "get_binlog_info", request.remote_tablet_id, request.binlog_version);
308
0
    std::string binlog_info;
309
0
    auto get_binlog_info_cb = [&get_binlog_info_url, &binlog_info](HttpClient* client) {
310
0
        RETURN_IF_ERROR(client->init(get_binlog_info_url));
311
0
        client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
312
0
        return client->execute(&binlog_info);
313
0
    };
314
0
    auto status = _exec_http_req(client, max_retry, 1, get_binlog_info_cb);
315
0
    if (!status.ok()) {
316
0
        LOG(WARNING) << "failed to get binlog info from " << get_binlog_info_url
317
0
                     << ", status=" << status.to_string();
318
0
        status.to_thrift(&tstatus);
319
0
        return;
320
0
    }
321
0
    elapsed_time_map.emplace("get_binlog_info", watch.elapsed_time_microseconds());
322
323
0
    std::vector<std::string> binlog_info_parts = absl::StrSplit(binlog_info, ":");
324
0
    if (binlog_info_parts.size() != 2) {
325
0
        status = Status::RuntimeError("failed to parse binlog info into 2 parts: {}", binlog_info);
326
0
        LOG(WARNING) << "failed to get binlog info from " << get_binlog_info_url
327
0
                     << ", status=" << status.to_string();
328
0
        status.to_thrift(&tstatus);
329
0
        return;
330
0
    }
331
0
    std::string remote_rowset_id = std::move(binlog_info_parts[0]);
332
0
    int64_t num_segments = -1;
333
0
    try {
334
0
        num_segments = std::stoll(binlog_info_parts[1]);
335
0
    } catch (std::exception& e) {
336
0
        status = Status::RuntimeError("failed to parse num segments from binlog info {}: {}",
337
0
                                      binlog_info, e.what());
338
0
        LOG(WARNING) << "failed to get binlog info from " << get_binlog_info_url
339
0
                     << ", status=" << status;
340
0
        status.to_thrift(&tstatus);
341
0
        return;
342
0
    }
343
344
    // Step 4: get rowset meta
345
0
    auto get_rowset_meta_url = fmt::format(
346
0
            "{}?method={}&tablet_id={}&rowset_id={}&binlog_version={}", binlog_api_url,
347
0
            "get_rowset_meta", request.remote_tablet_id, remote_rowset_id, request.binlog_version);
348
0
    std::string rowset_meta_str;
349
0
    auto get_rowset_meta_cb = [&get_rowset_meta_url, &rowset_meta_str](HttpClient* client) {
350
0
        RETURN_IF_ERROR(client->init(get_rowset_meta_url));
351
0
        client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
352
0
        return client->execute(&rowset_meta_str);
353
0
    };
354
0
    status = _exec_http_req(client, max_retry, 1, get_rowset_meta_cb);
355
0
    if (!status.ok()) {
356
0
        LOG(WARNING) << "failed to get rowset meta from " << get_rowset_meta_url
357
0
                     << ", status=" << status.to_string();
358
0
        status.to_thrift(&tstatus);
359
0
        return;
360
0
    }
361
0
    elapsed_time_map.emplace("get_rowset_meta", watch.elapsed_time_microseconds());
362
363
0
    RowsetMetaPB rowset_meta_pb;
364
0
    if (!rowset_meta_pb.ParseFromString(rowset_meta_str)) {
365
0
        LOG(WARNING) << "failed to parse rowset meta from " << get_rowset_meta_url;
366
0
        status = Status::InternalError("failed to parse rowset meta");
367
0
        status.to_thrift(&tstatus);
368
0
        return;
369
0
    }
370
    // save source rowset id and tablet id
371
0
    rowset_meta_pb.set_source_rowset_id(remote_rowset_id);
372
0
    rowset_meta_pb.set_source_tablet_id(request.remote_tablet_id);
373
    // rewrite rowset meta
374
0
    rowset_meta_pb.set_tablet_id(local_tablet_id);
375
0
    rowset_meta_pb.set_partition_id(partition_id);
376
0
    rowset_meta_pb.set_tablet_schema_hash(local_tablet->tablet_meta()->schema_hash());
377
0
    rowset_meta_pb.set_txn_id(txn_id);
378
0
    rowset_meta_pb.set_rowset_state(RowsetStatePB::COMMITTED);
379
0
    auto rowset_meta = std::make_shared<RowsetMeta>();
380
0
    if (!rowset_meta->init_from_pb(rowset_meta_pb)) {
381
0
        LOG(WARNING) << "failed to init rowset meta from " << get_rowset_meta_url;
382
0
        status = Status::InternalError("failed to init rowset meta");
383
0
        status.to_thrift(&tstatus);
384
0
        return;
385
0
    }
386
0
    RowsetId new_rowset_id = engine.next_rowset_id();
387
0
    auto pending_rs_guard = engine.pending_local_rowsets().add(new_rowset_id);
388
0
    rowset_meta->set_rowset_id(new_rowset_id);
389
0
    rowset_meta->set_tablet_uid(local_tablet->tablet_uid());
390
391
    // Step 5: get all segment files
392
    // Step 5.1: get all segment files size
393
0
    std::vector<std::string> segment_file_urls;
394
0
    segment_file_urls.reserve(num_segments);
395
0
    std::vector<uint64_t> segment_file_sizes;
396
0
    segment_file_sizes.reserve(num_segments);
397
0
    for (int64_t segment_index = 0; segment_index < num_segments; ++segment_index) {
398
0
        auto get_segment_file_size_url = fmt::format(
399
0
                "{}?method={}&tablet_id={}&rowset_id={}&segment_index={}", binlog_api_url,
400
0
                "get_segment_file", request.remote_tablet_id, remote_rowset_id, segment_index);
401
0
        uint64_t segment_file_size;
402
0
        auto get_segment_file_size_cb = [&get_segment_file_size_url,
403
0
                                         &segment_file_size](HttpClient* client) {
404
0
            RETURN_IF_ERROR(client->init(get_segment_file_size_url));
405
0
            client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
406
0
            RETURN_IF_ERROR(client->head());
407
0
            return client->get_content_length(&segment_file_size);
408
0
        };
409
410
0
        status = _exec_http_req(client, max_retry, 1, get_segment_file_size_cb);
411
0
        if (!status.ok()) {
412
0
            LOG(WARNING) << "failed to get segment file size from " << get_segment_file_size_url
413
0
                         << ", status=" << status.to_string();
414
0
            status.to_thrift(&tstatus);
415
0
            return;
416
0
        }
417
418
0
        segment_file_sizes.push_back(segment_file_size);
419
0
        segment_file_urls.push_back(std::move(get_segment_file_size_url));
420
0
    }
421
0
    elapsed_time_map.emplace("get_segment_file_size", watch.elapsed_time_microseconds());
422
423
    // Step 5.2: check data capacity
424
0
    uint64_t total_size = std::accumulate(segment_file_sizes.begin(), segment_file_sizes.end(),
425
0
                                          0ULL); // NOLINT(bugprone-fold-init-type)
426
0
    if (!local_tablet->can_add_binlog(total_size)) {
427
0
        LOG(WARNING) << "failed to add binlog, no enough space, total_size=" << total_size
428
0
                     << ", tablet=" << local_tablet->tablet_id();
429
0
        status = Status::InternalError("no enough space");
430
0
        status.to_thrift(&tstatus);
431
0
        return;
432
0
    }
433
0
    total_download_bytes = total_size;
434
0
    total_download_files = num_segments;
435
436
    // Step 5.3: get all segment files
437
0
    for (int64_t segment_index = 0; segment_index < num_segments; ++segment_index) {
438
0
        auto segment_file_size = segment_file_sizes[segment_index];
439
0
        auto get_segment_file_url = segment_file_urls[segment_index];
440
0
        if (config::enable_download_md5sum_check) {
441
0
            get_segment_file_url = fmt::format("{}&acquire_md5=true", get_segment_file_url);
442
0
        }
443
444
0
        auto segment_path = local_segment_path(local_tablet->tablet_path(),
445
0
                                               rowset_meta->rowset_id().to_string(), segment_index);
446
0
        LOG(INFO) << "download segment file from " << get_segment_file_url << " to "
447
0
                  << segment_path;
448
0
        uint64_t estimate_timeout = estimate_download_timeout(segment_file_size);
449
0
        auto get_segment_file_cb = [&get_segment_file_url, &segment_path, segment_file_size,
450
0
                                    estimate_timeout, &download_success_files](HttpClient* client) {
451
0
            return _download_binlog_segment_file(client, get_segment_file_url, segment_path,
452
0
                                                 segment_file_size, estimate_timeout,
453
0
                                                 download_success_files);
454
0
        };
455
456
0
        status = _exec_http_req(client, max_retry, 1, get_segment_file_cb);
457
0
        if (!status.ok()) {
458
0
            LOG(WARNING) << "failed to get segment file from " << get_segment_file_url
459
0
                         << ", status=" << status.to_string();
460
0
            status.to_thrift(&tstatus);
461
0
            return;
462
0
        }
463
0
    }
464
0
    elapsed_time_map.emplace("get_segment_files", watch.elapsed_time_microseconds());
465
466
    // Step 6: get all segment index files
467
    // Step 6.1: get all segment index files size
468
0
    std::vector<std::string> segment_index_file_urls;
469
0
    std::vector<uint64_t> segment_index_file_sizes;
470
0
    std::vector<std::string> segment_index_file_names;
471
0
    auto tablet_schema = rowset_meta->tablet_schema();
472
0
    if (tablet_schema->get_inverted_index_storage_format() == InvertedIndexStorageFormatPB::V1) {
473
0
        for (const auto& index : tablet_schema->inverted_indexes()) {
474
0
            auto index_id = index->index_id();
475
0
            for (int64_t segment_index = 0; segment_index < num_segments; ++segment_index) {
476
0
                auto get_segment_index_file_size_url = fmt::format(
477
0
                        "{}?method={}&tablet_id={}&rowset_id={}&segment_index={}&segment_index_id={"
478
0
                        "}",
479
0
                        binlog_api_url, "get_segment_index_file", request.remote_tablet_id,
480
0
                        remote_rowset_id, segment_index, index_id);
481
0
                uint64_t segment_index_file_size;
482
0
                auto get_segment_index_file_size_cb =
483
0
                        [&get_segment_index_file_size_url,
484
0
                         &segment_index_file_size](HttpClient* client) {
485
0
                            RETURN_IF_ERROR(client->init(get_segment_index_file_size_url));
486
0
                            client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
487
0
                            RETURN_IF_ERROR(client->head());
488
0
                            return client->get_content_length(&segment_index_file_size);
489
0
                        };
490
491
0
                auto segment_path =
492
0
                        local_segment_path(local_tablet->tablet_path(),
493
0
                                           rowset_meta->rowset_id().to_string(), segment_index);
494
0
                segment_index_file_names.push_back(InvertedIndexDescriptor::get_index_file_path_v1(
495
0
                        InvertedIndexDescriptor::get_index_file_path_prefix(segment_path), index_id,
496
0
                        index->get_index_suffix()));
497
498
0
                status = _exec_http_req(client, max_retry, 1, get_segment_index_file_size_cb);
499
0
                if (!status.ok()) {
500
0
                    LOG(WARNING) << "failed to get segment file size from "
501
0
                                 << get_segment_index_file_size_url
502
0
                                 << ", status=" << status.to_string();
503
0
                    status.to_thrift(&tstatus);
504
0
                    return;
505
0
                }
506
507
0
                segment_index_file_sizes.push_back(segment_index_file_size);
508
0
                segment_index_file_urls.push_back(std::move(get_segment_index_file_size_url));
509
0
            }
510
0
        }
511
0
    } else {
512
0
        for (int64_t segment_index = 0; segment_index < num_segments; ++segment_index) {
513
0
            if (tablet_schema->has_inverted_index() || tablet_schema->has_ann_index()) {
514
0
                auto get_segment_index_file_size_url = fmt::format(
515
0
                        "{}?method={}&tablet_id={}&rowset_id={}&segment_index={}&segment_index_id={"
516
0
                        "}",
517
0
                        binlog_api_url, "get_segment_index_file", request.remote_tablet_id,
518
0
                        remote_rowset_id, segment_index, -1);
519
0
                uint64_t segment_index_file_size;
520
0
                auto get_segment_index_file_size_cb =
521
0
                        [&get_segment_index_file_size_url,
522
0
                         &segment_index_file_size](HttpClient* client) {
523
0
                            RETURN_IF_ERROR(client->init(get_segment_index_file_size_url));
524
0
                            client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
525
0
                            RETURN_IF_ERROR(client->head());
526
0
                            return client->get_content_length(&segment_index_file_size);
527
0
                        };
528
0
                auto segment_path =
529
0
                        local_segment_path(local_tablet->tablet_path(),
530
0
                                           rowset_meta->rowset_id().to_string(), segment_index);
531
0
                segment_index_file_names.push_back(InvertedIndexDescriptor::get_index_file_path_v2(
532
0
                        InvertedIndexDescriptor::get_index_file_path_prefix(segment_path)));
533
534
0
                status = _exec_http_req(client, max_retry, 1, get_segment_index_file_size_cb);
535
0
                if (!status.ok()) {
536
0
                    LOG(WARNING) << "failed to get segment file size from "
537
0
                                 << get_segment_index_file_size_url
538
0
                                 << ", status=" << status.to_string();
539
0
                    status.to_thrift(&tstatus);
540
0
                    return;
541
0
                }
542
543
0
                segment_index_file_sizes.push_back(segment_index_file_size);
544
0
                segment_index_file_urls.push_back(std::move(get_segment_index_file_size_url));
545
0
            }
546
0
        }
547
0
    }
548
0
    elapsed_time_map.emplace("get_segment_index_file_size", watch.elapsed_time_microseconds());
549
550
    // Step 6.2: check data capacity
551
0
    uint64_t total_index_size =
552
0
            std::accumulate(segment_index_file_sizes.begin(), segment_index_file_sizes.end(),
553
0
                            0ULL); // NOLINT(bugprone-fold-init-type)
554
0
    if (!local_tablet->can_add_binlog(total_index_size)) {
555
0
        LOG(WARNING) << "failed to add binlog, no enough space, total_index_size="
556
0
                     << total_index_size << ", tablet=" << local_tablet->tablet_id();
557
0
        status = Status::InternalError("no enough space");
558
0
        status.to_thrift(&tstatus);
559
0
        return;
560
0
    }
561
0
    total_download_bytes += total_index_size;
562
0
    total_download_files += segment_index_file_urls.size();
563
564
    // Step 6.3: get all segment index files
565
0
    DCHECK(segment_index_file_sizes.size() == segment_index_file_names.size());
566
0
    DCHECK(segment_index_file_names.size() == segment_index_file_urls.size());
567
0
    for (int64_t i = 0; i < segment_index_file_urls.size(); ++i) {
568
0
        auto segment_index_file_size = segment_index_file_sizes[i];
569
0
        auto get_segment_index_file_url = segment_index_file_urls[i];
570
0
        if (config::enable_download_md5sum_check) {
571
0
            get_segment_index_file_url =
572
0
                    fmt::format("{}&acquire_md5=true", get_segment_index_file_url);
573
0
        }
574
575
0
        uint64_t estimate_timeout = estimate_download_timeout(segment_index_file_size);
576
0
        auto local_segment_index_path = segment_index_file_names[i];
577
0
        LOG(INFO) << fmt::format("download segment index file from {} to {}",
578
0
                                 get_segment_index_file_url, local_segment_index_path);
579
0
        auto get_segment_index_file_cb = [&get_segment_index_file_url, &local_segment_index_path,
580
0
                                          segment_index_file_size, estimate_timeout,
581
0
                                          &download_success_files](HttpClient* client) {
582
0
            return _download_binlog_index_file(client, get_segment_index_file_url,
583
0
                                               local_segment_index_path, segment_index_file_size,
584
0
                                               estimate_timeout, download_success_files);
585
0
        };
586
587
0
        status = _exec_http_req(client, max_retry, 1, get_segment_index_file_cb);
588
0
        if (!status.ok()) {
589
0
            LOG(WARNING) << "failed to get segment index file from " << get_segment_index_file_url
590
0
                         << ", status=" << status.to_string();
591
0
            status.to_thrift(&tstatus);
592
0
            return;
593
0
        }
594
0
    }
595
0
    elapsed_time_map.emplace("get_segment_index_files", watch.elapsed_time_microseconds());
596
597
    // Step 7: create rowset && calculate delete bitmap && commit
598
    // Step 7.1: create rowset
599
0
    RowsetSharedPtr rowset;
600
0
    status = RowsetFactory::create_rowset(local_tablet->tablet_schema(),
601
0
                                          local_tablet->tablet_path(), rowset_meta, &rowset);
602
0
    if (!status) {
603
0
        LOG(WARNING) << "failed to create rowset from rowset meta for remote tablet"
604
0
                     << ". rowset_id: " << rowset_meta_pb.rowset_id()
605
0
                     << ", rowset_type: " << rowset_meta_pb.rowset_type()
606
0
                     << ", remote_tablet_id=" << rowset_meta_pb.tablet_id() << ", txn_id=" << txn_id
607
0
                     << ", status=" << status.to_string();
608
0
        status.to_thrift(&tstatus);
609
0
        return;
610
0
    }
611
612
    // Step 7.2 calculate delete bitmap before commit
613
0
    auto calc_delete_bitmap_token = engine.calc_delete_bitmap_executor()->create_token();
614
0
    DeleteBitmapPtr delete_bitmap = std::make_shared<DeleteBitmap>(local_tablet_id);
615
0
    RowsetIdUnorderedSet pre_rowset_ids;
616
0
    if (local_tablet->enable_unique_key_merge_on_write()) {
617
0
        auto beta_rowset = reinterpret_cast<BetaRowset*>(rowset.get());
618
0
        std::vector<segment_v2::SegmentSharedPtr> segments;
619
0
        status = beta_rowset->load_segments(&segments);
620
0
        if (!status) {
621
0
            LOG(WARNING) << "failed to load segments from rowset"
622
0
                         << ". rowset_id: " << beta_rowset->rowset_id() << ", txn_id=" << txn_id
623
0
                         << ", status=" << status.to_string();
624
0
            status.to_thrift(&tstatus);
625
0
            return;
626
0
        }
627
0
        elapsed_time_map.emplace("load_segments", watch.elapsed_time_microseconds());
628
0
        if (segments.size() > 1) {
629
            // calculate delete bitmap between segments
630
0
            status = local_tablet->calc_delete_bitmap_between_segments(
631
0
                    rowset->tablet_schema(), rowset->rowset_id(), segments, delete_bitmap);
632
0
            if (!status) {
633
0
                LOG(WARNING) << "failed to calculate delete bitmap"
634
0
                             << ". tablet_id: " << local_tablet->tablet_id()
635
0
                             << ". rowset_id: " << rowset->rowset_id() << ", txn_id=" << txn_id
636
0
                             << ", status=" << status.to_string();
637
0
                status.to_thrift(&tstatus);
638
0
                return;
639
0
            }
640
0
            elapsed_time_map.emplace("calc_delete_bitmap", watch.elapsed_time_microseconds());
641
0
        }
642
643
0
        static_cast<void>(BaseTablet::commit_phase_update_delete_bitmap(
644
0
                local_tablet, rowset, pre_rowset_ids, delete_bitmap, segments, txn_id,
645
0
                calc_delete_bitmap_token.get(), nullptr));
646
0
        elapsed_time_map.emplace("commit_phase_update_delete_bitmap",
647
0
                                 watch.elapsed_time_microseconds());
648
0
        static_cast<void>(calc_delete_bitmap_token->wait());
649
0
        elapsed_time_map.emplace("wait_delete_bitmap", watch.elapsed_time_microseconds());
650
0
    }
651
652
    // Step 7.3: commit txn
653
0
    Status commit_txn_status = engine.txn_manager()->commit_txn(
654
0
            local_tablet->data_dir()->get_meta(), rowset_meta->partition_id(),
655
0
            rowset_meta->txn_id(), rowset_meta->tablet_id(), local_tablet->tablet_uid(),
656
0
            rowset_meta->load_id(), rowset, std::move(pending_rs_guard), false);
657
0
    if (!commit_txn_status && !commit_txn_status.is<ErrorCode::PUSH_TRANSACTION_ALREADY_EXIST>()) {
658
0
        auto err_msg = fmt::format(
659
0
                "failed to commit txn for remote tablet. rowset_id: {}, remote_tablet_id={}, "
660
0
                "txn_id={}, status={}",
661
0
                rowset_meta->rowset_id().to_string(), rowset_meta->tablet_id(),
662
0
                rowset_meta->txn_id(), commit_txn_status.to_string());
663
0
        LOG(WARNING) << err_msg;
664
0
        set_tstatus(TStatusCode::RUNTIME_ERROR, std::move(err_msg));
665
0
        return;
666
0
    }
667
0
    elapsed_time_map.emplace("commit_txn", watch.elapsed_time_microseconds());
668
669
0
    if (local_tablet->enable_unique_key_merge_on_write()) {
670
0
        engine.txn_manager()->set_txn_related_delete_bitmap(partition_id, txn_id, local_tablet_id,
671
0
                                                            local_tablet->tablet_uid(), true,
672
0
                                                            delete_bitmap, pre_rowset_ids, nullptr);
673
0
        elapsed_time_map.emplace("set_txn_related_delete_bitmap",
674
0
                                 watch.elapsed_time_microseconds());
675
0
    }
676
677
0
    tstatus.__set_status_code(TStatusCode::OK);
678
0
}
679
} // namespace
680
681
BaseBackendService::BaseBackendService(ExecEnv* exec_env)
682
4
        : _exec_env(exec_env), _agent_server(new AgentServer(exec_env, exec_env->cluster_info())) {}
683
684
0
BaseBackendService::~BaseBackendService() = default;
685
686
BackendService::BackendService(StorageEngine& engine, ExecEnv* exec_env)
687
3
        : BaseBackendService(exec_env), _engine(engine) {}
688
689
BackendService::~BackendService() = default;
690
691
3
Status BackendService::start_thrift_dependencies() {
692
3
    _agent_server->start_workers(_engine, _exec_env);
693
694
3
    auto thread_num = config::ingest_binlog_work_pool_size;
695
3
    if (thread_num < 0) {
696
3
        LOG(INFO) << fmt::format("ingest binlog thread pool size is {}, so we will in sync mode",
697
3
                                 thread_num);
698
3
        return Status::OK();
699
3
    }
700
701
0
    if (thread_num == 0) {
702
0
        thread_num = std::thread::hardware_concurrency();
703
0
    }
704
0
    static_cast<void>(doris::ThreadPoolBuilder("IngestBinlog")
705
0
                              .set_min_threads(thread_num)
706
0
                              .set_max_threads(thread_num * 2)
707
0
                              .build(&_ingest_binlog_workers));
708
0
    LOG(INFO) << fmt::format("ingest binlog thread pool size is {}, in async mode", thread_num);
709
0
    return Status::OK();
710
3
}
711
712
134
void BackendService::get_tablet_stat(TTabletStatResult& result) {
713
134
    _engine.tablet_manager()->get_tablet_stat(&result);
714
134
}
715
716
0
int64_t BackendService::get_trash_used_capacity() {
717
0
    int64_t result = 0;
718
719
0
    std::vector<DataDirInfo> data_dir_infos;
720
0
    static_cast<void>(_engine.get_all_data_dir_info(&data_dir_infos, false /*do not update */));
721
722
    // uses excute sql `show trash`, then update backend trash capacity too.
723
0
    _engine.notify_listener("REPORT_DISK_STATE");
724
725
0
    for (const auto& root_path_info : data_dir_infos) {
726
0
        result += root_path_info.trash_used_capacity;
727
0
    }
728
729
0
    return result;
730
0
}
731
732
0
void BackendService::get_disk_trash_used_capacity(std::vector<TDiskTrashInfo>& diskTrashInfos) {
733
0
    std::vector<DataDirInfo> data_dir_infos;
734
0
    static_cast<void>(_engine.get_all_data_dir_info(&data_dir_infos, false /*do not update */));
735
736
    // uses excute sql `show trash on <be>`, then update backend trash capacity too.
737
0
    _engine.notify_listener("REPORT_DISK_STATE");
738
739
0
    for (const auto& root_path_info : data_dir_infos) {
740
0
        TDiskTrashInfo diskTrashInfo;
741
0
        diskTrashInfo.__set_root_path(root_path_info.path);
742
0
        diskTrashInfo.__set_state(root_path_info.is_used ? "ONLINE" : "OFFLINE");
743
0
        diskTrashInfo.__set_trash_used_capacity(root_path_info.trash_used_capacity);
744
0
        diskTrashInfos.push_back(diskTrashInfo);
745
0
    }
746
0
}
747
748
void BaseBackendService::submit_routine_load_task(TStatus& t_status,
749
186
                                                  const std::vector<TRoutineLoadTask>& tasks) {
750
186
    for (auto& task : tasks) {
751
186
        Status st = _exec_env->routine_load_task_executor()->submit_task(task);
752
186
        if (!st.ok()) {
753
1
            LOG(WARNING) << "failed to submit routine load task. job id: " << task.job_id
754
1
                         << " task id: " << task.id;
755
1
            return st.to_thrift(&t_status);
756
1
        }
757
186
    }
758
759
185
    return Status::OK().to_thrift(&t_status);
760
186
}
761
762
/*
763
 * 1. validate user privilege (todo)
764
 * 2. FragmentMgr#exec_plan_fragment
765
 */
766
3
void BaseBackendService::open_scanner(TScanOpenResult& result_, const TScanOpenParams& params) {
767
3
    TStatus t_status;
768
3
    TUniqueId fragment_instance_id = generate_uuid();
769
    // A query_id is randomly generated to replace t_query_plan_info.query_id.
770
    // external query does not need to report anything to FE, so the query_id can be changed.
771
    // Otherwise, multiple independent concurrent open tablet scanners have the same query_id.
772
    // when one of the scanners ends, the other scanners will be canceled through FragmentMgr.cancel(query_id).
773
3
    TUniqueId query_id = generate_uuid();
774
3
    std::shared_ptr<ScanContext> p_context;
775
3
    static_cast<void>(_exec_env->external_scan_context_mgr()->create_scan_context(&p_context));
776
3
    p_context->fragment_instance_id = fragment_instance_id;
777
3
    p_context->offset = 0;
778
3
    p_context->last_access_time = time(nullptr);
779
3
    if (params.__isset.keep_alive_min) {
780
0
        p_context->keep_alive_min = params.keep_alive_min;
781
3
    } else {
782
3
        p_context->keep_alive_min = 5;
783
3
    }
784
785
3
    Status exec_st;
786
3
    TQueryPlanInfo t_query_plan_info;
787
3
    {
788
3
        const std::string& opaqued_query_plan = params.opaqued_query_plan;
789
3
        std::string query_plan_info;
790
        // base64 decode query plan
791
3
        if (!base64_decode(opaqued_query_plan, &query_plan_info)) {
792
0
            LOG(WARNING) << "open context error: base64_decode decode opaqued_query_plan failure";
793
0
            std::stringstream msg;
794
0
            msg << "query_plan_info: " << query_plan_info
795
0
                << " validate error, should not be modified after returned Doris FE processed";
796
0
            exec_st = Status::InvalidArgument(msg.str());
797
0
        }
798
799
3
        const uint8_t* buf = (const uint8_t*)query_plan_info.data();
800
3
        uint32_t len = (uint32_t)query_plan_info.size();
801
        // deserialize TQueryPlanInfo
802
3
        auto st = deserialize_thrift_msg(buf, &len, false, &t_query_plan_info);
803
3
        if (!st.ok()) {
804
0
            LOG(WARNING) << "open context error: deserialize TQueryPlanInfo failure";
805
0
            std::stringstream msg;
806
0
            msg << "query_plan_info: " << query_plan_info
807
0
                << " deserialize error, should not be modified after returned Doris FE processed";
808
0
            exec_st = Status::InvalidArgument(msg.str());
809
0
        }
810
3
        p_context->query_id = query_id;
811
3
    }
812
3
    std::vector<TScanColumnDesc> selected_columns;
813
3
    if (exec_st.ok()) {
814
        // start the scan procedure
815
3
        LOG(INFO) << fmt::format(
816
3
                "exec external scanner, old_query_id = {}, new_query_id = {}, fragment_instance_id "
817
3
                "= {}",
818
3
                print_id(t_query_plan_info.query_id), print_id(query_id),
819
3
                print_id(fragment_instance_id));
820
3
        exec_st = _exec_env->fragment_mgr()->exec_external_plan_fragment(
821
3
                params, t_query_plan_info, query_id, fragment_instance_id, &selected_columns);
822
3
    }
823
3
    exec_st.to_thrift(&t_status);
824
    //return status
825
    // t_status.status_code = TStatusCode::OK;
826
3
    result_.status = t_status;
827
3
    result_.__set_context_id(p_context->context_id);
828
3
    result_.__set_selected_columns(selected_columns);
829
3
}
830
831
// fetch result from polling the queue, should always maintain the context offset, otherwise inconsistent result
832
5
void BaseBackendService::get_next(TScanBatchResult& result_, const TScanNextBatchParams& params) {
833
5
    std::string context_id = params.context_id;
834
5
    u_int64_t offset = params.offset;
835
5
    TStatus t_status;
836
5
    std::shared_ptr<ScanContext> context;
837
5
    Status st = _exec_env->external_scan_context_mgr()->get_scan_context(context_id, &context);
838
5
    if (!st.ok()) {
839
0
        st.to_thrift(&t_status);
840
0
        result_.status = t_status;
841
0
        return;
842
0
    }
843
5
    if (offset != context->offset) {
844
0
        LOG(ERROR) << "getNext error: context offset [" << context->offset << " ]"
845
0
                   << " ,client offset [ " << offset << " ]";
846
        // invalid offset
847
0
        t_status.status_code = TStatusCode::NOT_FOUND;
848
0
        t_status.error_msgs.push_back(
849
0
                absl::Substitute("context_id=$0, send_offset=$1, context_offset=$2", context_id,
850
0
                                 offset, context->offset));
851
0
        result_.status = t_status;
852
5
    } else {
853
        // during accessing, should disabled last_access_time
854
5
        context->last_access_time = -1;
855
5
        TUniqueId fragment_instance_id = context->fragment_instance_id;
856
5
        std::shared_ptr<arrow::RecordBatch> record_batch;
857
5
        bool eos;
858
859
5
        st = _exec_env->result_queue_mgr()->fetch_result(fragment_instance_id, &record_batch, &eos);
860
5
        if (st.ok()) {
861
5
            result_.__set_eos(eos);
862
5
            if (!eos) {
863
3
                std::string record_batch_str;
864
3
                st = serialize_record_batch(*record_batch, &record_batch_str);
865
3
                st.to_thrift(&t_status);
866
3
                if (st.ok()) {
867
                    // avoid copy large string
868
3
                    result_.rows = std::move(record_batch_str);
869
                    // set __isset
870
3
                    result_.__isset.rows = true;
871
3
                    context->offset += record_batch->num_rows();
872
3
                }
873
3
            }
874
5
        } else {
875
0
            LOG(WARNING) << "fragment_instance_id [" << print_id(fragment_instance_id)
876
0
                         << "] fetch result status [" << st.to_string() + "]";
877
0
            st.to_thrift(&t_status);
878
0
            result_.status = t_status;
879
0
        }
880
5
    }
881
5
    context->last_access_time = time(nullptr);
882
5
}
883
884
2
void BaseBackendService::close_scanner(TScanCloseResult& result_, const TScanCloseParams& params) {
885
2
    std::string context_id = params.context_id;
886
2
    TStatus t_status;
887
2
    Status st = _exec_env->external_scan_context_mgr()->clear_scan_context(context_id);
888
2
    st.to_thrift(&t_status);
889
2
    result_.status = t_status;
890
2
}
891
892
void BackendService::get_stream_load_record(TStreamLoadRecordResult& result,
893
67
                                            int64_t last_stream_record_time) {
894
67
    BaseBackendService::get_stream_load_record(result, last_stream_record_time,
895
67
                                               _engine.get_stream_load_recorder());
896
67
}
897
898
0
void BackendService::check_storage_format(TCheckStorageFormatResult& result) {
899
0
    _engine.tablet_manager()->get_all_tablets_storage_format(&result);
900
0
}
901
902
void BackendService::make_snapshot(TAgentResult& return_value,
903
0
                                   const TSnapshotRequest& snapshot_request) {
904
0
    std::string snapshot_path;
905
0
    bool allow_incremental_clone = false;
906
0
    Status status = _engine.snapshot_mgr()->make_snapshot(snapshot_request, &snapshot_path,
907
0
                                                          &allow_incremental_clone);
908
0
    if (!status) {
909
0
        LOG_WARNING("failed to make snapshot")
910
0
                .tag("tablet_id", snapshot_request.tablet_id)
911
0
                .tag("schema_hash", snapshot_request.schema_hash)
912
0
                .error(status);
913
0
    } else {
914
0
        LOG_INFO("successfully make snapshot")
915
0
                .tag("tablet_id", snapshot_request.tablet_id)
916
0
                .tag("schema_hash", snapshot_request.schema_hash)
917
0
                .tag("snapshot_path", snapshot_path);
918
0
        return_value.__set_snapshot_path(snapshot_path);
919
0
        return_value.__set_allow_incremental_clone(allow_incremental_clone);
920
0
    }
921
922
0
    status.to_thrift(&return_value.status);
923
0
    return_value.__set_snapshot_version(snapshot_request.preferred_snapshot_version);
924
0
}
925
926
void BackendService::release_snapshot(TAgentResult& return_value,
927
0
                                      const std::string& snapshot_path) {
928
0
    Status status = _engine.snapshot_mgr()->release_snapshot(snapshot_path);
929
0
    if (!status) {
930
0
        LOG_WARNING("failed to release snapshot").tag("snapshot_path", snapshot_path).error(status);
931
0
    } else {
932
0
        LOG_INFO("successfully release snapshot").tag("snapshot_path", snapshot_path);
933
0
    }
934
0
    status.to_thrift(&return_value.status);
935
0
}
936
937
void BackendService::ingest_binlog(TIngestBinlogResult& result,
938
0
                                   const TIngestBinlogRequest& request) {
939
0
    LOG(INFO) << "ingest binlog. request: " << apache::thrift::ThriftDebugString(request);
940
941
0
    TStatus tstatus;
942
0
    Defer defer {[&result, &tstatus]() {
943
0
        result.__set_status(tstatus);
944
0
        LOG(INFO) << "ingest binlog. result: " << apache::thrift::ThriftDebugString(result);
945
0
    }};
946
947
0
    auto set_tstatus = [&tstatus](TStatusCode::type code, std::string error_msg) {
948
0
        tstatus.__set_status_code(code);
949
0
        tstatus.__isset.error_msgs = true;
950
0
        tstatus.error_msgs.push_back(std::move(error_msg));
951
0
    };
952
953
0
    if (!config::enable_feature_binlog) {
954
0
        set_tstatus(TStatusCode::RUNTIME_ERROR, "enable feature binlog is false");
955
0
        return;
956
0
    }
957
958
    /// Check args: txn_id, remote_tablet_id, binlog_version, remote_host, remote_port, partition_id, load_id
959
0
    if (!request.__isset.txn_id) {
960
0
        auto error_msg = "txn_id is empty";
961
0
        LOG(WARNING) << error_msg;
962
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
963
0
        return;
964
0
    }
965
0
    if (!request.__isset.remote_tablet_id) {
966
0
        auto error_msg = "remote_tablet_id is empty";
967
0
        LOG(WARNING) << error_msg;
968
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
969
0
        return;
970
0
    }
971
0
    if (!request.__isset.binlog_version) {
972
0
        auto error_msg = "binlog_version is empty";
973
0
        LOG(WARNING) << error_msg;
974
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
975
0
        return;
976
0
    }
977
0
    if (!request.__isset.remote_host) {
978
0
        auto error_msg = "remote_host is empty";
979
0
        LOG(WARNING) << error_msg;
980
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
981
0
        return;
982
0
    }
983
0
    if (!request.__isset.remote_port) {
984
0
        auto error_msg = "remote_port is empty";
985
0
        LOG(WARNING) << error_msg;
986
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
987
0
        return;
988
0
    }
989
0
    if (!request.__isset.partition_id) {
990
0
        auto error_msg = "partition_id is empty";
991
0
        LOG(WARNING) << error_msg;
992
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
993
0
        return;
994
0
    }
995
0
    if (!request.__isset.local_tablet_id) {
996
0
        auto error_msg = "local_tablet_id is empty";
997
0
        LOG(WARNING) << error_msg;
998
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
999
0
        return;
1000
0
    }
1001
0
    if (!request.__isset.load_id) {
1002
0
        auto error_msg = "load_id is empty";
1003
0
        LOG(WARNING) << error_msg;
1004
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
1005
0
        return;
1006
0
    }
1007
1008
0
    auto txn_id = request.txn_id;
1009
    // Step 1: get local tablet
1010
0
    auto const& local_tablet_id = request.local_tablet_id;
1011
0
    auto local_tablet = _engine.tablet_manager()->get_tablet(local_tablet_id);
1012
0
    if (local_tablet == nullptr) {
1013
0
        auto error_msg = fmt::format("tablet {} not found", local_tablet_id);
1014
0
        LOG(WARNING) << error_msg;
1015
0
        set_tstatus(TStatusCode::TABLET_MISSING, std::move(error_msg));
1016
0
        return;
1017
0
    }
1018
1019
    // Step 2: check txn, create txn, prepare_txn will check it
1020
0
    auto partition_id = request.partition_id;
1021
0
    auto& load_id = request.load_id;
1022
0
    auto is_ingrest = true;
1023
0
    PUniqueId p_load_id;
1024
0
    p_load_id.set_hi(load_id.hi);
1025
0
    p_load_id.set_lo(load_id.lo);
1026
1027
0
    {
1028
        // TODO: Before push_lock is not held, but I think it should hold.
1029
0
        auto status = local_tablet->prepare_txn(partition_id, txn_id, p_load_id, is_ingrest);
1030
0
        if (!status.ok()) {
1031
0
            LOG(WARNING) << "prepare txn failed. txn_id=" << txn_id
1032
0
                         << ", status=" << status.to_string();
1033
0
            status.to_thrift(&tstatus);
1034
0
            return;
1035
0
        }
1036
0
    }
1037
1038
0
    bool is_async = (_ingest_binlog_workers != nullptr);
1039
0
    result.__set_is_async(is_async);
1040
1041
0
    auto ingest_binlog_func = [=, this, tstatus = &tstatus]() {
1042
0
        IngestBinlogArg ingest_binlog_arg = {
1043
0
                .txn_id = txn_id,
1044
0
                .partition_id = partition_id,
1045
0
                .local_tablet_id = local_tablet_id,
1046
0
                .local_tablet = local_tablet,
1047
1048
0
                .request = request,
1049
0
                .tstatus = is_async ? nullptr : tstatus,
1050
0
        };
1051
1052
0
        _ingest_binlog(_engine, &ingest_binlog_arg);
1053
0
    };
1054
1055
0
    if (is_async) {
1056
0
        auto status = _ingest_binlog_workers->submit_func(std::move(ingest_binlog_func));
1057
0
        if (!status.ok()) {
1058
0
            status.to_thrift(&tstatus);
1059
0
            return;
1060
0
        }
1061
0
    } else {
1062
0
        ingest_binlog_func();
1063
0
    }
1064
0
}
1065
1066
void BackendService::query_ingest_binlog(TQueryIngestBinlogResult& result,
1067
0
                                         const TQueryIngestBinlogRequest& request) {
1068
0
    LOG(INFO) << "query ingest binlog. request: " << apache::thrift::ThriftDebugString(request);
1069
1070
0
    auto set_result = [&](TIngestBinlogStatus::type status, std::string error_msg) {
1071
0
        result.__set_status(status);
1072
0
        result.__set_err_msg(std::move(error_msg));
1073
0
    };
1074
1075
    /// Check args: txn_id, partition_id, tablet_id, load_id
1076
0
    if (!request.__isset.txn_id) {
1077
0
        auto error_msg = "txn_id is empty";
1078
0
        LOG(WARNING) << error_msg;
1079
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1080
0
        return;
1081
0
    }
1082
0
    if (!request.__isset.partition_id) {
1083
0
        auto error_msg = "partition_id is empty";
1084
0
        LOG(WARNING) << error_msg;
1085
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1086
0
        return;
1087
0
    }
1088
0
    if (!request.__isset.tablet_id) {
1089
0
        auto error_msg = "tablet_id is empty";
1090
0
        LOG(WARNING) << error_msg;
1091
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1092
0
        return;
1093
0
    }
1094
0
    if (!request.__isset.load_id) {
1095
0
        auto error_msg = "load_id is empty";
1096
0
        LOG(WARNING) << error_msg;
1097
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1098
0
        return;
1099
0
    }
1100
1101
0
    auto partition_id = request.partition_id;
1102
0
    auto txn_id = request.txn_id;
1103
0
    auto tablet_id = request.tablet_id;
1104
1105
    // Step 1: get local tablet
1106
0
    auto local_tablet = _engine.tablet_manager()->get_tablet(tablet_id);
1107
0
    if (local_tablet == nullptr) {
1108
0
        auto error_msg = fmt::format("tablet {} not found", tablet_id);
1109
0
        LOG(WARNING) << error_msg;
1110
0
        set_result(TIngestBinlogStatus::NOT_FOUND, std::move(error_msg));
1111
0
        return;
1112
0
    }
1113
1114
    // Step 2: get txn state
1115
0
    auto tablet_uid = local_tablet->tablet_uid();
1116
0
    auto txn_state =
1117
0
            _engine.txn_manager()->get_txn_state(partition_id, txn_id, tablet_id, tablet_uid);
1118
0
    switch (txn_state) {
1119
0
    case TxnState::NOT_FOUND:
1120
0
        result.__set_status(TIngestBinlogStatus::NOT_FOUND);
1121
0
        break;
1122
0
    case TxnState::PREPARED:
1123
0
        result.__set_status(TIngestBinlogStatus::DOING);
1124
0
        break;
1125
0
    case TxnState::COMMITTED:
1126
0
        result.__set_status(TIngestBinlogStatus::OK);
1127
0
        break;
1128
0
    case TxnState::ROLLEDBACK:
1129
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1130
0
        break;
1131
0
    case TxnState::ABORTED:
1132
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1133
0
        break;
1134
0
    case TxnState::DELETED:
1135
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1136
0
        break;
1137
0
    }
1138
0
}
1139
1140
0
void BaseBackendService::get_tablet_stat(TTabletStatResult& result) {
1141
0
    LOG(ERROR) << "get_tablet_stat is not implemented";
1142
0
}
1143
1144
3
int64_t BaseBackendService::get_trash_used_capacity() {
1145
3
    LOG(ERROR) << "get_trash_used_capacity is not implemented";
1146
3
    return 0;
1147
3
}
1148
1149
void BaseBackendService::get_stream_load_record(TStreamLoadRecordResult& result,
1150
0
                                                int64_t last_stream_record_time) {
1151
0
    LOG(ERROR) << "get_stream_load_record is not implemented";
1152
0
}
1153
1154
void BaseBackendService::get_stream_load_record(
1155
        TStreamLoadRecordResult& result, int64_t last_stream_record_time,
1156
96
        std::shared_ptr<StreamLoadRecorder> stream_load_recorder) {
1157
96
    if (stream_load_recorder != nullptr) {
1158
96
        std::map<std::string, std::string> records;
1159
96
        auto st = stream_load_recorder->get_batch(std::to_string(last_stream_record_time),
1160
96
                                                  config::stream_load_record_batch_size, &records);
1161
96
        if (st.ok()) {
1162
96
            LOG(INFO) << "get_batch stream_load_record rocksdb successfully. records size: "
1163
96
                      << records.size()
1164
96
                      << ", last_stream_load_timestamp: " << last_stream_record_time;
1165
96
            std::map<std::string, TStreamLoadRecord> stream_load_record_batch;
1166
96
            auto it = records.begin();
1167
2.48k
            for (; it != records.end(); ++it) {
1168
2.38k
                TStreamLoadRecord stream_load_item;
1169
2.38k
                StreamLoadContext::parse_stream_load_record(it->second, stream_load_item);
1170
2.38k
                stream_load_record_batch.emplace(it->first.c_str(), stream_load_item);
1171
2.38k
            }
1172
96
            result.__set_stream_load_record(stream_load_record_batch);
1173
96
        }
1174
96
    } else {
1175
0
        LOG(WARNING) << "stream_load_recorder is null.";
1176
0
    }
1177
96
}
1178
1179
0
void BaseBackendService::get_disk_trash_used_capacity(std::vector<TDiskTrashInfo>& diskTrashInfos) {
1180
0
    LOG(ERROR) << "get_disk_trash_used_capacity is not implemented";
1181
0
}
1182
1183
void BaseBackendService::make_snapshot(TAgentResult& return_value,
1184
0
                                       const TSnapshotRequest& snapshot_request) {
1185
0
    LOG(ERROR) << "make_snapshot is not implemented";
1186
0
    return_value.__set_status(Status::NotSupported("make_snapshot is not implemented").to_thrift());
1187
0
}
1188
1189
void BaseBackendService::release_snapshot(TAgentResult& return_value,
1190
0
                                          const std::string& snapshot_path) {
1191
0
    LOG(ERROR) << "release_snapshot is not implemented";
1192
0
    return_value.__set_status(
1193
0
            Status::NotSupported("release_snapshot is not implemented").to_thrift());
1194
0
}
1195
1196
0
void BaseBackendService::check_storage_format(TCheckStorageFormatResult& result) {
1197
0
    LOG(ERROR) << "check_storage_format is not implemented";
1198
0
}
1199
1200
void BaseBackendService::ingest_binlog(TIngestBinlogResult& result,
1201
0
                                       const TIngestBinlogRequest& request) {
1202
0
    LOG(ERROR) << "ingest_binlog is not implemented";
1203
0
    result.__set_status(Status::NotSupported("ingest_binlog is not implemented").to_thrift());
1204
0
}
1205
1206
void BaseBackendService::query_ingest_binlog(TQueryIngestBinlogResult& result,
1207
0
                                             const TQueryIngestBinlogRequest& request) {
1208
0
    LOG(ERROR) << "query_ingest_binlog is not implemented";
1209
0
    result.__set_status(TIngestBinlogStatus::UNKNOWN);
1210
0
    result.__set_err_msg("query_ingest_binlog is not implemented");
1211
0
}
1212
1213
void BaseBackendService::warm_up_cache_async(TWarmUpCacheAsyncResponse& response,
1214
0
                                             const TWarmUpCacheAsyncRequest& request) {
1215
0
    LOG(ERROR) << "warm_up_cache_async is not implemented";
1216
0
    response.__set_status(
1217
0
            Status::NotSupported("warm_up_cache_async is not implemented").to_thrift());
1218
0
}
1219
1220
void BaseBackendService::check_warm_up_cache_async(TCheckWarmUpCacheAsyncResponse& response,
1221
0
                                                   const TCheckWarmUpCacheAsyncRequest& request) {
1222
0
    LOG(ERROR) << "check_warm_up_cache_async is not implemented";
1223
0
    response.__set_status(
1224
0
            Status::NotSupported("check_warm_up_cache_async is not implemented").to_thrift());
1225
0
}
1226
1227
void BaseBackendService::sync_load_for_tablets(TSyncLoadForTabletsResponse& response,
1228
0
                                               const TSyncLoadForTabletsRequest& request) {
1229
0
    LOG(ERROR) << "sync_load_for_tablets is not implemented";
1230
0
}
1231
1232
void BaseBackendService::get_top_n_hot_partitions(TGetTopNHotPartitionsResponse& response,
1233
0
                                                  const TGetTopNHotPartitionsRequest& request) {
1234
0
    LOG(ERROR) << "get_top_n_hot_partitions is not implemented";
1235
0
}
1236
1237
void BaseBackendService::warm_up_tablets(TWarmUpTabletsResponse& response,
1238
0
                                         const TWarmUpTabletsRequest& request) {
1239
0
    LOG(ERROR) << "warm_up_tablets is not implemented";
1240
0
    response.__set_status(Status::NotSupported("warm_up_tablets is not implemented").to_thrift());
1241
0
}
1242
1243
void BaseBackendService::get_realtime_exec_status(TGetRealtimeExecStatusResponse& response,
1244
1
                                                  const TGetRealtimeExecStatusRequest& request) {
1245
1
    if (!request.__isset.id) {
1246
0
        LOG_WARNING("Invalidate argument, id is empty");
1247
0
        response.__set_status(Status::InvalidArgument("id is empty").to_thrift());
1248
0
        return;
1249
0
    }
1250
1251
1
    RuntimeProfile::Counter get_realtime_timer {TUnit::TIME_NS};
1252
1253
1
    Defer _print_log([&]() {
1254
1
        LOG_INFO("Getting realtime exec status of query {} , cost time {}", print_id(request.id),
1255
1
                 PrettyPrinter::print(get_realtime_timer.value(), get_realtime_timer.type()));
1256
1
    });
1257
1258
1
    SCOPED_TIMER(&get_realtime_timer);
1259
1260
1
    std::unique_ptr<TReportExecStatusParams> report_exec_status_params =
1261
1
            std::make_unique<TReportExecStatusParams>();
1262
1
    std::unique_ptr<TQueryStatistics> query_stats = std::make_unique<TQueryStatistics>();
1263
1264
1
    std::string req_type = request.__isset.req_type ? request.req_type : "profile";
1265
1
    Status st;
1266
1
    if (req_type == "stats") {
1267
1
        st = ExecEnv::GetInstance()->fragment_mgr()->get_query_statistics(request.id,
1268
1
                                                                          query_stats.get());
1269
1
        if (st.ok()) {
1270
1
            response.__set_query_stats(*query_stats);
1271
1
        }
1272
1
    } else {
1273
        // default is "profile"
1274
0
        st = ExecEnv::GetInstance()->fragment_mgr()->get_realtime_exec_status(
1275
0
                request.id, report_exec_status_params.get());
1276
0
        if (st.ok()) {
1277
0
            response.__set_report_exec_status_params(*report_exec_status_params);
1278
0
        }
1279
0
    }
1280
1281
1
    report_exec_status_params->__set_query_id(TUniqueId());
1282
1
    report_exec_status_params->__set_done(false);
1283
1
    response.__set_status(st.to_thrift());
1284
1
}
1285
1286
void BaseBackendService::get_dictionary_status(TDictionaryStatusList& result,
1287
2.36k
                                               const std::vector<int64_t>& dictionary_ids) {
1288
2.36k
    std::vector<TDictionaryStatus> dictionary_status;
1289
2.36k
    ExecEnv::GetInstance()->dict_factory()->get_dictionary_status(dictionary_status,
1290
2.36k
                                                                  dictionary_ids);
1291
2.36k
    result.__set_dictionary_status_list(dictionary_status);
1292
2.36k
    LOG(INFO) << "query for dictionary status, return " << result.dictionary_status_list.size()
1293
2.36k
              << " rows";
1294
2.36k
}
1295
1296
void BaseBackendService::test_storage_connectivity(TTestStorageConnectivityResponse& response,
1297
0
                                                   const TTestStorageConnectivityRequest& request) {
1298
0
    Status status = io::StorageConnectivityTester::test(request.type, request.properties);
1299
0
    response.__set_status(status.to_thrift());
1300
0
}
1301
1302
2
void BaseBackendService::get_python_envs(std::vector<TPythonEnvInfo>& result) {
1303
2
    result = PythonVersionManager::instance().env_infos_to_thrift();
1304
2
}
1305
1306
void BaseBackendService::get_python_packages(std::vector<TPythonPackageInfo>& result,
1307
1
                                             const std::string& python_version) {
1308
1
    PythonVersion version;
1309
1
    auto& manager = PythonVersionManager::instance();
1310
1
    THROW_IF_ERROR(manager.get_version(python_version, &version));
1311
1312
1
    std::vector<std::pair<std::string, std::string>> packages;
1313
1
    THROW_IF_ERROR(list_installed_packages(version, &packages));
1314
1
    result = manager.package_infos_to_thrift(packages);
1315
1
}
1316
1317
} // namespace doris