Coverage Report

Created: 2026-04-14 07:58

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
7
        : _exec_env(exec_env), _agent_server(new AgentServer(exec_env, exec_env->cluster_info())) {}
683
684
3
BaseBackendService::~BaseBackendService() = default;
685
686
BackendService::BackendService(StorageEngine& engine, ExecEnv* exec_env)
687
6
        : BaseBackendService(exec_env), _engine(engine) {}
688
689
BackendService::~BackendService() = default;
690
691
Status BackendService::create_service(StorageEngine& engine, ExecEnv* exec_env, int port,
692
                                      std::unique_ptr<ThriftServer>* server,
693
6
                                      std::shared_ptr<doris::BackendService> service) {
694
6
    service->_agent_server->start_workers(engine, exec_env);
695
    // TODO: do we want a BoostThreadFactory?
696
    // TODO: we want separate thread factories here, so that fe requests can't starve
697
    // be requests
698
    // std::shared_ptr<TProcessor> be_processor = std::make_shared<BackendServiceProcessor>(service);
699
6
    auto be_processor = std::make_shared<BackendServiceProcessor>(service);
700
701
6
    *server = std::make_unique<ThriftServer>("backend", be_processor, port,
702
6
                                             config::be_service_threads);
703
704
6
    LOG(INFO) << "Doris BackendService listening on " << port;
705
706
6
    auto thread_num = config::ingest_binlog_work_pool_size;
707
6
    if (thread_num < 0) {
708
6
        LOG(INFO) << fmt::format("ingest binlog thread pool size is {}, so we will in sync mode",
709
6
                                 thread_num);
710
6
        return Status::OK();
711
6
    }
712
713
0
    if (thread_num == 0) {
714
0
        thread_num = std::thread::hardware_concurrency();
715
0
    }
716
0
    static_cast<void>(doris::ThreadPoolBuilder("IngestBinlog")
717
0
                              .set_min_threads(thread_num)
718
0
                              .set_max_threads(thread_num * 2)
719
0
                              .build(&(service->_ingest_binlog_workers)));
720
0
    LOG(INFO) << fmt::format("ingest binlog thread pool size is {}, in async mode", thread_num);
721
0
    return Status::OK();
722
6
}
723
724
159
void BackendService::get_tablet_stat(TTabletStatResult& result) {
725
159
    _engine.tablet_manager()->get_tablet_stat(&result);
726
159
}
727
728
0
int64_t BackendService::get_trash_used_capacity() {
729
0
    int64_t result = 0;
730
731
0
    std::vector<DataDirInfo> data_dir_infos;
732
0
    static_cast<void>(_engine.get_all_data_dir_info(&data_dir_infos, false /*do not update */));
733
734
    // uses excute sql `show trash`, then update backend trash capacity too.
735
0
    _engine.notify_listener("REPORT_DISK_STATE");
736
737
0
    for (const auto& root_path_info : data_dir_infos) {
738
0
        result += root_path_info.trash_used_capacity;
739
0
    }
740
741
0
    return result;
742
0
}
743
744
0
void BackendService::get_disk_trash_used_capacity(std::vector<TDiskTrashInfo>& diskTrashInfos) {
745
0
    std::vector<DataDirInfo> data_dir_infos;
746
0
    static_cast<void>(_engine.get_all_data_dir_info(&data_dir_infos, false /*do not update */));
747
748
    // uses excute sql `show trash on <be>`, then update backend trash capacity too.
749
0
    _engine.notify_listener("REPORT_DISK_STATE");
750
751
0
    for (const auto& root_path_info : data_dir_infos) {
752
0
        TDiskTrashInfo diskTrashInfo;
753
0
        diskTrashInfo.__set_root_path(root_path_info.path);
754
0
        diskTrashInfo.__set_state(root_path_info.is_used ? "ONLINE" : "OFFLINE");
755
0
        diskTrashInfo.__set_trash_used_capacity(root_path_info.trash_used_capacity);
756
0
        diskTrashInfos.push_back(diskTrashInfo);
757
0
    }
758
0
}
759
760
void BaseBackendService::submit_routine_load_task(TStatus& t_status,
761
70
                                                  const std::vector<TRoutineLoadTask>& tasks) {
762
70
    for (auto& task : tasks) {
763
70
        Status st = _exec_env->routine_load_task_executor()->submit_task(task);
764
70
        if (!st.ok()) {
765
0
            LOG(WARNING) << "failed to submit routine load task. job id: " << task.job_id
766
0
                         << " task id: " << task.id;
767
0
            return st.to_thrift(&t_status);
768
0
        }
769
70
    }
770
771
70
    return Status::OK().to_thrift(&t_status);
772
70
}
773
774
/*
775
 * 1. validate user privilege (todo)
776
 * 2. FragmentMgr#exec_plan_fragment
777
 */
778
3
void BaseBackendService::open_scanner(TScanOpenResult& result_, const TScanOpenParams& params) {
779
3
    TStatus t_status;
780
3
    TUniqueId fragment_instance_id = generate_uuid();
781
    // A query_id is randomly generated to replace t_query_plan_info.query_id.
782
    // external query does not need to report anything to FE, so the query_id can be changed.
783
    // Otherwise, multiple independent concurrent open tablet scanners have the same query_id.
784
    // when one of the scanners ends, the other scanners will be canceled through FragmentMgr.cancel(query_id).
785
3
    TUniqueId query_id = generate_uuid();
786
3
    std::shared_ptr<ScanContext> p_context;
787
3
    static_cast<void>(_exec_env->external_scan_context_mgr()->create_scan_context(&p_context));
788
3
    p_context->fragment_instance_id = fragment_instance_id;
789
3
    p_context->offset = 0;
790
3
    p_context->last_access_time = time(nullptr);
791
3
    if (params.__isset.keep_alive_min) {
792
0
        p_context->keep_alive_min = params.keep_alive_min;
793
3
    } else {
794
3
        p_context->keep_alive_min = 5;
795
3
    }
796
797
3
    Status exec_st;
798
3
    TQueryPlanInfo t_query_plan_info;
799
3
    {
800
3
        const std::string& opaqued_query_plan = params.opaqued_query_plan;
801
3
        std::string query_plan_info;
802
        // base64 decode query plan
803
3
        if (!base64_decode(opaqued_query_plan, &query_plan_info)) {
804
0
            LOG(WARNING) << "open context error: base64_decode decode opaqued_query_plan failure";
805
0
            std::stringstream msg;
806
0
            msg << "query_plan_info: " << query_plan_info
807
0
                << " validate error, should not be modified after returned Doris FE processed";
808
0
            exec_st = Status::InvalidArgument(msg.str());
809
0
        }
810
811
3
        const uint8_t* buf = (const uint8_t*)query_plan_info.data();
812
3
        uint32_t len = (uint32_t)query_plan_info.size();
813
        // deserialize TQueryPlanInfo
814
3
        auto st = deserialize_thrift_msg(buf, &len, false, &t_query_plan_info);
815
3
        if (!st.ok()) {
816
0
            LOG(WARNING) << "open context error: deserialize TQueryPlanInfo failure";
817
0
            std::stringstream msg;
818
0
            msg << "query_plan_info: " << query_plan_info
819
0
                << " deserialize error, should not be modified after returned Doris FE processed";
820
0
            exec_st = Status::InvalidArgument(msg.str());
821
0
        }
822
3
        p_context->query_id = query_id;
823
3
    }
824
3
    std::vector<TScanColumnDesc> selected_columns;
825
3
    if (exec_st.ok()) {
826
        // start the scan procedure
827
3
        LOG(INFO) << fmt::format(
828
3
                "exec external scanner, old_query_id = {}, new_query_id = {}, fragment_instance_id "
829
3
                "= {}",
830
3
                print_id(t_query_plan_info.query_id), print_id(query_id),
831
3
                print_id(fragment_instance_id));
832
3
        exec_st = _exec_env->fragment_mgr()->exec_external_plan_fragment(
833
3
                params, t_query_plan_info, query_id, fragment_instance_id, &selected_columns);
834
3
    }
835
3
    exec_st.to_thrift(&t_status);
836
    //return status
837
    // t_status.status_code = TStatusCode::OK;
838
3
    result_.status = t_status;
839
3
    result_.__set_context_id(p_context->context_id);
840
3
    result_.__set_selected_columns(selected_columns);
841
3
}
842
843
// fetch result from polling the queue, should always maintain the context offset, otherwise inconsistent result
844
5
void BaseBackendService::get_next(TScanBatchResult& result_, const TScanNextBatchParams& params) {
845
5
    std::string context_id = params.context_id;
846
5
    u_int64_t offset = params.offset;
847
5
    TStatus t_status;
848
5
    std::shared_ptr<ScanContext> context;
849
5
    Status st = _exec_env->external_scan_context_mgr()->get_scan_context(context_id, &context);
850
5
    if (!st.ok()) {
851
0
        st.to_thrift(&t_status);
852
0
        result_.status = t_status;
853
0
        return;
854
0
    }
855
5
    if (offset != context->offset) {
856
0
        LOG(ERROR) << "getNext error: context offset [" << context->offset << " ]"
857
0
                   << " ,client offset [ " << offset << " ]";
858
        // invalid offset
859
0
        t_status.status_code = TStatusCode::NOT_FOUND;
860
0
        t_status.error_msgs.push_back(
861
0
                absl::Substitute("context_id=$0, send_offset=$1, context_offset=$2", context_id,
862
0
                                 offset, context->offset));
863
0
        result_.status = t_status;
864
5
    } else {
865
        // during accessing, should disabled last_access_time
866
5
        context->last_access_time = -1;
867
5
        TUniqueId fragment_instance_id = context->fragment_instance_id;
868
5
        std::shared_ptr<arrow::RecordBatch> record_batch;
869
5
        bool eos;
870
871
5
        st = _exec_env->result_queue_mgr()->fetch_result(fragment_instance_id, &record_batch, &eos);
872
5
        if (st.ok()) {
873
5
            result_.__set_eos(eos);
874
5
            if (!eos) {
875
3
                std::string record_batch_str;
876
3
                st = serialize_record_batch(*record_batch, &record_batch_str);
877
3
                st.to_thrift(&t_status);
878
3
                if (st.ok()) {
879
                    // avoid copy large string
880
3
                    result_.rows = std::move(record_batch_str);
881
                    // set __isset
882
3
                    result_.__isset.rows = true;
883
3
                    context->offset += record_batch->num_rows();
884
3
                }
885
3
            }
886
5
        } else {
887
0
            LOG(WARNING) << "fragment_instance_id [" << print_id(fragment_instance_id)
888
0
                         << "] fetch result status [" << st.to_string() + "]";
889
0
            st.to_thrift(&t_status);
890
0
            result_.status = t_status;
891
0
        }
892
5
    }
893
5
    context->last_access_time = time(nullptr);
894
5
}
895
896
2
void BaseBackendService::close_scanner(TScanCloseResult& result_, const TScanCloseParams& params) {
897
2
    std::string context_id = params.context_id;
898
2
    TStatus t_status;
899
2
    Status st = _exec_env->external_scan_context_mgr()->clear_scan_context(context_id);
900
2
    st.to_thrift(&t_status);
901
2
    result_.status = t_status;
902
2
}
903
904
void BackendService::get_stream_load_record(TStreamLoadRecordResult& result,
905
79
                                            int64_t last_stream_record_time) {
906
79
    BaseBackendService::get_stream_load_record(result, last_stream_record_time,
907
79
                                               _engine.get_stream_load_recorder());
908
79
}
909
910
0
void BackendService::check_storage_format(TCheckStorageFormatResult& result) {
911
0
    _engine.tablet_manager()->get_all_tablets_storage_format(&result);
912
0
}
913
914
void BackendService::make_snapshot(TAgentResult& return_value,
915
0
                                   const TSnapshotRequest& snapshot_request) {
916
0
    std::string snapshot_path;
917
0
    bool allow_incremental_clone = false;
918
0
    Status status = _engine.snapshot_mgr()->make_snapshot(snapshot_request, &snapshot_path,
919
0
                                                          &allow_incremental_clone);
920
0
    if (!status) {
921
0
        LOG_WARNING("failed to make snapshot")
922
0
                .tag("tablet_id", snapshot_request.tablet_id)
923
0
                .tag("schema_hash", snapshot_request.schema_hash)
924
0
                .error(status);
925
0
    } else {
926
0
        LOG_INFO("successfully make snapshot")
927
0
                .tag("tablet_id", snapshot_request.tablet_id)
928
0
                .tag("schema_hash", snapshot_request.schema_hash)
929
0
                .tag("snapshot_path", snapshot_path);
930
0
        return_value.__set_snapshot_path(snapshot_path);
931
0
        return_value.__set_allow_incremental_clone(allow_incremental_clone);
932
0
    }
933
934
0
    status.to_thrift(&return_value.status);
935
0
    return_value.__set_snapshot_version(snapshot_request.preferred_snapshot_version);
936
0
}
937
938
void BackendService::release_snapshot(TAgentResult& return_value,
939
0
                                      const std::string& snapshot_path) {
940
0
    Status status = _engine.snapshot_mgr()->release_snapshot(snapshot_path);
941
0
    if (!status) {
942
0
        LOG_WARNING("failed to release snapshot").tag("snapshot_path", snapshot_path).error(status);
943
0
    } else {
944
0
        LOG_INFO("successfully release snapshot").tag("snapshot_path", snapshot_path);
945
0
    }
946
0
    status.to_thrift(&return_value.status);
947
0
}
948
949
void BackendService::ingest_binlog(TIngestBinlogResult& result,
950
0
                                   const TIngestBinlogRequest& request) {
951
0
    LOG(INFO) << "ingest binlog. request: " << apache::thrift::ThriftDebugString(request);
952
953
0
    TStatus tstatus;
954
0
    Defer defer {[&result, &tstatus]() {
955
0
        result.__set_status(tstatus);
956
0
        LOG(INFO) << "ingest binlog. result: " << apache::thrift::ThriftDebugString(result);
957
0
    }};
958
959
0
    auto set_tstatus = [&tstatus](TStatusCode::type code, std::string error_msg) {
960
0
        tstatus.__set_status_code(code);
961
0
        tstatus.__isset.error_msgs = true;
962
0
        tstatus.error_msgs.push_back(std::move(error_msg));
963
0
    };
964
965
0
    if (!config::enable_feature_binlog) {
966
0
        set_tstatus(TStatusCode::RUNTIME_ERROR, "enable feature binlog is false");
967
0
        return;
968
0
    }
969
970
    /// Check args: txn_id, remote_tablet_id, binlog_version, remote_host, remote_port, partition_id, load_id
971
0
    if (!request.__isset.txn_id) {
972
0
        auto error_msg = "txn_id 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_tablet_id) {
978
0
        auto error_msg = "remote_tablet_id 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.binlog_version) {
984
0
        auto error_msg = "binlog_version 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.remote_host) {
990
0
        auto error_msg = "remote_host 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.remote_port) {
996
0
        auto error_msg = "remote_port 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.partition_id) {
1002
0
        auto error_msg = "partition_id is empty";
1003
0
        LOG(WARNING) << error_msg;
1004
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
1005
0
        return;
1006
0
    }
1007
0
    if (!request.__isset.local_tablet_id) {
1008
0
        auto error_msg = "local_tablet_id is empty";
1009
0
        LOG(WARNING) << error_msg;
1010
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
1011
0
        return;
1012
0
    }
1013
0
    if (!request.__isset.load_id) {
1014
0
        auto error_msg = "load_id is empty";
1015
0
        LOG(WARNING) << error_msg;
1016
0
        set_tstatus(TStatusCode::ANALYSIS_ERROR, error_msg);
1017
0
        return;
1018
0
    }
1019
1020
0
    auto txn_id = request.txn_id;
1021
    // Step 1: get local tablet
1022
0
    auto const& local_tablet_id = request.local_tablet_id;
1023
0
    auto local_tablet = _engine.tablet_manager()->get_tablet(local_tablet_id);
1024
0
    if (local_tablet == nullptr) {
1025
0
        auto error_msg = fmt::format("tablet {} not found", local_tablet_id);
1026
0
        LOG(WARNING) << error_msg;
1027
0
        set_tstatus(TStatusCode::TABLET_MISSING, std::move(error_msg));
1028
0
        return;
1029
0
    }
1030
1031
    // Step 2: check txn, create txn, prepare_txn will check it
1032
0
    auto partition_id = request.partition_id;
1033
0
    auto& load_id = request.load_id;
1034
0
    auto is_ingrest = true;
1035
0
    PUniqueId p_load_id;
1036
0
    p_load_id.set_hi(load_id.hi);
1037
0
    p_load_id.set_lo(load_id.lo);
1038
1039
0
    {
1040
        // TODO: Before push_lock is not held, but I think it should hold.
1041
0
        auto status = local_tablet->prepare_txn(partition_id, txn_id, p_load_id, is_ingrest);
1042
0
        if (!status.ok()) {
1043
0
            LOG(WARNING) << "prepare txn failed. txn_id=" << txn_id
1044
0
                         << ", status=" << status.to_string();
1045
0
            status.to_thrift(&tstatus);
1046
0
            return;
1047
0
        }
1048
0
    }
1049
1050
0
    bool is_async = (_ingest_binlog_workers != nullptr);
1051
0
    result.__set_is_async(is_async);
1052
1053
0
    auto ingest_binlog_func = [=, this, tstatus = &tstatus]() {
1054
0
        IngestBinlogArg ingest_binlog_arg = {
1055
0
                .txn_id = txn_id,
1056
0
                .partition_id = partition_id,
1057
0
                .local_tablet_id = local_tablet_id,
1058
0
                .local_tablet = local_tablet,
1059
1060
0
                .request = request,
1061
0
                .tstatus = is_async ? nullptr : tstatus,
1062
0
        };
1063
1064
0
        _ingest_binlog(_engine, &ingest_binlog_arg);
1065
0
    };
1066
1067
0
    if (is_async) {
1068
0
        auto status = _ingest_binlog_workers->submit_func(std::move(ingest_binlog_func));
1069
0
        if (!status.ok()) {
1070
0
            status.to_thrift(&tstatus);
1071
0
            return;
1072
0
        }
1073
0
    } else {
1074
0
        ingest_binlog_func();
1075
0
    }
1076
0
}
1077
1078
void BackendService::query_ingest_binlog(TQueryIngestBinlogResult& result,
1079
0
                                         const TQueryIngestBinlogRequest& request) {
1080
0
    LOG(INFO) << "query ingest binlog. request: " << apache::thrift::ThriftDebugString(request);
1081
1082
0
    auto set_result = [&](TIngestBinlogStatus::type status, std::string error_msg) {
1083
0
        result.__set_status(status);
1084
0
        result.__set_err_msg(std::move(error_msg));
1085
0
    };
1086
1087
    /// Check args: txn_id, partition_id, tablet_id, load_id
1088
0
    if (!request.__isset.txn_id) {
1089
0
        auto error_msg = "txn_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.partition_id) {
1095
0
        auto error_msg = "partition_id is empty";
1096
0
        LOG(WARNING) << error_msg;
1097
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1098
0
        return;
1099
0
    }
1100
0
    if (!request.__isset.tablet_id) {
1101
0
        auto error_msg = "tablet_id is empty";
1102
0
        LOG(WARNING) << error_msg;
1103
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1104
0
        return;
1105
0
    }
1106
0
    if (!request.__isset.load_id) {
1107
0
        auto error_msg = "load_id is empty";
1108
0
        LOG(WARNING) << error_msg;
1109
0
        set_result(TIngestBinlogStatus::ANALYSIS_ERROR, error_msg);
1110
0
        return;
1111
0
    }
1112
1113
0
    auto partition_id = request.partition_id;
1114
0
    auto txn_id = request.txn_id;
1115
0
    auto tablet_id = request.tablet_id;
1116
1117
    // Step 1: get local tablet
1118
0
    auto local_tablet = _engine.tablet_manager()->get_tablet(tablet_id);
1119
0
    if (local_tablet == nullptr) {
1120
0
        auto error_msg = fmt::format("tablet {} not found", tablet_id);
1121
0
        LOG(WARNING) << error_msg;
1122
0
        set_result(TIngestBinlogStatus::NOT_FOUND, std::move(error_msg));
1123
0
        return;
1124
0
    }
1125
1126
    // Step 2: get txn state
1127
0
    auto tablet_uid = local_tablet->tablet_uid();
1128
0
    auto txn_state =
1129
0
            _engine.txn_manager()->get_txn_state(partition_id, txn_id, tablet_id, tablet_uid);
1130
0
    switch (txn_state) {
1131
0
    case TxnState::NOT_FOUND:
1132
0
        result.__set_status(TIngestBinlogStatus::NOT_FOUND);
1133
0
        break;
1134
0
    case TxnState::PREPARED:
1135
0
        result.__set_status(TIngestBinlogStatus::DOING);
1136
0
        break;
1137
0
    case TxnState::COMMITTED:
1138
0
        result.__set_status(TIngestBinlogStatus::OK);
1139
0
        break;
1140
0
    case TxnState::ROLLEDBACK:
1141
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1142
0
        break;
1143
0
    case TxnState::ABORTED:
1144
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1145
0
        break;
1146
0
    case TxnState::DELETED:
1147
0
        result.__set_status(TIngestBinlogStatus::FAILED);
1148
0
        break;
1149
0
    }
1150
0
}
1151
1152
0
void BaseBackendService::get_tablet_stat(TTabletStatResult& result) {
1153
0
    LOG(ERROR) << "get_tablet_stat is not implemented";
1154
0
}
1155
1156
3
int64_t BaseBackendService::get_trash_used_capacity() {
1157
3
    LOG(ERROR) << "get_trash_used_capacity is not implemented";
1158
3
    return 0;
1159
3
}
1160
1161
void BaseBackendService::get_stream_load_record(TStreamLoadRecordResult& result,
1162
0
                                                int64_t last_stream_record_time) {
1163
0
    LOG(ERROR) << "get_stream_load_record is not implemented";
1164
0
}
1165
1166
void BaseBackendService::get_stream_load_record(
1167
        TStreamLoadRecordResult& result, int64_t last_stream_record_time,
1168
109
        std::shared_ptr<StreamLoadRecorder> stream_load_recorder) {
1169
109
    if (stream_load_recorder != nullptr) {
1170
109
        std::map<std::string, std::string> records;
1171
109
        auto st = stream_load_recorder->get_batch(std::to_string(last_stream_record_time),
1172
109
                                                  config::stream_load_record_batch_size, &records);
1173
109
        if (st.ok()) {
1174
109
            LOG(INFO) << "get_batch stream_load_record rocksdb successfully. records size: "
1175
109
                      << records.size()
1176
109
                      << ", last_stream_load_timestamp: " << last_stream_record_time;
1177
109
            std::map<std::string, TStreamLoadRecord> stream_load_record_batch;
1178
109
            auto it = records.begin();
1179
2.35k
            for (; it != records.end(); ++it) {
1180
2.24k
                TStreamLoadRecord stream_load_item;
1181
2.24k
                StreamLoadContext::parse_stream_load_record(it->second, stream_load_item);
1182
2.24k
                stream_load_record_batch.emplace(it->first.c_str(), stream_load_item);
1183
2.24k
            }
1184
109
            result.__set_stream_load_record(stream_load_record_batch);
1185
109
        }
1186
109
    } else {
1187
0
        LOG(WARNING) << "stream_load_recorder is null.";
1188
0
    }
1189
109
}
1190
1191
0
void BaseBackendService::get_disk_trash_used_capacity(std::vector<TDiskTrashInfo>& diskTrashInfos) {
1192
0
    LOG(ERROR) << "get_disk_trash_used_capacity is not implemented";
1193
0
}
1194
1195
void BaseBackendService::make_snapshot(TAgentResult& return_value,
1196
0
                                       const TSnapshotRequest& snapshot_request) {
1197
0
    LOG(ERROR) << "make_snapshot is not implemented";
1198
0
    return_value.__set_status(Status::NotSupported("make_snapshot is not implemented").to_thrift());
1199
0
}
1200
1201
void BaseBackendService::release_snapshot(TAgentResult& return_value,
1202
0
                                          const std::string& snapshot_path) {
1203
0
    LOG(ERROR) << "release_snapshot is not implemented";
1204
0
    return_value.__set_status(
1205
0
            Status::NotSupported("release_snapshot is not implemented").to_thrift());
1206
0
}
1207
1208
0
void BaseBackendService::check_storage_format(TCheckStorageFormatResult& result) {
1209
0
    LOG(ERROR) << "check_storage_format is not implemented";
1210
0
}
1211
1212
void BaseBackendService::ingest_binlog(TIngestBinlogResult& result,
1213
0
                                       const TIngestBinlogRequest& request) {
1214
0
    LOG(ERROR) << "ingest_binlog is not implemented";
1215
0
    result.__set_status(Status::NotSupported("ingest_binlog is not implemented").to_thrift());
1216
0
}
1217
1218
void BaseBackendService::query_ingest_binlog(TQueryIngestBinlogResult& result,
1219
0
                                             const TQueryIngestBinlogRequest& request) {
1220
0
    LOG(ERROR) << "query_ingest_binlog is not implemented";
1221
0
    result.__set_status(TIngestBinlogStatus::UNKNOWN);
1222
0
    result.__set_err_msg("query_ingest_binlog is not implemented");
1223
0
}
1224
1225
void BaseBackendService::warm_up_cache_async(TWarmUpCacheAsyncResponse& response,
1226
0
                                             const TWarmUpCacheAsyncRequest& request) {
1227
0
    LOG(ERROR) << "warm_up_cache_async is not implemented";
1228
0
    response.__set_status(
1229
0
            Status::NotSupported("warm_up_cache_async is not implemented").to_thrift());
1230
0
}
1231
1232
void BaseBackendService::check_warm_up_cache_async(TCheckWarmUpCacheAsyncResponse& response,
1233
0
                                                   const TCheckWarmUpCacheAsyncRequest& request) {
1234
0
    LOG(ERROR) << "check_warm_up_cache_async is not implemented";
1235
0
    response.__set_status(
1236
0
            Status::NotSupported("check_warm_up_cache_async is not implemented").to_thrift());
1237
0
}
1238
1239
void BaseBackendService::sync_load_for_tablets(TSyncLoadForTabletsResponse& response,
1240
0
                                               const TSyncLoadForTabletsRequest& request) {
1241
0
    LOG(ERROR) << "sync_load_for_tablets is not implemented";
1242
0
}
1243
1244
void BaseBackendService::get_top_n_hot_partitions(TGetTopNHotPartitionsResponse& response,
1245
0
                                                  const TGetTopNHotPartitionsRequest& request) {
1246
0
    LOG(ERROR) << "get_top_n_hot_partitions is not implemented";
1247
0
}
1248
1249
void BaseBackendService::warm_up_tablets(TWarmUpTabletsResponse& response,
1250
0
                                         const TWarmUpTabletsRequest& request) {
1251
0
    LOG(ERROR) << "warm_up_tablets is not implemented";
1252
0
    response.__set_status(Status::NotSupported("warm_up_tablets is not implemented").to_thrift());
1253
0
}
1254
1255
void BaseBackendService::get_realtime_exec_status(TGetRealtimeExecStatusResponse& response,
1256
1
                                                  const TGetRealtimeExecStatusRequest& request) {
1257
1
    if (!request.__isset.id) {
1258
0
        LOG_WARNING("Invalidate argument, id is empty");
1259
0
        response.__set_status(Status::InvalidArgument("id is empty").to_thrift());
1260
0
        return;
1261
0
    }
1262
1263
1
    RuntimeProfile::Counter get_realtime_timer {TUnit::TIME_NS};
1264
1265
1
    Defer _print_log([&]() {
1266
1
        LOG_INFO("Getting realtime exec status of query {} , cost time {}", print_id(request.id),
1267
1
                 PrettyPrinter::print(get_realtime_timer.value(), get_realtime_timer.type()));
1268
1
    });
1269
1270
1
    SCOPED_TIMER(&get_realtime_timer);
1271
1272
1
    std::unique_ptr<TReportExecStatusParams> report_exec_status_params =
1273
1
            std::make_unique<TReportExecStatusParams>();
1274
1
    std::unique_ptr<TQueryStatistics> query_stats = std::make_unique<TQueryStatistics>();
1275
1276
1
    std::string req_type = request.__isset.req_type ? request.req_type : "profile";
1277
1
    Status st;
1278
1
    if (req_type == "stats") {
1279
1
        st = ExecEnv::GetInstance()->fragment_mgr()->get_query_statistics(request.id,
1280
1
                                                                          query_stats.get());
1281
1
        if (st.ok()) {
1282
1
            response.__set_query_stats(*query_stats);
1283
1
        }
1284
1
    } else {
1285
        // default is "profile"
1286
0
        st = ExecEnv::GetInstance()->fragment_mgr()->get_realtime_exec_status(
1287
0
                request.id, report_exec_status_params.get());
1288
0
        if (st.ok()) {
1289
0
            response.__set_report_exec_status_params(*report_exec_status_params);
1290
0
        }
1291
0
    }
1292
1293
1
    report_exec_status_params->__set_query_id(TUniqueId());
1294
1
    report_exec_status_params->__set_done(false);
1295
1
    response.__set_status(st.to_thrift());
1296
1
}
1297
1298
void BaseBackendService::get_dictionary_status(TDictionaryStatusList& result,
1299
2.66k
                                               const std::vector<int64_t>& dictionary_ids) {
1300
2.66k
    std::vector<TDictionaryStatus> dictionary_status;
1301
2.66k
    ExecEnv::GetInstance()->dict_factory()->get_dictionary_status(dictionary_status,
1302
2.66k
                                                                  dictionary_ids);
1303
2.66k
    result.__set_dictionary_status_list(dictionary_status);
1304
2.66k
    LOG(INFO) << "query for dictionary status, return " << result.dictionary_status_list.size()
1305
2.66k
              << " rows";
1306
2.66k
}
1307
1308
void BaseBackendService::test_storage_connectivity(TTestStorageConnectivityResponse& response,
1309
2
                                                   const TTestStorageConnectivityRequest& request) {
1310
2
    Status status = io::StorageConnectivityTester::test(request.type, request.properties);
1311
2
    response.__set_status(status.to_thrift());
1312
2
}
1313
1314
2
void BaseBackendService::get_python_envs(std::vector<TPythonEnvInfo>& result) {
1315
2
    result = PythonVersionManager::instance().env_infos_to_thrift();
1316
2
}
1317
1318
void BaseBackendService::get_python_packages(std::vector<TPythonPackageInfo>& result,
1319
1
                                             const std::string& python_version) {
1320
1
    PythonVersion version;
1321
1
    auto& manager = PythonVersionManager::instance();
1322
1
    THROW_IF_ERROR(manager.get_version(python_version, &version));
1323
1324
1
    std::vector<std::pair<std::string, std::string>> packages;
1325
1
    THROW_IF_ERROR(list_installed_packages(version, &packages));
1326
1
    result = manager.package_infos_to_thrift(packages);
1327
1
}
1328
1329
} // namespace doris