Coverage Report

Created: 2026-07-04 04:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/service/internal_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/internal_service.h"
19
20
#include <assert.h>
21
#include <brpc/closure_guard.h>
22
#include <brpc/controller.h>
23
#include <bthread/bthread.h>
24
#include <bthread/types.h>
25
#include <butil/errno.h>
26
#include <butil/iobuf.h>
27
#include <fcntl.h>
28
#include <fmt/core.h>
29
#include <gen_cpp/DataSinks_types.h>
30
#include <gen_cpp/MasterService_types.h>
31
#include <gen_cpp/PaloInternalService_types.h>
32
#include <gen_cpp/PlanNodes_types.h>
33
#include <gen_cpp/Status_types.h>
34
#include <gen_cpp/Types_types.h>
35
#include <gen_cpp/internal_service.pb.h>
36
#include <gen_cpp/olap_file.pb.h>
37
#include <gen_cpp/segment_v2.pb.h>
38
#include <gen_cpp/types.pb.h>
39
#include <google/protobuf/stubs/callback.h>
40
#include <stddef.h>
41
#include <stdint.h>
42
#include <sys/stat.h>
43
44
#include <algorithm>
45
#include <exception>
46
#include <filesystem>
47
#include <memory>
48
#include <set>
49
#include <sstream>
50
#include <string>
51
#include <utility>
52
#include <vector>
53
54
#include "cloud/cloud_storage_engine.h"
55
#include "cloud/cloud_tablet_mgr.h"
56
#include "cloud/config.h"
57
#include "common/config.h"
58
#include "common/exception.h"
59
#include "common/logging.h"
60
#include "common/metrics/doris_metrics.h"
61
#include "common/metrics/metrics.h"
62
#include "common/signal_handler.h"
63
#include "common/status.h"
64
#include "core/block/block.h"
65
#include "core/data_type/data_type.h"
66
#include "exec/common/variant_util.h"
67
#include "exec/exchange/vdata_stream_mgr.h"
68
#include "exec/rowid_fetcher.h"
69
#include "exec/runtime_filter/runtime_filter_mgr.h"
70
#include "exec/sink/writer/varrow_flight_result_writer.h"
71
#include "exec/sink/writer/vmysql_result_writer.h"
72
#include "exprs/function/dictionary_factory.h"
73
#include "format/arrow/arrow_row_batch.h"
74
#include "format/csv/csv_reader.h"
75
#include "format/generic_reader.h"
76
#include "format/jni/jni_reader.h"
77
#include "format/json/new_json_reader.h"
78
#include "format/native/native_reader.h"
79
#include "format/orc/vorc_reader.h"
80
#include "format/parquet/vparquet_reader.h"
81
#include "format/text/text_reader.h"
82
#ifdef BUILD_RUST_READERS
83
#include "format/lance/lance_rust_reader.h"
84
#endif
85
#include "io/fs/local_file_system.h"
86
#include "io/fs/stream_load_pipe.h"
87
#include "io/io_common.h"
88
#include "load/channel/load_channel_mgr.h"
89
#include "load/channel/load_stream_mgr.h"
90
#include "load/delta_writer/delta_writer.h"
91
#include "load/group_commit/wal/wal_manager.h"
92
#include "load/routine_load/routine_load_task_executor.h"
93
#include "load/stream_load/new_load_stream_mgr.h"
94
#include "load/stream_load/stream_load_context.h"
95
#include "runtime/cache/result_cache.h"
96
#include "runtime/cdc_client_mgr.h"
97
#include "runtime/descriptors.h"
98
#include "runtime/exec_env.h"
99
#include "runtime/fold_constant_executor.h"
100
#include "runtime/fragment_mgr.h"
101
#include "runtime/query_context.h"
102
#include "runtime/result_block_buffer.h"
103
#include "runtime/result_buffer_mgr.h"
104
#include "runtime/runtime_profile.h"
105
#include "runtime/thread_context.h"
106
#include "runtime/workload_group/workload_group.h"
107
#include "runtime/workload_group/workload_group_manager.h"
108
#include "service/backend_options.h"
109
#include "service/http/http_client.h"
110
#include "service/point_query_executor.h"
111
#include "storage/data_dir.h"
112
#include "storage/index/inverted/inverted_index_desc.h"
113
#include "storage/olap_common.h"
114
#include "storage/olap_define.h"
115
#include "storage/rowset/beta_rowset.h"
116
#include "storage/rowset/rowset.h"
117
#include "storage/rowset/rowset_factory.h"
118
#include "storage/rowset/rowset_meta.h"
119
#include "storage/segment/column_reader.h"
120
#include "storage/storage_engine.h"
121
#include "storage/tablet/tablet_fwd.h"
122
#include "storage/tablet/tablet_manager.h"
123
#include "storage/tablet/tablet_schema.h"
124
#include "storage/txn/txn_manager.h"
125
#include "util/async_io.h"
126
#include "util/brpc_client_cache.h"
127
#include "util/brpc_closure.h"
128
#include "util/jdbc_utils.h"
129
#include "util/jsonb/serialize.h"
130
#include "util/md5.h"
131
#include "util/network_util.h"
132
#include "util/proto_util.h"
133
#include "util/stopwatch.hpp"
134
#include "util/string_util.h"
135
#include "util/thrift_util.h"
136
#include "util/time.h"
137
#include "util/uid_util.h"
138
139
namespace google {
140
namespace protobuf {
141
class RpcController;
142
} // namespace protobuf
143
} // namespace google
144
145
namespace doris {
146
#include "common/compile_check_avoid_begin.h"
147
using namespace ErrorCode;
148
149
const uint32_t DOWNLOAD_FILE_MAX_RETRY = 3;
150
151
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(heavy_work_pool_queue_size, MetricUnit::NOUNIT);
152
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(peer_fetch_work_pool_queue_size, MetricUnit::NOUNIT);
153
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(light_work_pool_queue_size, MetricUnit::NOUNIT);
154
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(heavy_work_active_threads, MetricUnit::NOUNIT);
155
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(peer_fetch_work_active_threads, MetricUnit::NOUNIT);
156
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(light_work_active_threads, MetricUnit::NOUNIT);
157
158
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(heavy_work_pool_max_queue_size, MetricUnit::NOUNIT);
159
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(peer_fetch_work_pool_max_queue_size, MetricUnit::NOUNIT);
160
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(light_work_pool_max_queue_size, MetricUnit::NOUNIT);
161
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(heavy_work_max_threads, MetricUnit::NOUNIT);
162
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(peer_fetch_work_max_threads, MetricUnit::NOUNIT);
163
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(light_work_max_threads, MetricUnit::NOUNIT);
164
165
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(arrow_flight_work_pool_queue_size, MetricUnit::NOUNIT);
166
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(arrow_flight_work_active_threads, MetricUnit::NOUNIT);
167
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(arrow_flight_work_pool_max_queue_size, MetricUnit::NOUNIT);
168
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(arrow_flight_work_max_threads, MetricUnit::NOUNIT);
169
170
static bvar::LatencyRecorder g_process_remote_fetch_rowsets_latency("process_remote_fetch_rowsets");
171
172
bthread_key_t btls_key;
173
174
0
static void thread_context_deleter(void* d) {
175
0
    delete static_cast<ThreadContext*>(d);
176
0
}
177
178
0
static int32_t resolved_brpc_peer_fetch_pool_threads() {
179
0
    return config::brpc_peer_fetch_pool_threads != -1 ? config::brpc_peer_fetch_pool_threads
180
0
                                                      : std::max(64, CpuInfo::num_cores() * 2);
181
0
}
182
183
0
static int32_t resolved_brpc_peer_fetch_pool_max_queue_size() {
184
0
    return config::brpc_peer_fetch_pool_max_queue_size != -1
185
0
                   ? config::brpc_peer_fetch_pool_max_queue_size
186
0
                   : std::max(4096, CpuInfo::num_cores() * 128);
187
0
}
188
189
template <typename T>
190
concept CanCancel = requires(T* response) { response->mutable_status(); };
191
192
template <typename T>
193
0
void offer_failed(T* response, google::protobuf::Closure* done, const FifoThreadPool& pool) {
194
0
    brpc::ClosureGuard closure_guard(done);
195
0
    LOG(WARNING) << "fail to offer request to the work pool, pool=" << pool.get_info();
196
0
}
Unexecuted instantiation: _ZN5doris12offer_failedINS_25PTabletWriterCancelResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedINS_14PCacheResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedINS_17PFetchCacheResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
197
198
template <CanCancel T>
199
0
void offer_failed(T* response, google::protobuf::Closure* done, const FifoThreadPool& pool) {
200
0
    brpc::ClosureGuard closure_guard(done);
201
    // Should use status to generate protobuf message, because it will encoding Backend Info
202
    // into the error message and then we could know which backend's pool is full.
203
0
    Status st = Status::Error<TStatusCode::CANCELLED>(
204
0
            "fail to offer request to the work pool, pool={}", pool.get_info());
205
0
    st.to_protobuf(response->mutable_status());
206
0
    LOG(WARNING) << "cancelled due to fail to offer request to the work pool, pool="
207
0
                 << pool.get_info();
208
0
}
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PTabletWriterOpenResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PExecPlanFragmentResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23POpenLoadStreamResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_27PTabletWriterAddBlockResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_25PCancelPlanFragmentResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_21PFetchArrowDataResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_26POutfileWriteSuccessResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PFetchTableSchemaResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_29PFetchArrowFlightSchemaResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_24PTabletKeyLookupResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_25PJdbcTestConnectionResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_20PFetchColIdsResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_26PFetchRemoteSchemaResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_12PProxyResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_20PMergeFilterResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PSendFilterSizeResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PSyncFilterSizeResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_22PPublishFilterResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_15PSendDataResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_13PCommitResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_15PRollbackResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_19PConstantExprResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_26PTransmitRecCTEBlockResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_20PRerunFragmentResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_20PResetGlobalRfResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_19PTransmitDataResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_24PCheckRPCChannelResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_24PResetRPCChannelResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PTabletWriteSlaveResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_27PTabletWriteSlaveDoneResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_17PMultiGetResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_13PGlobResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_26PGroupCommitInsertResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_24PGetWalQueueSizeResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_22PGetBeResourceResponseEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
Unexecuted instantiation: _ZN5doris12offer_failedITkNS_9CanCancelENS_23PRequestCdcClientResultEEEvPT_PN6google8protobuf7ClosureERKNS_14WorkThreadPoolILb0EEE
209
210
template <typename T>
211
class NewHttpClosure : public ::google::protobuf::Closure {
212
public:
213
    NewHttpClosure(google::protobuf::Closure* done) : _done(done) {}
214
0
    NewHttpClosure(T* request, google::protobuf::Closure* done) : _request(request), _done(done) {}
Unexecuted instantiation: _ZN5doris14NewHttpClosureINS_28PTabletWriterAddBlockRequestEEC2EPS1_PN6google8protobuf7ClosureE
Unexecuted instantiation: _ZN5doris14NewHttpClosureINS_19PTransmitDataParamsEEC2EPS1_PN6google8protobuf7ClosureE
215
216
0
    void Run() override {
217
0
        if (_request != nullptr) {
218
0
            delete _request;
219
0
            _request = nullptr;
220
0
        }
221
0
        if (_done != nullptr) {
222
0
            _done->Run();
223
0
        }
224
0
        delete this;
225
0
    }
Unexecuted instantiation: _ZN5doris14NewHttpClosureINS_28PTabletWriterAddBlockRequestEE3RunEv
Unexecuted instantiation: _ZN5doris14NewHttpClosureINS_19PTransmitDataParamsEE3RunEv
226
227
private:
228
    T* _request = nullptr;
229
    google::protobuf::Closure* _done = nullptr;
230
};
231
232
PInternalService::PInternalService(ExecEnv* exec_env)
233
0
        : _exec_env(exec_env),
234
          // heavy threadpool is used for load process and other process that will read disk or access network.
235
0
          _heavy_work_pool(config::brpc_heavy_work_pool_threads != -1
236
0
                                   ? config::brpc_heavy_work_pool_threads
237
0
                                   : std::max(128, CpuInfo::num_cores() * 4),
238
0
                           config::brpc_heavy_work_pool_max_queue_size != -1
239
0
                                   ? config::brpc_heavy_work_pool_max_queue_size
240
0
                                   : std::max(10240, CpuInfo::num_cores() * 320),
241
0
                           "brpc_heavy"),
242
          // peer fetch threadpool isolates fetch_peer_data from heavy load traffic to avoid peer reads starving imports.
243
0
          _peer_fetch_pool(resolved_brpc_peer_fetch_pool_threads(),
244
0
                           resolved_brpc_peer_fetch_pool_max_queue_size(), "brpc_peer_fetch"),
245
246
          // light threadpool should be only used in query processing logic. All hanlers should be very light, not locked, not access disk.
247
0
          _light_work_pool(config::brpc_light_work_pool_threads != -1
248
0
                                   ? config::brpc_light_work_pool_threads
249
0
                                   : std::max(128, CpuInfo::num_cores() * 4),
250
0
                           config::brpc_light_work_pool_max_queue_size != -1
251
0
                                   ? config::brpc_light_work_pool_max_queue_size
252
0
                                   : std::max(10240, CpuInfo::num_cores() * 320),
253
0
                           "brpc_light"),
254
0
          _arrow_flight_work_pool(config::brpc_arrow_flight_work_pool_threads != -1
255
0
                                          ? config::brpc_arrow_flight_work_pool_threads
256
0
                                          : std::max(512, CpuInfo::num_cores() * 2),
257
0
                                  config::brpc_arrow_flight_work_pool_max_queue_size != -1
258
0
                                          ? config::brpc_arrow_flight_work_pool_max_queue_size
259
0
                                          : std::max(20480, CpuInfo::num_cores() * 640),
260
0
                                  "brpc_arrow_flight") {
261
0
    REGISTER_HOOK_METRIC(heavy_work_pool_queue_size,
262
0
                         [this]() { return _heavy_work_pool.get_queue_size(); });
263
0
    REGISTER_HOOK_METRIC(peer_fetch_work_pool_queue_size,
264
0
                         [this]() { return _peer_fetch_pool.get_queue_size(); });
265
0
    REGISTER_HOOK_METRIC(light_work_pool_queue_size,
266
0
                         [this]() { return _light_work_pool.get_queue_size(); });
267
0
    REGISTER_HOOK_METRIC(heavy_work_active_threads,
268
0
                         [this]() { return _heavy_work_pool.get_active_threads(); });
269
0
    REGISTER_HOOK_METRIC(peer_fetch_work_active_threads,
270
0
                         [this]() { return _peer_fetch_pool.get_active_threads(); });
271
0
    REGISTER_HOOK_METRIC(light_work_active_threads,
272
0
                         [this]() { return _light_work_pool.get_active_threads(); });
273
274
0
    REGISTER_HOOK_METRIC(heavy_work_pool_max_queue_size,
275
0
                         []() { return config::brpc_heavy_work_pool_max_queue_size; });
276
0
    REGISTER_HOOK_METRIC(peer_fetch_work_pool_max_queue_size,
277
0
                         []() { return resolved_brpc_peer_fetch_pool_max_queue_size(); });
278
0
    REGISTER_HOOK_METRIC(light_work_pool_max_queue_size,
279
0
                         []() { return config::brpc_light_work_pool_max_queue_size; });
280
0
    REGISTER_HOOK_METRIC(heavy_work_max_threads,
281
0
                         []() { return config::brpc_heavy_work_pool_threads; });
282
0
    REGISTER_HOOK_METRIC(peer_fetch_work_max_threads,
283
0
                         []() { return resolved_brpc_peer_fetch_pool_threads(); });
284
0
    REGISTER_HOOK_METRIC(light_work_max_threads,
285
0
                         []() { return config::brpc_light_work_pool_threads; });
286
287
0
    REGISTER_HOOK_METRIC(arrow_flight_work_pool_queue_size,
288
0
                         [this]() { return _arrow_flight_work_pool.get_queue_size(); });
289
0
    REGISTER_HOOK_METRIC(arrow_flight_work_active_threads,
290
0
                         [this]() { return _arrow_flight_work_pool.get_active_threads(); });
291
0
    REGISTER_HOOK_METRIC(arrow_flight_work_pool_max_queue_size,
292
0
                         []() { return config::brpc_arrow_flight_work_pool_max_queue_size; });
293
0
    REGISTER_HOOK_METRIC(arrow_flight_work_max_threads,
294
0
                         []() { return config::brpc_arrow_flight_work_pool_threads; });
295
296
0
    _exec_env->load_stream_mgr()->set_heavy_work_pool(&_heavy_work_pool);
297
298
0
    CHECK_EQ(0, bthread_key_create(&btls_key, thread_context_deleter));
299
0
    CHECK_EQ(0, bthread_key_create(&AsyncIO::btls_io_ctx_key, AsyncIO::io_ctx_key_deleter));
300
0
}
301
302
PInternalServiceImpl::PInternalServiceImpl(StorageEngine& engine, ExecEnv* exec_env)
303
0
        : PInternalService(exec_env), _engine(engine) {}
304
305
0
PInternalServiceImpl::~PInternalServiceImpl() = default;
306
307
0
PInternalService::~PInternalService() {
308
0
    DEREGISTER_HOOK_METRIC(heavy_work_pool_queue_size);
309
0
    DEREGISTER_HOOK_METRIC(peer_fetch_work_pool_queue_size);
310
0
    DEREGISTER_HOOK_METRIC(light_work_pool_queue_size);
311
0
    DEREGISTER_HOOK_METRIC(heavy_work_active_threads);
312
0
    DEREGISTER_HOOK_METRIC(peer_fetch_work_active_threads);
313
0
    DEREGISTER_HOOK_METRIC(light_work_active_threads);
314
315
0
    DEREGISTER_HOOK_METRIC(heavy_work_pool_max_queue_size);
316
0
    DEREGISTER_HOOK_METRIC(peer_fetch_work_pool_max_queue_size);
317
0
    DEREGISTER_HOOK_METRIC(light_work_pool_max_queue_size);
318
0
    DEREGISTER_HOOK_METRIC(heavy_work_max_threads);
319
0
    DEREGISTER_HOOK_METRIC(peer_fetch_work_max_threads);
320
0
    DEREGISTER_HOOK_METRIC(light_work_max_threads);
321
322
0
    DEREGISTER_HOOK_METRIC(arrow_flight_work_pool_queue_size);
323
0
    DEREGISTER_HOOK_METRIC(arrow_flight_work_active_threads);
324
0
    DEREGISTER_HOOK_METRIC(arrow_flight_work_pool_max_queue_size);
325
0
    DEREGISTER_HOOK_METRIC(arrow_flight_work_max_threads);
326
327
0
    CHECK_EQ(0, bthread_key_delete(btls_key));
328
0
    CHECK_EQ(0, bthread_key_delete(AsyncIO::btls_io_ctx_key));
329
0
}
330
331
void PInternalService::tablet_writer_open(google::protobuf::RpcController* controller,
332
                                          const PTabletWriterOpenRequest* request,
333
                                          PTabletWriterOpenResult* response,
334
0
                                          google::protobuf::Closure* done) {
335
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done]() {
336
0
        VLOG_RPC << "tablet writer open, id=" << request->id()
337
0
                 << ", index_id=" << request->index_id() << ", txn_id=" << request->txn_id();
338
0
        signal::SignalTaskIdKeeper keeper(request->id());
339
0
        brpc::ClosureGuard closure_guard(done);
340
0
        auto st = _exec_env->load_channel_mgr()->open(*request);
341
0
        if (!st.ok()) {
342
0
            LOG(WARNING) << "load channel open failed, message=" << st << ", id=" << request->id()
343
0
                         << ", index_id=" << request->index_id()
344
0
                         << ", txn_id=" << request->txn_id();
345
0
        }
346
0
        st.to_protobuf(response->mutable_status());
347
0
    });
348
0
    if (!ret) {
349
0
        offer_failed(response, done, _heavy_work_pool);
350
0
        return;
351
0
    }
352
0
}
353
354
void PInternalService::exec_plan_fragment(google::protobuf::RpcController* controller,
355
                                          const PExecPlanFragmentRequest* request,
356
                                          PExecPlanFragmentResult* response,
357
0
                                          google::protobuf::Closure* done) {
358
0
    timeval tv {};
359
0
    gettimeofday(&tv, nullptr);
360
0
    response->set_received_time(tv.tv_sec * 1000LL + tv.tv_usec / 1000);
361
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
362
0
        _exec_plan_fragment_in_pthread(controller, request, response, done);
363
0
    });
364
0
    if (!ret) {
365
0
        offer_failed(response, done, _light_work_pool);
366
0
        return;
367
0
    }
368
0
}
369
370
void PInternalService::_exec_plan_fragment_in_pthread(google::protobuf::RpcController* controller,
371
                                                      const PExecPlanFragmentRequest* request,
372
                                                      PExecPlanFragmentResult* response,
373
0
                                                      google::protobuf::Closure* done) {
374
0
    timeval tv1 {};
375
0
    gettimeofday(&tv1, nullptr);
376
0
    response->set_execution_time(tv1.tv_sec * 1000LL + tv1.tv_usec / 1000);
377
0
    brpc::ClosureGuard closure_guard(done);
378
0
    auto st = Status::OK();
379
0
    bool compact = request->has_compact() ? request->compact() : false;
380
0
    PFragmentRequestVersion version =
381
0
            request->has_version() ? request->version() : PFragmentRequestVersion::VERSION_1;
382
0
    try {
383
0
        st = _exec_plan_fragment_impl(request->request(), version, compact);
384
0
    } catch (const Exception& e) {
385
0
        st = e.to_status();
386
0
    } catch (const std::exception& e) {
387
0
        st = Status::Error(ErrorCode::INTERNAL_ERROR, e.what());
388
0
    } catch (...) {
389
0
        st = Status::Error(ErrorCode::INTERNAL_ERROR,
390
0
                           "_exec_plan_fragment_impl meet unknown error");
391
0
    }
392
0
    if (!st.ok()) {
393
0
        LOG(WARNING) << "exec plan fragment failed, errmsg=" << st;
394
0
    }
395
0
    st.to_protobuf(response->mutable_status());
396
0
    timeval tv2 {};
397
0
    gettimeofday(&tv2, nullptr);
398
0
    response->set_execution_done_time(tv2.tv_sec * 1000LL + tv2.tv_usec / 1000);
399
0
}
400
401
void PInternalService::exec_plan_fragment_prepare(google::protobuf::RpcController* controller,
402
                                                  const PExecPlanFragmentRequest* request,
403
                                                  PExecPlanFragmentResult* response,
404
0
                                                  google::protobuf::Closure* done) {
405
0
    timeval tv {};
406
0
    gettimeofday(&tv, nullptr);
407
0
    response->set_received_time(tv.tv_sec * 1000LL + tv.tv_usec / 1000);
408
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
409
0
        _exec_plan_fragment_in_pthread(controller, request, response, done);
410
0
    });
411
0
    if (!ret) {
412
0
        offer_failed(response, done, _light_work_pool);
413
0
        return;
414
0
    }
415
0
}
416
417
void PInternalService::exec_plan_fragment_start(google::protobuf::RpcController* /*controller*/,
418
                                                const PExecPlanFragmentStartRequest* request,
419
                                                PExecPlanFragmentResult* result,
420
0
                                                google::protobuf::Closure* done) {
421
0
    timeval tv {};
422
0
    gettimeofday(&tv, nullptr);
423
0
    result->set_received_time(tv.tv_sec * 1000LL + tv.tv_usec / 1000);
424
0
    bool ret = _light_work_pool.try_offer([this, request, result, done]() {
425
0
        timeval tv1 {};
426
0
        gettimeofday(&tv1, nullptr);
427
0
        result->set_execution_time(tv1.tv_sec * 1000LL + tv1.tv_usec / 1000);
428
0
        brpc::ClosureGuard closure_guard(done);
429
0
        auto st = _exec_env->fragment_mgr()->start_query_execution(request);
430
0
        st.to_protobuf(result->mutable_status());
431
0
        timeval tv2 {};
432
0
        gettimeofday(&tv2, nullptr);
433
0
        result->set_execution_done_time(tv2.tv_sec * 1000LL + tv2.tv_usec / 1000);
434
0
    });
435
0
    if (!ret) {
436
0
        offer_failed(result, done, _light_work_pool);
437
0
        return;
438
0
    }
439
0
}
440
441
void PInternalService::open_load_stream(google::protobuf::RpcController* controller,
442
                                        const POpenLoadStreamRequest* request,
443
                                        POpenLoadStreamResponse* response,
444
0
                                        google::protobuf::Closure* done) {
445
0
    bool ret = _heavy_work_pool.try_offer([this, controller, request, response, done]() {
446
0
        signal::SignalTaskIdKeeper keeper(request->load_id());
447
0
        brpc::ClosureGuard done_guard(done);
448
0
        brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
449
0
        brpc::StreamOptions stream_options;
450
451
0
        LOG(INFO) << "open load stream, load_id=" << request->load_id()
452
0
                  << ", src_id=" << request->src_id();
453
454
0
        std::vector<BaseTabletSPtr> tablets;
455
0
        for (const auto& req : request->tablets()) {
456
0
            BaseTabletSPtr tablet;
457
0
            if (auto res = ExecEnv::get_tablet(req.tablet_id()); !res.has_value()) [[unlikely]] {
458
0
                auto st = std::move(res).error();
459
0
                st.to_protobuf(response->mutable_status());
460
0
                cntl->SetFailed(st.to_string());
461
0
                return;
462
0
            } else {
463
0
                tablet = std::move(res).value();
464
0
            }
465
0
            auto resp = response->add_tablet_schemas();
466
0
            resp->set_index_id(req.index_id());
467
0
            resp->set_enable_unique_key_merge_on_write(tablet->enable_unique_key_merge_on_write());
468
0
            tablet->tablet_schema()->to_schema_pb(resp->mutable_tablet_schema());
469
0
            tablets.push_back(tablet);
470
0
        }
471
0
        if (!tablets.empty()) {
472
0
            auto* tablet_load_infos = response->mutable_tablet_load_rowset_num_infos();
473
0
            for (const auto& tablet : tablets) {
474
0
                BaseDeltaWriter::collect_tablet_load_rowset_num_info(tablet.get(),
475
0
                                                                     tablet_load_infos);
476
0
            }
477
0
        }
478
479
0
        LoadStream* load_stream = nullptr;
480
0
        auto st = _exec_env->load_stream_mgr()->open_load_stream(request, load_stream);
481
0
        if (!st.ok()) {
482
0
            st.to_protobuf(response->mutable_status());
483
0
            return;
484
0
        }
485
486
0
        stream_options.handler = load_stream;
487
0
        stream_options.idle_timeout_ms = request->idle_timeout_ms();
488
0
        DBUG_EXECUTE_IF("PInternalServiceImpl.open_load_stream.set_idle_timeout",
489
0
                        { stream_options.idle_timeout_ms = 1; });
490
491
0
        StreamId streamid;
492
0
        if (brpc::StreamAccept(&streamid, *cntl, &stream_options) != 0) {
493
0
            st = Status::Cancelled("Fail to accept stream {}", streamid);
494
0
            st.to_protobuf(response->mutable_status());
495
0
            cntl->SetFailed(st.to_string());
496
0
            return;
497
0
        }
498
499
0
        VLOG_DEBUG << "get streamid =" << streamid;
500
0
        st.to_protobuf(response->mutable_status());
501
0
    });
502
0
    if (!ret) {
503
0
        offer_failed(response, done, _heavy_work_pool);
504
0
    }
505
0
}
506
507
void PInternalService::tablet_writer_add_block_by_http(google::protobuf::RpcController* controller,
508
                                                       const ::doris::PEmptyRequest* request,
509
                                                       PTabletWriterAddBlockResult* response,
510
0
                                                       google::protobuf::Closure* done) {
511
0
    PTabletWriterAddBlockRequest* new_request = new PTabletWriterAddBlockRequest();
512
0
    google::protobuf::Closure* new_done =
513
0
            new NewHttpClosure<PTabletWriterAddBlockRequest>(new_request, done);
514
0
    brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
515
0
    Status st = attachment_extract_request_contain_block<PTabletWriterAddBlockRequest>(new_request,
516
0
                                                                                       cntl);
517
0
    if (st.ok()) {
518
0
        tablet_writer_add_block(controller, new_request, response, new_done);
519
0
    } else {
520
0
        st.to_protobuf(response->mutable_status());
521
0
    }
522
0
}
523
524
void PInternalService::tablet_writer_add_block(google::protobuf::RpcController* controller,
525
                                               const PTabletWriterAddBlockRequest* request,
526
                                               PTabletWriterAddBlockResult* response,
527
0
                                               google::protobuf::Closure* done) {
528
0
    int64_t submit_task_time_ns = MonotonicNanos();
529
0
    bool ret = _heavy_work_pool.try_offer([request, response, done, submit_task_time_ns, this]() {
530
0
        int64_t wait_execution_time_ns = MonotonicNanos() - submit_task_time_ns;
531
0
        brpc::ClosureGuard closure_guard(done);
532
0
        int64_t execution_time_ns = 0;
533
0
        {
534
0
            SCOPED_RAW_TIMER(&execution_time_ns);
535
0
            signal::SignalTaskIdKeeper keeper(request->id());
536
0
            auto st = _exec_env->load_channel_mgr()->add_batch(*request, response);
537
0
            if (!st.ok()) {
538
0
                LOG(WARNING) << "tablet writer add block failed, message=" << st
539
0
                             << ", id=" << request->id() << ", index_id=" << request->index_id()
540
0
                             << ", sender_id=" << request->sender_id()
541
0
                             << ", backend id=" << request->backend_id();
542
0
            }
543
0
            st.to_protobuf(response->mutable_status());
544
0
        }
545
0
        response->set_execution_time_us(execution_time_ns / NANOS_PER_MICRO);
546
0
        response->set_wait_execution_time_us(wait_execution_time_ns / NANOS_PER_MICRO);
547
0
    });
548
0
    if (!ret) {
549
0
        offer_failed(response, done, _heavy_work_pool);
550
0
        return;
551
0
    }
552
0
}
553
554
void PInternalService::tablet_writer_cancel(google::protobuf::RpcController* controller,
555
                                            const PTabletWriterCancelRequest* request,
556
                                            PTabletWriterCancelResult* response,
557
0
                                            google::protobuf::Closure* done) {
558
0
    bool ret = _heavy_work_pool.try_offer([this, request, done]() {
559
0
        VLOG_RPC << "tablet writer cancel, id=" << request->id()
560
0
                 << ", index_id=" << request->index_id() << ", sender_id=" << request->sender_id();
561
0
        signal::SignalTaskIdKeeper keeper(request->id());
562
0
        brpc::ClosureGuard closure_guard(done);
563
0
        auto st = _exec_env->load_channel_mgr()->cancel(*request);
564
0
        if (!st.ok()) {
565
0
            LOG(WARNING) << "tablet writer cancel failed, id=" << request->id()
566
0
                         << ", index_id=" << request->index_id()
567
0
                         << ", sender_id=" << request->sender_id();
568
0
        }
569
0
    });
570
0
    if (!ret) {
571
0
        offer_failed(response, done, _heavy_work_pool);
572
0
        return;
573
0
    }
574
0
}
575
576
Status PInternalService::_exec_plan_fragment_impl(
577
        const std::string& ser_request, PFragmentRequestVersion version, bool compact,
578
0
        const std::function<void(RuntimeState*, Status*)>& cb) {
579
    // Sometimes the BE do not receive the first heartbeat message and it receives request from FE
580
    // If BE execute this fragment, it will core when it wants to get some property from master info.
581
0
    if (ExecEnv::GetInstance()->cluster_info() == nullptr) {
582
0
        return Status::InternalError(
583
0
                "Have not receive the first heartbeat message from master, not ready to provide "
584
0
                "service");
585
0
    }
586
0
    CHECK(version == PFragmentRequestVersion::VERSION_3)
587
0
            << "only support version 3, received " << version;
588
0
    if (version == PFragmentRequestVersion::VERSION_3) {
589
0
        TPipelineFragmentParamsList t_request;
590
0
        {
591
0
            const uint8_t* buf = (const uint8_t*)ser_request.data();
592
0
            uint32_t len = ser_request.size();
593
0
            RETURN_IF_ERROR(deserialize_thrift_msg(buf, &len, compact, &t_request));
594
0
        }
595
596
0
        const auto& fragment_list = t_request.params_list;
597
0
        if (fragment_list.empty()) {
598
0
            return Status::InternalError("Invalid TPipelineFragmentParamsList!");
599
0
        }
600
0
        MonotonicStopWatch timer;
601
0
        timer.start();
602
603
        // work for old version frontend
604
0
        if (!t_request.__isset.runtime_filter_info) {
605
0
            TRuntimeFilterInfo runtime_filter_info;
606
0
            auto local_param = fragment_list[0].local_params[0];
607
0
            if (local_param.__isset.runtime_filter_params) {
608
0
                runtime_filter_info.__set_runtime_filter_params(local_param.runtime_filter_params);
609
0
            }
610
0
            if (local_param.__isset.topn_filter_descs) {
611
0
                runtime_filter_info.__set_topn_filter_descs(local_param.topn_filter_descs);
612
0
            }
613
0
            t_request.__set_runtime_filter_info(runtime_filter_info);
614
0
        }
615
616
0
        for (const TPipelineFragmentParams& fragment : fragment_list) {
617
0
            if (cb) {
618
0
                RETURN_IF_ERROR(_exec_env->fragment_mgr()->exec_plan_fragment(
619
0
                        fragment, QuerySource::INTERNAL_FRONTEND, cb, t_request));
620
0
            } else {
621
0
                RETURN_IF_ERROR(_exec_env->fragment_mgr()->exec_plan_fragment(
622
0
                        fragment, QuerySource::INTERNAL_FRONTEND, t_request));
623
0
            }
624
0
        }
625
0
        timer.stop();
626
0
        double cost_secs = static_cast<double>(timer.elapsed_time()) / 1000000000ULL;
627
0
        if (cost_secs > 5) {
628
0
            LOG_WARNING("Prepare {} fragments of query {} costs {} seconds, it costs too much",
629
0
                        fragment_list.size(), print_id(fragment_list.front().query_id), cost_secs);
630
0
        }
631
632
0
        return Status::OK();
633
0
    } else {
634
0
        return Status::InternalError("invalid version");
635
0
    }
636
0
}
637
638
void PInternalService::cancel_plan_fragment(google::protobuf::RpcController* /*controller*/,
639
                                            const PCancelPlanFragmentRequest* request,
640
                                            PCancelPlanFragmentResult* result,
641
0
                                            google::protobuf::Closure* done) {
642
0
    bool ret = _light_work_pool.try_offer([this, request, result, done]() {
643
0
        brpc::ClosureGuard closure_guard(done);
644
0
        signal::SignalTaskIdKeeper keeper(request->finst_id());
645
0
        Status st = Status::OK();
646
647
0
        const bool has_cancel_reason = request->has_cancel_reason();
648
0
        const bool has_cancel_status = request->has_cancel_status();
649
        // During upgrade only LIMIT_REACH is used, other reason is changed to internal error
650
0
        Status actual_cancel_status = Status::OK();
651
        // Convert PPlanFragmentCancelReason to Status
652
0
        if (has_cancel_status) {
653
            // If fe set cancel status, then it is new FE now, should use cancel status.
654
0
            actual_cancel_status = Status::create<false>(request->cancel_status());
655
0
        } else if (has_cancel_reason) {
656
            // If fe not set cancel status, but set cancel reason, should convert cancel reason
657
            // to cancel status here.
658
0
            if (request->cancel_reason() == PPlanFragmentCancelReason::LIMIT_REACH) {
659
0
                actual_cancel_status = Status::Error<ErrorCode::LIMIT_REACH>("limit reach");
660
0
            } else {
661
                // Use cancel reason as error message
662
0
                actual_cancel_status = Status::InternalError(
663
0
                        PPlanFragmentCancelReason_Name(request->cancel_reason()));
664
0
            }
665
0
        } else {
666
0
            actual_cancel_status = Status::InternalError("unknown error");
667
0
        }
668
669
0
        TUniqueId query_id;
670
0
        query_id.__set_hi(request->query_id().hi());
671
0
        query_id.__set_lo(request->query_id().lo());
672
0
        LOG(INFO) << fmt::format("Cancel query {}, reason: {}", print_id(query_id),
673
0
                                 actual_cancel_status.to_string());
674
0
        _exec_env->fragment_mgr()->cancel_query(query_id, actual_cancel_status);
675
676
        // TODO: the logic seems useless, cancel only return Status::OK. remove it
677
0
        st.to_protobuf(result->mutable_status());
678
0
    });
679
0
    if (!ret) {
680
0
        offer_failed(result, done, _light_work_pool);
681
0
        return;
682
0
    }
683
0
}
684
685
void PInternalService::fetch_data(google::protobuf::RpcController* controller,
686
                                  const PFetchDataRequest* request, PFetchDataResult* result,
687
0
                                  google::protobuf::Closure* done) {
688
    // fetch_data is a light operation which will put a request rather than wait inplace when there's no data ready.
689
    // when there's data ready, use brpc to send. there's queue in brpc service. won't take it too long.
690
0
    auto ctx = GetResultBatchCtx::create_shared(result, done);
691
0
    TUniqueId unique_id = UniqueId(request->finst_id()).to_thrift(); // query_id or instance_id
692
0
    std::shared_ptr<MySQLResultBlockBuffer> buffer;
693
0
    Status st = ExecEnv::GetInstance()->result_mgr()->find_buffer(unique_id, buffer);
694
0
    if (!st.ok()) {
695
0
        LOG(WARNING) << "Result buffer not found! finst ID: " << print_id(unique_id);
696
0
        return;
697
0
    }
698
0
    if (st = buffer->get_batch(ctx); !st.ok()) {
699
0
        LOG(WARNING) << "fetch_data failed: " << st.to_string();
700
0
    }
701
0
}
702
703
void PInternalService::fetch_arrow_data(google::protobuf::RpcController* controller,
704
                                        const PFetchArrowDataRequest* request,
705
                                        PFetchArrowDataResult* result,
706
0
                                        google::protobuf::Closure* done) {
707
0
    bool ret = _arrow_flight_work_pool.try_offer([request, result, done]() {
708
0
        auto ctx = GetArrowResultBatchCtx::create_shared(result, done);
709
0
        TUniqueId unique_id = UniqueId(request->finst_id()).to_thrift(); // query_id or instance_id
710
0
        std::shared_ptr<ArrowFlightResultBlockBuffer> arrow_buffer;
711
0
        auto st = ExecEnv::GetInstance()->result_mgr()->find_buffer(unique_id, arrow_buffer);
712
0
        if (!st.ok()) {
713
0
            LOG(WARNING) << "Result buffer not found! Query ID: " << print_id(unique_id);
714
0
            return;
715
0
        }
716
0
        if (st = arrow_buffer->get_batch(ctx); !st.ok()) {
717
0
            LOG(WARNING) << "fetch_arrow_data failed: " << st.to_string();
718
0
        }
719
0
    });
720
0
    if (!ret) {
721
0
        offer_failed(result, done, _arrow_flight_work_pool);
722
0
        return;
723
0
    }
724
0
}
725
726
void PInternalService::outfile_write_success(google::protobuf::RpcController* controller,
727
                                             const POutfileWriteSuccessRequest* request,
728
                                             POutfileWriteSuccessResult* result,
729
0
                                             google::protobuf::Closure* done) {
730
0
    bool ret = _heavy_work_pool.try_offer([request, result, done]() {
731
0
        VLOG_RPC << "outfile write success file";
732
0
        brpc::ClosureGuard closure_guard(done);
733
0
        TResultFileSink result_file_sink;
734
0
        Status st = Status::OK();
735
0
        {
736
0
            const uint8_t* buf = (const uint8_t*)(request->result_file_sink().data());
737
0
            uint32_t len = request->result_file_sink().size();
738
0
            st = deserialize_thrift_msg(buf, &len, false, &result_file_sink);
739
0
            if (!st.ok()) {
740
0
                LOG(WARNING) << "outfile write success file failed, errmsg = " << st;
741
0
                st.to_protobuf(result->mutable_status());
742
0
                return;
743
0
            }
744
0
        }
745
746
0
        TResultFileSinkOptions file_options = result_file_sink.file_options;
747
0
        std::stringstream ss;
748
0
        ss << file_options.file_path << file_options.success_file_name;
749
0
        std::string file_name = ss.str();
750
0
        if (result_file_sink.storage_backend_type == TStorageBackendType::LOCAL) {
751
            // For local file writer, the file_path is a local dir.
752
            // Here we do a simple security verification by checking whether the file exists.
753
            // Because the file path is currently arbitrarily specified by the user,
754
            // Doris is not responsible for ensuring the correctness of the path.
755
            // This is just to prevent overwriting the existing file.
756
0
            bool exists = true;
757
0
            st = io::global_local_filesystem()->exists(file_name, &exists);
758
0
            if (!st.ok()) {
759
0
                LOG(WARNING) << "outfile write success filefailed, errmsg = " << st;
760
0
                st.to_protobuf(result->mutable_status());
761
0
                return;
762
0
            }
763
0
            if (exists) {
764
0
                st = Status::InternalError("File already exists: {}", file_name);
765
0
            }
766
0
            if (!st.ok()) {
767
0
                LOG(WARNING) << "outfile write success file failed, errmsg = " << st;
768
0
                st.to_protobuf(result->mutable_status());
769
0
                return;
770
0
            }
771
0
        }
772
773
0
        auto file_type_res =
774
0
                FileFactory::convert_storage_type(result_file_sink.storage_backend_type);
775
0
        if (!file_type_res.has_value()) [[unlikely]] {
776
0
            st = std::move(file_type_res).error();
777
0
            st.to_protobuf(result->mutable_status());
778
0
            LOG(WARNING) << "encounter unkonw type=" << result_file_sink.storage_backend_type
779
0
                         << ", st=" << st;
780
0
            return;
781
0
        }
782
783
0
        auto&& res = FileFactory::create_file_writer(file_type_res.value(), ExecEnv::GetInstance(),
784
0
                                                     file_options.broker_addresses,
785
0
                                                     file_options.broker_properties, file_name,
786
0
                                                     {
787
0
                                                             .write_file_cache = false,
788
0
                                                             .sync_file_data = false,
789
0
                                                     });
790
0
        using T = std::decay_t<decltype(res)>;
791
0
        if (!res.has_value()) [[unlikely]] {
792
0
            st = std::forward<T>(res).error();
793
0
            st.to_protobuf(result->mutable_status());
794
0
            return;
795
0
        }
796
797
0
        std::unique_ptr<doris::io::FileWriter> _file_writer_impl = std::forward<T>(res).value();
798
        // must write somthing because s3 file writer can not writer empty file
799
0
        st = _file_writer_impl->append({"success"});
800
0
        if (!st.ok()) {
801
0
            LOG(WARNING) << "outfile write success filefailed, errmsg=" << st;
802
0
            st.to_protobuf(result->mutable_status());
803
0
            return;
804
0
        }
805
0
        st = _file_writer_impl->close();
806
0
        if (!st.ok()) {
807
0
            LOG(WARNING) << "outfile write success filefailed, errmsg=" << st;
808
0
            st.to_protobuf(result->mutable_status());
809
0
            return;
810
0
        }
811
0
    });
812
0
    if (!ret) {
813
0
        offer_failed(result, done, _heavy_work_pool);
814
0
        return;
815
0
    }
816
0
}
817
818
void PInternalService::fetch_table_schema(google::protobuf::RpcController* controller,
819
                                          const PFetchTableSchemaRequest* request,
820
                                          PFetchTableSchemaResult* result,
821
0
                                          google::protobuf::Closure* done) {
822
0
    bool ret = _heavy_work_pool.try_offer([request, result, done]() {
823
0
        VLOG_RPC << "fetch table schema";
824
0
        brpc::ClosureGuard closure_guard(done);
825
0
        TFileScanRange file_scan_range;
826
0
        Status st = Status::OK();
827
0
        {
828
0
            const uint8_t* buf = (const uint8_t*)(request->file_scan_range().data());
829
0
            uint32_t len = request->file_scan_range().size();
830
0
            st = deserialize_thrift_msg(buf, &len, false, &file_scan_range);
831
0
            if (!st.ok()) {
832
0
                LOG(WARNING) << "fetch table schema failed, errmsg=" << st;
833
0
                st.to_protobuf(result->mutable_status());
834
0
                return;
835
0
            }
836
0
        }
837
0
        if (file_scan_range.__isset.ranges == false) {
838
0
            st = Status::InternalError("can not get TFileRangeDesc.");
839
0
            st.to_protobuf(result->mutable_status());
840
0
            return;
841
0
        }
842
0
        if (file_scan_range.__isset.params == false) {
843
0
            st = Status::InternalError("can not get TFileScanRangeParams.");
844
0
            st.to_protobuf(result->mutable_status());
845
0
            return;
846
0
        }
847
0
        const TFileRangeDesc& range = file_scan_range.ranges.at(0);
848
0
        const TFileScanRangeParams& params = file_scan_range.params;
849
850
0
        std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
851
0
                MemTrackerLimiter::Type::OTHER,
852
0
                fmt::format("InternalService::fetch_table_schema:{}#{}", params.format_type,
853
0
                            params.file_type));
854
0
        SCOPED_ATTACH_TASK(mem_tracker);
855
856
        // make sure profile is desctructed after reader cause PrefetchBufferedReader
857
        // might asynchronouslly access the profile
858
0
        std::unique_ptr<RuntimeProfile> profile =
859
0
                std::make_unique<RuntimeProfile>("FetchTableSchema");
860
0
        std::unique_ptr<GenericReader> reader(nullptr);
861
0
        auto io_ctx = std::make_shared<io::IOContext>();
862
0
        auto file_cache_statis = std::make_shared<io::FileCacheStatistics>();
863
0
        auto file_reader_stats = std::make_shared<io::FileReaderStats>();
864
0
        io_ctx->file_cache_stats = file_cache_statis.get();
865
0
        io_ctx->file_reader_stats = file_reader_stats.get();
866
0
        constexpr size_t fetch_schema_batch_size = 4064;
867
        // file_slots is no use, but the lifetime should be longer than reader
868
0
        std::vector<SlotDescriptor*> file_slots;
869
0
        switch (params.format_type) {
870
0
        case TFileFormatType::FORMAT_CSV_PLAIN:
871
0
        case TFileFormatType::FORMAT_CSV_GZ:
872
0
        case TFileFormatType::FORMAT_CSV_BZ2:
873
0
        case TFileFormatType::FORMAT_CSV_LZ4FRAME:
874
0
        case TFileFormatType::FORMAT_CSV_LZ4BLOCK:
875
0
        case TFileFormatType::FORMAT_CSV_SNAPPYBLOCK:
876
0
        case TFileFormatType::FORMAT_CSV_LZOP:
877
0
        case TFileFormatType::FORMAT_CSV_DEFLATE: {
878
0
            reader = CsvReader::create_unique(nullptr, profile.get(), nullptr, params, range,
879
0
                                              file_slots, fetch_schema_batch_size, io_ctx.get(),
880
0
                                              io_ctx);
881
0
            break;
882
0
        }
883
0
        case TFileFormatType::FORMAT_TEXT: {
884
0
            reader = TextReader::create_unique(nullptr, profile.get(), nullptr, params, range,
885
0
                                               file_slots, fetch_schema_batch_size, io_ctx.get());
886
0
            break;
887
0
        }
888
0
        case TFileFormatType::FORMAT_PARQUET: {
889
0
            reader = ParquetReader::create_unique(params, range, io_ctx, nullptr);
890
0
            break;
891
0
        }
892
0
        case TFileFormatType::FORMAT_ORC: {
893
0
            reader = OrcReader::create_unique(params, range, fetch_schema_batch_size, "", io_ctx);
894
0
            break;
895
0
        }
896
0
        case TFileFormatType::FORMAT_NATIVE: {
897
0
            reader = NativeReader::create_unique(profile.get(), params, range, io_ctx.get(),
898
0
                                                 nullptr);
899
0
            break;
900
0
        }
901
0
        case TFileFormatType::FORMAT_JSON: {
902
0
            reader = NewJsonReader::create_unique(profile.get(), params, range, file_slots,
903
0
                                                  fetch_schema_batch_size, io_ctx.get(), io_ctx);
904
0
            break;
905
0
        }
906
#ifdef BUILD_RUST_READERS
907
        case TFileFormatType::FORMAT_LANCE: {
908
            reader = LanceRustReader::create_unique(params, range, io_ctx.get());
909
            break;
910
        }
911
#endif
912
0
        default:
913
0
            st = Status::InternalError("Not supported file format in fetch table schema: {}",
914
0
                                       params.format_type);
915
0
            st.to_protobuf(result->mutable_status());
916
0
            return;
917
0
        }
918
0
        if (!st.ok()) {
919
0
            LOG(WARNING) << "failed to create reader, errmsg=" << st;
920
0
            st.to_protobuf(result->mutable_status());
921
0
            return;
922
0
        }
923
0
        st = reader->init_schema_reader();
924
0
        if (!st.ok()) {
925
0
            LOG(WARNING) << "failed to init reader, errmsg=" << st;
926
0
            st.to_protobuf(result->mutable_status());
927
0
            return;
928
0
        }
929
0
        std::vector<std::string> col_names;
930
0
        std::vector<DataTypePtr> col_types;
931
0
        st = reader->get_parsed_schema(&col_names, &col_types);
932
0
        if (!st.ok()) {
933
0
            LOG(WARNING) << "fetch table schema failed, errmsg=" << st;
934
0
            st.to_protobuf(result->mutable_status());
935
0
            return;
936
0
        }
937
0
        result->set_column_nums(col_names.size());
938
0
        for (size_t idx = 0; idx < col_names.size(); ++idx) {
939
0
            result->add_column_names(col_names[idx]);
940
0
        }
941
0
        for (size_t idx = 0; idx < col_types.size(); ++idx) {
942
0
            PTypeDesc* type_desc = result->add_column_types();
943
0
            col_types[idx]->to_protobuf(type_desc);
944
0
        }
945
0
        st.to_protobuf(result->mutable_status());
946
0
    });
947
0
    if (!ret) {
948
0
        offer_failed(result, done, _heavy_work_pool);
949
0
        return;
950
0
    }
951
0
}
952
953
void PInternalService::fetch_arrow_flight_schema(google::protobuf::RpcController* controller,
954
                                                 const PFetchArrowFlightSchemaRequest* request,
955
                                                 PFetchArrowFlightSchemaResult* result,
956
0
                                                 google::protobuf::Closure* done) {
957
0
    bool ret = _arrow_flight_work_pool.try_offer([request, result, done]() {
958
0
        brpc::ClosureGuard closure_guard(done);
959
0
        std::shared_ptr<arrow::Schema> schema;
960
0
        std::shared_ptr<ArrowFlightResultBlockBuffer> buffer;
961
0
        auto st = ExecEnv::GetInstance()->result_mgr()->find_buffer(
962
0
                UniqueId(request->finst_id()).to_thrift(), buffer);
963
0
        if (!st.ok()) {
964
0
            LOG(WARNING) << "fetch arrow flight schema failed, errmsg=" << st;
965
0
            st.to_protobuf(result->mutable_status());
966
0
            return;
967
0
        }
968
0
        st = buffer->get_schema(&schema);
969
0
        if (!st.ok()) {
970
0
            LOG(WARNING) << "fetch arrow flight schema failed, errmsg=" << st;
971
0
            st.to_protobuf(result->mutable_status());
972
0
            return;
973
0
        }
974
975
0
        std::string schema_str;
976
0
        st = serialize_arrow_schema(&schema, &schema_str);
977
0
        if (st.ok()) {
978
0
            result->set_schema(std::move(schema_str));
979
0
            if (!config::public_host.empty()) {
980
0
                result->set_be_arrow_flight_ip(config::public_host);
981
0
            }
982
0
            if (config::arrow_flight_sql_proxy_port != -1) {
983
0
                result->set_be_arrow_flight_port(config::arrow_flight_sql_proxy_port);
984
0
            }
985
0
        }
986
0
        st.to_protobuf(result->mutable_status());
987
0
    });
988
0
    if (!ret) {
989
0
        offer_failed(result, done, _arrow_flight_work_pool);
990
0
        return;
991
0
    }
992
0
}
993
994
Status PInternalService::_tablet_fetch_data(const PTabletKeyLookupRequest* request,
995
0
                                            PTabletKeyLookupResponse* response) {
996
0
    PointQueryExecutor executor;
997
0
    RETURN_IF_ERROR(executor.init(request, response));
998
0
    if (response->has_need_resend_query_context() && response->need_resend_query_context()) {
999
0
        return Status::OK();
1000
0
    }
1001
0
    RETURN_IF_ERROR(executor.lookup_up());
1002
0
    executor.print_profile();
1003
0
    return Status::OK();
1004
0
}
1005
1006
void PInternalService::tablet_fetch_data(google::protobuf::RpcController* controller,
1007
                                         const PTabletKeyLookupRequest* request,
1008
                                         PTabletKeyLookupResponse* response,
1009
0
                                         google::protobuf::Closure* done) {
1010
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
1011
0
        [[maybe_unused]] auto* cntl = static_cast<brpc::Controller*>(controller);
1012
0
        brpc::ClosureGuard guard(done);
1013
0
        Status st = _tablet_fetch_data(request, response);
1014
0
        st.to_protobuf(response->mutable_status());
1015
0
    });
1016
0
    if (!ret) {
1017
0
        offer_failed(response, done, _light_work_pool);
1018
0
        return;
1019
0
    }
1020
0
}
1021
1022
void PInternalService::test_jdbc_connection(google::protobuf::RpcController* controller,
1023
                                            const PJdbcTestConnectionRequest* request,
1024
                                            PJdbcTestConnectionResult* result,
1025
0
                                            google::protobuf::Closure* done) {
1026
0
    if (!doris::config::enable_java_support) {
1027
0
        doris::Status status = doris::Status::InternalError(
1028
0
                "you can change be config enable_java_support to true and restart be.");
1029
0
        status.to_protobuf(result->mutable_status());
1030
0
        done->Run();
1031
0
        return;
1032
0
    }
1033
0
    bool ret = _heavy_work_pool.try_offer([request, result, done]() {
1034
0
        VLOG_RPC << "test jdbc connection";
1035
0
        brpc::ClosureGuard closure_guard(done);
1036
0
        std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
1037
0
                MemTrackerLimiter::Type::OTHER,
1038
0
                fmt::format("InternalService::test_jdbc_connection"));
1039
0
        SCOPED_ATTACH_TASK(mem_tracker);
1040
0
        TTableDescriptor table_desc;
1041
0
        Status st = Status::OK();
1042
0
        {
1043
0
            const uint8_t* buf = (const uint8_t*)request->jdbc_table().data();
1044
0
            uint32_t len = request->jdbc_table().size();
1045
0
            st = deserialize_thrift_msg(buf, &len, false, &table_desc);
1046
0
            if (!st.ok()) {
1047
0
                LOG(WARNING) << "test jdbc connection failed, errmsg=" << st;
1048
0
                st.to_protobuf(result->mutable_status());
1049
0
                return;
1050
0
            }
1051
0
        }
1052
0
        TJdbcTable jdbc_table = (table_desc.jdbcTable);
1053
1054
        // Resolve driver URL to absolute file:// path
1055
0
        std::string driver_url;
1056
0
        st = JdbcUtils::resolve_driver_url(jdbc_table.jdbc_driver_url, &driver_url);
1057
0
        if (!st.ok()) {
1058
0
            st.to_protobuf(result->mutable_status());
1059
0
            return;
1060
0
        }
1061
1062
        // Build params for JdbcConnectionTester
1063
0
        std::map<std::string, std::string> params;
1064
0
        params["jdbc_url"] = jdbc_table.jdbc_url;
1065
0
        params["jdbc_user"] = jdbc_table.jdbc_user;
1066
0
        params["jdbc_password"] = jdbc_table.jdbc_password;
1067
0
        params["jdbc_driver_class"] = jdbc_table.jdbc_driver_class;
1068
0
        params["jdbc_driver_url"] = driver_url;
1069
0
        params["query_sql"] = request->query_str();
1070
0
        params["catalog_id"] = std::to_string(jdbc_table.catalog_id);
1071
0
        params["connection_pool_min_size"] = std::to_string(jdbc_table.connection_pool_min_size);
1072
0
        params["connection_pool_max_size"] = std::to_string(jdbc_table.connection_pool_max_size);
1073
0
        params["connection_pool_max_wait_time"] =
1074
0
                std::to_string(jdbc_table.connection_pool_max_wait_time);
1075
0
        params["connection_pool_max_life_time"] =
1076
0
                std::to_string(jdbc_table.connection_pool_max_life_time);
1077
0
        params["connection_pool_keep_alive"] =
1078
0
                jdbc_table.connection_pool_keep_alive ? "true" : "false";
1079
0
        params["clean_datasource"] = "true";
1080
        // Map jdbc_table_type (TOdbcTableType enum value) to string name
1081
        // for JdbcTypeHandlerFactory to select the correct type handler.
1082
        // This ensures the right validation query is used (e.g. Oracle: "SELECT 1 FROM dual").
1083
0
        if (request->has_jdbc_table_type()) {
1084
0
            std::string type_name;
1085
0
            switch (request->jdbc_table_type()) {
1086
0
            case 0:
1087
0
                type_name = "MYSQL";
1088
0
                break;
1089
0
            case 1:
1090
0
                type_name = "ORACLE";
1091
0
                break;
1092
0
            case 2:
1093
0
                type_name = "POSTGRESQL";
1094
0
                break;
1095
0
            case 3:
1096
0
                type_name = "SQLSERVER";
1097
0
                break;
1098
0
            case 6:
1099
0
                type_name = "CLICKHOUSE";
1100
0
                break;
1101
0
            case 7:
1102
0
                type_name = "SAP_HANA";
1103
0
                break;
1104
0
            case 8:
1105
0
                type_name = "TRINO";
1106
0
                break;
1107
0
            case 9:
1108
0
                type_name = "PRESTO";
1109
0
                break;
1110
0
            case 10:
1111
0
                type_name = "OCEANBASE";
1112
0
                break;
1113
0
            case 11:
1114
0
                type_name = "OCEANBASE_ORACLE";
1115
0
                break;
1116
0
            case 13:
1117
0
                type_name = "DB2";
1118
0
                break;
1119
0
            case 14:
1120
0
                type_name = "GBASE";
1121
0
                break;
1122
0
            default:
1123
0
                break;
1124
0
            }
1125
0
            if (!type_name.empty()) {
1126
0
                params["table_type"] = type_name;
1127
0
            }
1128
0
        }
1129
        // required_fields and columns_types are required by JniReader
1130
0
        params["required_fields"] = "result";
1131
0
        params["columns_types"] = "int";
1132
1133
        // Use JniReader to create JdbcConnectionTester, which tests
1134
        // the connection in its open() method.
1135
0
        auto jni_reader =
1136
0
                std::make_unique<JniReader>("org/apache/doris/jdbc/JdbcConnectionTester", params);
1137
0
        st = jni_reader->open(nullptr, nullptr);
1138
0
        st.to_protobuf(result->mutable_status());
1139
1140
0
        Status close_st = jni_reader->close();
1141
0
        if (!close_st.ok()) {
1142
0
            LOG(WARNING) << "Failed to close JDBC connection tester: " << close_st.msg();
1143
0
        }
1144
0
    });
1145
1146
0
    if (!ret) {
1147
0
        offer_failed(result, done, _heavy_work_pool);
1148
0
        return;
1149
0
    }
1150
0
}
1151
1152
void PInternalServiceImpl::get_column_ids_by_tablet_ids(google::protobuf::RpcController* controller,
1153
                                                        const PFetchColIdsRequest* request,
1154
                                                        PFetchColIdsResponse* response,
1155
0
                                                        google::protobuf::Closure* done) {
1156
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
1157
0
        _get_column_ids_by_tablet_ids(controller, request, response, done);
1158
0
    });
1159
0
    if (!ret) {
1160
0
        offer_failed(response, done, _light_work_pool);
1161
0
        return;
1162
0
    }
1163
0
}
1164
1165
void PInternalServiceImpl::_get_column_ids_by_tablet_ids(
1166
        google::protobuf::RpcController* controller, const PFetchColIdsRequest* request,
1167
0
        PFetchColIdsResponse* response, google::protobuf::Closure* done) {
1168
0
    brpc::ClosureGuard guard(done);
1169
0
    [[maybe_unused]] auto* cntl = static_cast<brpc::Controller*>(controller);
1170
0
    TabletManager* tablet_mgr = _engine.tablet_manager();
1171
0
    const auto& params = request->params();
1172
0
    for (const auto& param : params) {
1173
0
        int64_t index_id = param.indexid();
1174
0
        const auto& tablet_ids = param.tablet_ids();
1175
0
        std::set<std::set<int32_t>> filter_set;
1176
0
        std::map<int32_t, const TabletColumn*> id_to_column;
1177
0
        for (const int64_t tablet_id : tablet_ids) {
1178
0
            TabletSharedPtr tablet = tablet_mgr->get_tablet(tablet_id);
1179
0
            if (tablet == nullptr) {
1180
0
                std::stringstream ss;
1181
0
                ss << "cannot get tablet by id:" << tablet_id;
1182
0
                LOG(WARNING) << ss.str();
1183
0
                response->mutable_status()->set_status_code(TStatusCode::ILLEGAL_STATE);
1184
0
                response->mutable_status()->add_error_msgs(ss.str());
1185
0
                return;
1186
0
            }
1187
            // check schema consistency, column ids should be the same
1188
0
            const auto& columns = tablet->tablet_schema()->columns();
1189
1190
0
            std::set<int32_t> column_ids;
1191
0
            for (const auto& col : columns) {
1192
0
                column_ids.insert(col->unique_id());
1193
0
            }
1194
0
            filter_set.insert(std::move(column_ids));
1195
1196
0
            if (id_to_column.empty()) {
1197
0
                for (const auto& col : columns) {
1198
0
                    id_to_column.insert(std::pair {col->unique_id(), col.get()});
1199
0
                }
1200
0
            } else {
1201
0
                for (const auto& col : columns) {
1202
0
                    auto it = id_to_column.find(col->unique_id());
1203
0
                    if (it == id_to_column.end() || *(it->second) != *col) {
1204
0
                        ColumnPB prev_col_pb;
1205
0
                        ColumnPB curr_col_pb;
1206
0
                        if (it != id_to_column.end()) {
1207
0
                            it->second->to_schema_pb(&prev_col_pb);
1208
0
                        }
1209
0
                        col->to_schema_pb(&curr_col_pb);
1210
0
                        std::stringstream ss;
1211
0
                        ss << "consistency check failed: index{ " << index_id << " }"
1212
0
                           << " got inconsistent schema, prev column: " << prev_col_pb.DebugString()
1213
0
                           << " current column: " << curr_col_pb.DebugString();
1214
0
                        LOG(WARNING) << ss.str();
1215
0
                        response->mutable_status()->set_status_code(TStatusCode::ILLEGAL_STATE);
1216
0
                        response->mutable_status()->add_error_msgs(ss.str());
1217
0
                        return;
1218
0
                    }
1219
0
                }
1220
0
            }
1221
0
        }
1222
1223
0
        if (filter_set.size() > 1) {
1224
            // consistecy check failed
1225
0
            std::stringstream ss;
1226
0
            ss << "consistency check failed: index{" << index_id << "}"
1227
0
               << "got inconsistent schema";
1228
0
            LOG(WARNING) << ss.str();
1229
0
            response->mutable_status()->set_status_code(TStatusCode::ILLEGAL_STATE);
1230
0
            response->mutable_status()->add_error_msgs(ss.str());
1231
0
            return;
1232
0
        }
1233
        // consistency check passed, use the first tablet to be the representative
1234
0
        TabletSharedPtr tablet = tablet_mgr->get_tablet(tablet_ids[0]);
1235
0
        const auto& columns = tablet->tablet_schema()->columns();
1236
0
        auto entry = response->add_entries();
1237
0
        entry->set_index_id(index_id);
1238
0
        auto col_name_to_id = entry->mutable_col_name_to_id();
1239
0
        for (const auto& column : columns) {
1240
0
            (*col_name_to_id)[column->name()] = column->unique_id();
1241
0
        }
1242
0
    }
1243
0
    response->mutable_status()->set_status_code(TStatusCode::OK);
1244
0
}
1245
1246
template <class RPCResponse>
1247
struct AsyncRPCContext {
1248
    RPCResponse response;
1249
    brpc::Controller cntl;
1250
    brpc::CallId cid;
1251
};
1252
1253
void PInternalService::fetch_remote_tablet_schema(google::protobuf::RpcController* controller,
1254
                                                  const PFetchRemoteSchemaRequest* request,
1255
                                                  PFetchRemoteSchemaResponse* response,
1256
0
                                                  google::protobuf::Closure* done) {
1257
0
    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
1258
0
        brpc::ClosureGuard closure_guard(done);
1259
0
        Status st = Status::OK();
1260
0
        std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
1261
0
                MemTrackerLimiter::Type::OTHER,
1262
0
                fmt::format("InternalService::fetch_remote_tablet_schema"));
1263
0
        SCOPED_ATTACH_TASK(mem_tracker);
1264
0
        if (request->is_coordinator()) {
1265
            // Spawn rpc request to none coordinator nodes, and finally merge them all
1266
0
            PFetchRemoteSchemaRequest remote_request(*request);
1267
            // set it none coordinator to get merged schema
1268
0
            remote_request.set_is_coordinator(false);
1269
0
            using PFetchRemoteTabletSchemaRpcContext = AsyncRPCContext<PFetchRemoteSchemaResponse>;
1270
0
            std::vector<PFetchRemoteTabletSchemaRpcContext> rpc_contexts(
1271
0
                    request->tablet_location_size());
1272
0
            for (int i = 0; i < request->tablet_location_size(); ++i) {
1273
0
                std::string host = request->tablet_location(i).host();
1274
0
                int32_t brpc_port = request->tablet_location(i).brpc_port();
1275
0
                std::shared_ptr<PBackendService_Stub> stub(
1276
0
                        ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(
1277
0
                                host, brpc_port));
1278
0
                if (stub == nullptr) {
1279
0
                    LOG(WARNING) << "Failed to init rpc to " << host << ":" << brpc_port;
1280
0
                    st = Status::InternalError("Failed to init rpc to {}:{}", host, brpc_port);
1281
0
                    continue;
1282
0
                }
1283
0
                rpc_contexts[i].cid = rpc_contexts[i].cntl.call_id();
1284
0
                rpc_contexts[i].cntl.set_timeout_ms(config::fetch_remote_schema_rpc_timeout_ms);
1285
0
                stub->fetch_remote_tablet_schema(&rpc_contexts[i].cntl, &remote_request,
1286
0
                                                 &rpc_contexts[i].response, brpc::DoNothing());
1287
0
            }
1288
0
            std::vector<TabletSchemaSPtr> schemas;
1289
0
            for (auto& rpc_context : rpc_contexts) {
1290
0
                brpc::Join(rpc_context.cid);
1291
0
                if (!st.ok()) {
1292
                    // make sure all flying rpc request is joined
1293
0
                    continue;
1294
0
                }
1295
0
                if (rpc_context.cntl.Failed()) {
1296
0
                    LOG(WARNING) << "fetch_remote_tablet_schema rpc err:"
1297
0
                                 << rpc_context.cntl.ErrorText();
1298
0
                    ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
1299
0
                            rpc_context.cntl.remote_side());
1300
0
                    st = Status::InternalError("fetch_remote_tablet_schema rpc err: {}",
1301
0
                                               rpc_context.cntl.ErrorText());
1302
0
                }
1303
0
                if (rpc_context.response.status().status_code() != 0) {
1304
0
                    st = Status::create(rpc_context.response.status());
1305
0
                }
1306
0
                if (rpc_context.response.has_merged_schema()) {
1307
0
                    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
1308
0
                    schema->init_from_pb(rpc_context.response.merged_schema());
1309
0
                    schemas.push_back(schema);
1310
0
                }
1311
0
            }
1312
0
            if (!schemas.empty() && st.ok()) {
1313
                // merge all
1314
0
                TabletSchemaSPtr merged_schema;
1315
0
                st = variant_util::get_least_common_schema(schemas, nullptr, merged_schema);
1316
0
                if (!st.ok()) {
1317
0
                    LOG(WARNING) << "Failed to get least common schema: " << st.to_string();
1318
0
                    st = Status::InternalError("Failed to get least common schema: {}",
1319
0
                                               st.to_string());
1320
0
                }
1321
0
                VLOG_DEBUG << "dump schema:" << merged_schema->dump_structure();
1322
0
                merged_schema->reserve_extracted_columns();
1323
0
                merged_schema->to_schema_pb(response->mutable_merged_schema());
1324
0
            }
1325
0
            st.to_protobuf(response->mutable_status());
1326
0
            return;
1327
0
        } else {
1328
            // This is not a coordinator, get it's tablet and merge schema
1329
0
            std::vector<int64_t> target_tablets;
1330
0
            for (int i = 0; i < request->tablet_location_size(); ++i) {
1331
0
                const auto& location = request->tablet_location(i);
1332
0
                auto backend = BackendOptions::get_local_backend();
1333
                // If this is the target backend
1334
0
                if (backend.host == location.host() && config::brpc_port == location.brpc_port()) {
1335
0
                    target_tablets.assign(location.tablet_id().begin(), location.tablet_id().end());
1336
0
                    break;
1337
0
                }
1338
0
            }
1339
0
            if (!target_tablets.empty()) {
1340
0
                std::vector<TabletSchemaSPtr> tablet_schemas;
1341
0
                for (int64_t tablet_id : target_tablets) {
1342
0
                    auto res = ExecEnv::get_tablet(tablet_id);
1343
0
                    if (!res.has_value()) {
1344
                        // just ignore
1345
0
                        LOG(WARNING) << "tablet does not exist, tablet id is " << tablet_id;
1346
0
                        continue;
1347
0
                    }
1348
0
                    auto tablet = res.value();
1349
0
                    auto rowsets = tablet->get_snapshot_rowset();
1350
0
                    auto schema =
1351
0
                            variant_util::VariantCompactionUtil::calculate_variant_extended_schema(
1352
0
                                    rowsets, tablet->tablet_schema());
1353
0
                    tablet_schemas.push_back(schema);
1354
0
                }
1355
0
                if (!tablet_schemas.empty()) {
1356
                    // merge all
1357
0
                    TabletSchemaSPtr merged_schema;
1358
0
                    st = variant_util::get_least_common_schema(tablet_schemas, nullptr,
1359
0
                                                               merged_schema);
1360
0
                    if (!st.ok()) {
1361
0
                        LOG(WARNING) << "Failed to get least common schema: " << st.to_string();
1362
0
                        st = Status::InternalError("Failed to get least common schema: {}",
1363
0
                                                   st.to_string());
1364
0
                    }
1365
0
                    merged_schema->to_schema_pb(response->mutable_merged_schema());
1366
0
                    VLOG_DEBUG << "dump schema:" << merged_schema->dump_structure();
1367
0
                }
1368
0
            }
1369
0
            st.to_protobuf(response->mutable_status());
1370
0
        }
1371
0
    });
1372
0
    if (!ret) {
1373
0
        offer_failed(response, done, _heavy_work_pool);
1374
0
    }
1375
0
}
1376
1377
void PInternalService::report_stream_load_status(google::protobuf::RpcController* controller,
1378
                                                 const PReportStreamLoadStatusRequest* request,
1379
                                                 PReportStreamLoadStatusResponse* response,
1380
0
                                                 google::protobuf::Closure* done) {
1381
0
    TUniqueId load_id;
1382
0
    load_id.__set_hi(request->load_id().hi());
1383
0
    load_id.__set_lo(request->load_id().lo());
1384
0
    Status st = Status::OK();
1385
0
    auto stream_load_ctx = _exec_env->new_load_stream_mgr()->get(load_id);
1386
0
    if (!stream_load_ctx) {
1387
0
        st = Status::InternalError("unknown stream load id: {}", UniqueId(load_id).to_string());
1388
0
    }
1389
0
    stream_load_ctx->load_status_promise.set_value(st);
1390
0
    st.to_protobuf(response->mutable_status());
1391
0
}
1392
1393
void PInternalService::get_info(google::protobuf::RpcController* controller,
1394
                                const PProxyRequest* request, PProxyResult* response,
1395
0
                                google::protobuf::Closure* done) {
1396
0
    bool ret = _exec_env->routine_load_task_executor()->get_thread_pool().submit_func([this,
1397
0
                                                                                       request,
1398
0
                                                                                       response,
1399
0
                                                                                       done]() {
1400
0
        brpc::ClosureGuard closure_guard(done);
1401
        // PProxyRequest is defined in gensrc/proto/internal_service.proto
1402
        // Currently it supports 2 kinds of requests:
1403
        // 1. get all kafka partition ids for given topic
1404
        // 2. get all kafka partition offsets for given topic and timestamp.
1405
0
        int timeout_ms = request->has_timeout_secs() ? request->timeout_secs() * 1000 : 60 * 1000;
1406
0
        if (request->has_kafka_meta_request()) {
1407
0
            const PKafkaMetaProxyRequest& kafka_request = request->kafka_meta_request();
1408
0
            if (!kafka_request.offset_flags().empty()) {
1409
0
                std::vector<PIntegerPair> partition_offsets;
1410
0
                Status st = _exec_env->routine_load_task_executor()
1411
0
                                    ->get_kafka_real_offsets_for_partitions(
1412
0
                                            request->kafka_meta_request(), &partition_offsets,
1413
0
                                            timeout_ms);
1414
0
                if (st.ok()) {
1415
0
                    PKafkaPartitionOffsets* part_offsets = response->mutable_partition_offsets();
1416
0
                    for (const auto& entry : partition_offsets) {
1417
0
                        PIntegerPair* res = part_offsets->add_offset_times();
1418
0
                        res->set_key(entry.key());
1419
0
                        res->set_val(entry.val());
1420
0
                    }
1421
0
                }
1422
0
                st.to_protobuf(response->mutable_status());
1423
0
                return;
1424
0
            } else if (!kafka_request.partition_id_for_latest_offsets().empty()) {
1425
                // get latest offsets for specified partition ids
1426
0
                std::vector<PIntegerPair> partition_offsets;
1427
0
                Status st = _exec_env->routine_load_task_executor()
1428
0
                                    ->get_kafka_latest_offsets_for_partitions(
1429
0
                                            request->kafka_meta_request(), &partition_offsets,
1430
0
                                            timeout_ms);
1431
0
                if (st.ok()) {
1432
0
                    PKafkaPartitionOffsets* part_offsets = response->mutable_partition_offsets();
1433
0
                    for (const auto& entry : partition_offsets) {
1434
0
                        PIntegerPair* res = part_offsets->add_offset_times();
1435
0
                        res->set_key(entry.key());
1436
0
                        res->set_val(entry.val());
1437
0
                    }
1438
0
                }
1439
0
                st.to_protobuf(response->mutable_status());
1440
0
                return;
1441
0
            } else if (!kafka_request.offset_times().empty()) {
1442
                // if offset_times() has elements, which means this request is to get offset by timestamp.
1443
0
                std::vector<PIntegerPair> partition_offsets;
1444
0
                Status st = _exec_env->routine_load_task_executor()
1445
0
                                    ->get_kafka_partition_offsets_for_times(
1446
0
                                            request->kafka_meta_request(), &partition_offsets,
1447
0
                                            timeout_ms);
1448
0
                if (st.ok()) {
1449
0
                    PKafkaPartitionOffsets* part_offsets = response->mutable_partition_offsets();
1450
0
                    for (const auto& entry : partition_offsets) {
1451
0
                        PIntegerPair* res = part_offsets->add_offset_times();
1452
0
                        res->set_key(entry.key());
1453
0
                        res->set_val(entry.val());
1454
0
                    }
1455
0
                }
1456
0
                st.to_protobuf(response->mutable_status());
1457
0
                return;
1458
0
            } else {
1459
                // get partition ids of topic
1460
0
                std::vector<int32_t> partition_ids;
1461
0
                Status st = _exec_env->routine_load_task_executor()->get_kafka_partition_meta(
1462
0
                        request->kafka_meta_request(), &partition_ids);
1463
0
                if (st.ok()) {
1464
0
                    PKafkaMetaProxyResult* kafka_result = response->mutable_kafka_meta_result();
1465
0
                    for (int32_t id : partition_ids) {
1466
0
                        kafka_result->add_partition_ids(id);
1467
0
                    }
1468
0
                }
1469
0
                st.to_protobuf(response->mutable_status());
1470
0
                return;
1471
0
            }
1472
0
        }
1473
0
        if (request->has_kinesis_meta_request()) {
1474
0
            std::vector<std::string> shard_ids;
1475
0
            Status st = _exec_env->routine_load_task_executor()->get_kinesis_shard_meta(
1476
0
                    request->kinesis_meta_request(), &shard_ids);
1477
0
            if (st.ok()) {
1478
0
                PKinesisMetaProxyResult* kinesis_result = response->mutable_kinesis_meta_result();
1479
0
                for (const auto& shard_id : shard_ids) {
1480
0
                    kinesis_result->add_shard_ids(shard_id);
1481
0
                }
1482
0
            }
1483
0
            st.to_protobuf(response->mutable_status());
1484
0
            return;
1485
0
        }
1486
0
        Status::OK().to_protobuf(response->mutable_status());
1487
0
    });
1488
0
    if (!ret) {
1489
0
        offer_failed(response, done, _heavy_work_pool);
1490
0
        return;
1491
0
    }
1492
0
}
1493
1494
void PInternalService::update_cache(google::protobuf::RpcController* controller,
1495
                                    const PUpdateCacheRequest* request, PCacheResponse* response,
1496
0
                                    google::protobuf::Closure* done) {
1497
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1498
0
        brpc::ClosureGuard closure_guard(done);
1499
0
        _exec_env->result_cache()->update(request, response);
1500
0
    });
1501
0
    if (!ret) {
1502
0
        offer_failed(response, done, _light_work_pool);
1503
0
        return;
1504
0
    }
1505
0
}
1506
1507
void PInternalService::fetch_cache(google::protobuf::RpcController* controller,
1508
                                   const PFetchCacheRequest* request, PFetchCacheResult* result,
1509
0
                                   google::protobuf::Closure* done) {
1510
0
    bool ret = _light_work_pool.try_offer([this, request, result, done]() {
1511
0
        brpc::ClosureGuard closure_guard(done);
1512
0
        _exec_env->result_cache()->fetch(request, result);
1513
0
    });
1514
0
    if (!ret) {
1515
0
        offer_failed(result, done, _light_work_pool);
1516
0
        return;
1517
0
    }
1518
0
}
1519
1520
void PInternalService::clear_cache(google::protobuf::RpcController* controller,
1521
                                   const PClearCacheRequest* request, PCacheResponse* response,
1522
0
                                   google::protobuf::Closure* done) {
1523
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1524
0
        brpc::ClosureGuard closure_guard(done);
1525
0
        _exec_env->result_cache()->clear(request, response);
1526
0
    });
1527
0
    if (!ret) {
1528
0
        offer_failed(response, done, _light_work_pool);
1529
0
        return;
1530
0
    }
1531
0
}
1532
1533
void PInternalService::merge_filter(::google::protobuf::RpcController* controller,
1534
                                    const ::doris::PMergeFilterRequest* request,
1535
                                    ::doris::PMergeFilterResponse* response,
1536
0
                                    ::google::protobuf::Closure* done) {
1537
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
1538
0
        signal::SignalTaskIdKeeper keeper(request->query_id());
1539
0
        brpc::ClosureGuard closure_guard(done);
1540
0
        auto attachment = static_cast<brpc::Controller*>(controller)->request_attachment();
1541
0
        butil::IOBufAsZeroCopyInputStream zero_copy_input_stream(attachment);
1542
0
        Status st;
1543
0
        try {
1544
0
            st = _exec_env->fragment_mgr()->merge_filter(request, &zero_copy_input_stream);
1545
0
        } catch (Exception& e) {
1546
0
            st = e.to_status();
1547
0
        }
1548
0
        st.to_protobuf(response->mutable_status());
1549
0
    });
1550
0
    if (!ret) {
1551
0
        offer_failed(response, done, _light_work_pool);
1552
0
        return;
1553
0
    }
1554
0
}
1555
1556
void PInternalService::send_filter_size(::google::protobuf::RpcController* controller,
1557
                                        const ::doris::PSendFilterSizeRequest* request,
1558
                                        ::doris::PSendFilterSizeResponse* response,
1559
0
                                        ::google::protobuf::Closure* done) {
1560
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1561
0
        signal::SignalTaskIdKeeper keeper(request->query_id());
1562
0
        brpc::ClosureGuard closure_guard(done);
1563
0
        Status st;
1564
0
        try {
1565
0
            st = _exec_env->fragment_mgr()->send_filter_size(request);
1566
0
        } catch (Exception& e) {
1567
0
            st = e.to_status();
1568
0
        }
1569
0
        st.to_protobuf(response->mutable_status());
1570
0
    });
1571
0
    if (!ret) {
1572
0
        offer_failed(response, done, _light_work_pool);
1573
0
        return;
1574
0
    }
1575
0
}
1576
1577
void PInternalService::sync_filter_size(::google::protobuf::RpcController* controller,
1578
                                        const ::doris::PSyncFilterSizeRequest* request,
1579
                                        ::doris::PSyncFilterSizeResponse* response,
1580
0
                                        ::google::protobuf::Closure* done) {
1581
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1582
0
        signal::SignalTaskIdKeeper keeper(request->query_id());
1583
0
        brpc::ClosureGuard closure_guard(done);
1584
0
        Status st;
1585
0
        try {
1586
0
            st = _exec_env->fragment_mgr()->sync_filter_size(request);
1587
0
        } catch (Exception& e) {
1588
0
            st = e.to_status();
1589
0
        }
1590
0
        st.to_protobuf(response->mutable_status());
1591
0
    });
1592
0
    if (!ret) {
1593
0
        offer_failed(response, done, _light_work_pool);
1594
0
        return;
1595
0
    }
1596
0
}
1597
1598
void PInternalService::apply_filterv2(::google::protobuf::RpcController* controller,
1599
                                      const ::doris::PPublishFilterRequestV2* request,
1600
                                      ::doris::PPublishFilterResponse* response,
1601
0
                                      ::google::protobuf::Closure* done) {
1602
0
    bool ret = _light_work_pool.try_offer([this, controller, request, response, done]() {
1603
0
        signal::SignalTaskIdKeeper keeper(request->query_id());
1604
0
        brpc::ClosureGuard closure_guard(done);
1605
0
        const butil::IOBuf& request_attachment =
1606
0
                static_cast<brpc::Controller*>(controller)->request_attachment();
1607
0
        butil::IOBuf apply_attachment = request_attachment;
1608
0
        butil::IOBuf forward_attachment = request_attachment;
1609
0
        butil::IOBufAsZeroCopyInputStream zero_copy_input_stream(apply_attachment);
1610
0
        VLOG_NOTICE << "rpc apply_filterv2 recv";
1611
0
        Status st;
1612
0
        try {
1613
0
            st = _exec_env->fragment_mgr()->apply_filterv2(request, &zero_copy_input_stream);
1614
0
        } catch (Exception& e) {
1615
0
            st = e.to_status();
1616
0
        }
1617
0
        if (!st.ok()) {
1618
0
            LOG(WARNING) << "apply filter meet error: " << st.to_string();
1619
0
        }
1620
0
        std::weak_ptr<QueryContext> forward_ctx;
1621
0
        if (auto query_ctx = _exec_env->fragment_mgr()->get_query_ctx(
1622
0
                    UniqueId(request->query_id()).to_thrift())) {
1623
0
            if (!query_ctx->ignore_runtime_filter_error()) {
1624
0
                forward_ctx = query_ctx;
1625
0
            }
1626
0
        }
1627
0
        Status forward_st = forward_runtime_filter(*request, forward_attachment, forward_ctx);
1628
0
        if (!forward_st.ok()) {
1629
0
            LOG(WARNING) << "forward runtime filter meet error: " << forward_st.to_string();
1630
0
            if (st.ok()) {
1631
0
                st = std::move(forward_st);
1632
0
            }
1633
0
        }
1634
0
        st.to_protobuf(response->mutable_status());
1635
0
    });
1636
0
    if (!ret) {
1637
0
        offer_failed(response, done, _light_work_pool);
1638
0
        return;
1639
0
    }
1640
0
}
1641
1642
void PInternalService::send_data(google::protobuf::RpcController* controller,
1643
                                 const PSendDataRequest* request, PSendDataResult* response,
1644
0
                                 google::protobuf::Closure* done) {
1645
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done]() {
1646
0
        brpc::ClosureGuard closure_guard(done);
1647
0
        TUniqueId load_id;
1648
0
        load_id.hi = request->load_id().hi();
1649
0
        load_id.lo = request->load_id().lo();
1650
        // On 1.2.3 we add load id to send data request and using load id to get pipe
1651
0
        auto stream_load_ctx = _exec_env->new_load_stream_mgr()->get(load_id);
1652
0
        if (stream_load_ctx == nullptr) {
1653
0
            response->mutable_status()->set_status_code(1);
1654
0
            response->mutable_status()->add_error_msgs("could not find stream load context");
1655
0
        } else {
1656
0
            auto pipe = stream_load_ctx->pipe;
1657
0
            for (int i = 0; i < request->data_size(); ++i) {
1658
0
                std::unique_ptr<PDataRow> row(new PDataRow());
1659
0
                row->CopyFrom(request->data(i));
1660
0
                Status s = pipe->append(std::move(row));
1661
0
                if (!s.ok()) {
1662
0
                    response->mutable_status()->set_status_code(1);
1663
0
                    response->mutable_status()->add_error_msgs(s.to_string());
1664
0
                    return;
1665
0
                }
1666
0
            }
1667
0
            response->mutable_status()->set_status_code(0);
1668
0
        }
1669
0
    });
1670
0
    if (!ret) {
1671
0
        offer_failed(response, done, _heavy_work_pool);
1672
0
        return;
1673
0
    }
1674
0
}
1675
1676
void PInternalService::commit(google::protobuf::RpcController* controller,
1677
                              const PCommitRequest* request, PCommitResult* response,
1678
0
                              google::protobuf::Closure* done) {
1679
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done]() {
1680
0
        brpc::ClosureGuard closure_guard(done);
1681
0
        TUniqueId load_id;
1682
0
        load_id.hi = request->load_id().hi();
1683
0
        load_id.lo = request->load_id().lo();
1684
1685
0
        auto stream_load_ctx = _exec_env->new_load_stream_mgr()->get(load_id);
1686
0
        if (stream_load_ctx == nullptr) {
1687
0
            response->mutable_status()->set_status_code(1);
1688
0
            response->mutable_status()->add_error_msgs("could not find stream load context");
1689
0
        } else {
1690
0
            static_cast<void>(stream_load_ctx->pipe->finish());
1691
0
            response->mutable_status()->set_status_code(0);
1692
0
        }
1693
0
    });
1694
0
    if (!ret) {
1695
0
        offer_failed(response, done, _heavy_work_pool);
1696
0
        return;
1697
0
    }
1698
0
}
1699
1700
void PInternalService::rollback(google::protobuf::RpcController* controller,
1701
                                const PRollbackRequest* request, PRollbackResult* response,
1702
0
                                google::protobuf::Closure* done) {
1703
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done]() {
1704
0
        brpc::ClosureGuard closure_guard(done);
1705
0
        TUniqueId load_id;
1706
0
        load_id.hi = request->load_id().hi();
1707
0
        load_id.lo = request->load_id().lo();
1708
0
        auto stream_load_ctx = _exec_env->new_load_stream_mgr()->get(load_id);
1709
0
        if (stream_load_ctx == nullptr) {
1710
0
            response->mutable_status()->set_status_code(1);
1711
0
            response->mutable_status()->add_error_msgs("could not find stream load context");
1712
0
        } else {
1713
0
            stream_load_ctx->pipe->cancel("rollback");
1714
0
            response->mutable_status()->set_status_code(0);
1715
0
        }
1716
0
    });
1717
0
    if (!ret) {
1718
0
        offer_failed(response, done, _heavy_work_pool);
1719
0
        return;
1720
0
    }
1721
0
}
1722
1723
void PInternalService::fold_constant_expr(google::protobuf::RpcController* controller,
1724
                                          const PConstantExprRequest* request,
1725
                                          PConstantExprResult* response,
1726
0
                                          google::protobuf::Closure* done) {
1727
0
    bool ret = _light_work_pool.try_offer([request, response, done]() {
1728
0
        brpc::ClosureGuard closure_guard(done);
1729
0
        TFoldConstantParams t_request;
1730
0
        Status st = Status::OK();
1731
0
        {
1732
0
            const uint8_t* buf = (const uint8_t*)request->request().data();
1733
0
            uint32_t len = request->request().size();
1734
0
            st = deserialize_thrift_msg(buf, &len, false, &t_request);
1735
0
        }
1736
0
        if (!st.ok()) {
1737
0
            LOG(WARNING) << "exec fold constant expr failed, errmsg=" << st
1738
0
                         << " .and query_id_is: " << t_request.query_id;
1739
0
            st.to_protobuf(response->mutable_status());
1740
0
            return;
1741
0
        }
1742
0
        auto fold_func = [&]() -> Status {
1743
0
            std::unique_ptr<FoldConstantExecutor> fold_executor =
1744
0
                    std::make_unique<FoldConstantExecutor>();
1745
0
            RETURN_IF_ERROR_OR_CATCH_EXCEPTION(
1746
0
                    fold_executor->fold_constant_vexpr(t_request, response));
1747
0
            return Status::OK();
1748
0
        };
1749
0
        st = fold_func();
1750
0
        if (!st.ok()) {
1751
0
            LOG(WARNING) << "exec fold constant expr failed, errmsg=" << st
1752
0
                         << " .and query_id_is: " << t_request.query_id;
1753
0
        }
1754
0
        st.to_protobuf(response->mutable_status());
1755
0
    });
1756
0
    if (!ret) {
1757
0
        offer_failed(response, done, _light_work_pool);
1758
0
        return;
1759
0
    }
1760
0
}
1761
1762
void PInternalService::transmit_rec_cte_block(google::protobuf::RpcController* controller,
1763
                                              const PTransmitRecCTEBlockParams* request,
1764
                                              PTransmitRecCTEBlockResult* response,
1765
0
                                              google::protobuf::Closure* done) {
1766
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1767
0
        brpc::ClosureGuard closure_guard(done);
1768
0
        auto st = _exec_env->fragment_mgr()->transmit_rec_cte_block(
1769
0
                UniqueId(request->query_id()).to_thrift(),
1770
0
                UniqueId(request->fragment_instance_id()).to_thrift(), request->node_id(),
1771
0
                request->blocks(), request->eos());
1772
0
        st.to_protobuf(response->mutable_status());
1773
0
    });
1774
0
    if (!ret) {
1775
0
        offer_failed(response, done, _light_work_pool);
1776
0
        return;
1777
0
    }
1778
0
}
1779
1780
void PInternalService::rerun_fragment(google::protobuf::RpcController* controller,
1781
                                      const PRerunFragmentParams* request,
1782
                                      PRerunFragmentResult* response,
1783
0
                                      google::protobuf::Closure* done) {
1784
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1785
        // Use shared_ptr<ClosureGuard> so we can transfer ownership to the PFC.
1786
        // For wait_for_destroy/final_close, the guard is stored in the PFC and the RPC
1787
        // response is deferred until the PFC is fully destroyed. For rebuild/submit,
1788
        // the guard fires immediately when this lambda returns.
1789
0
        std::shared_ptr<brpc::ClosureGuard> closure_guard =
1790
0
                std::make_shared<brpc::ClosureGuard>(done);
1791
0
        auto st = _exec_env->fragment_mgr()->rerun_fragment(
1792
0
                closure_guard, UniqueId(request->query_id()).to_thrift(), request->fragment_id(),
1793
0
                request->stage());
1794
0
        st.to_protobuf(response->mutable_status());
1795
0
    });
1796
0
    if (!ret) {
1797
0
        offer_failed(response, done, _light_work_pool);
1798
0
        return;
1799
0
    }
1800
0
}
1801
1802
void PInternalService::reset_global_rf(google::protobuf::RpcController* controller,
1803
                                       const PResetGlobalRfParams* request,
1804
                                       PResetGlobalRfResult* response,
1805
0
                                       google::protobuf::Closure* done) {
1806
0
    bool ret = _light_work_pool.try_offer([this, request, response, done]() {
1807
0
        brpc::ClosureGuard closure_guard(done);
1808
0
        auto st = _exec_env->fragment_mgr()->reset_global_rf(
1809
0
                UniqueId(request->query_id()).to_thrift(), request->filter_ids());
1810
0
        st.to_protobuf(response->mutable_status());
1811
0
    });
1812
0
    if (!ret) {
1813
0
        offer_failed(response, done, _light_work_pool);
1814
0
        return;
1815
0
    }
1816
0
}
1817
1818
void PInternalService::transmit_block(google::protobuf::RpcController* controller,
1819
                                      const PTransmitDataParams* request,
1820
                                      PTransmitDataResult* response,
1821
0
                                      google::protobuf::Closure* done) {
1822
0
    int64_t receive_time = GetCurrentTimeNanos();
1823
0
    if (config::enable_bthread_transmit_block) {
1824
0
        response->set_receive_time(receive_time);
1825
        // under high concurrency, thread pool will have a lot of lock contention.
1826
        // May offer failed to the thread pool, so that we should avoid using thread
1827
        // pool here.
1828
0
        _transmit_block(controller, request, response, done, Status::OK(), 0);
1829
0
    } else {
1830
0
        bool ret = _light_work_pool.try_offer([this, controller, request, response, done,
1831
0
                                               receive_time]() {
1832
0
            response->set_receive_time(receive_time);
1833
            // Sometimes transmit block function is the last owner of PlanFragmentExecutor
1834
            // It will release the object. And the object maybe a JNIContext.
1835
            // JNIContext will hold some TLS object. It could not work correctly under bthread
1836
            // Context. So that put the logic into pthread.
1837
            // But this is rarely happens, so this config is disabled by default.
1838
0
            _transmit_block(controller, request, response, done, Status::OK(),
1839
0
                            GetCurrentTimeNanos() - receive_time);
1840
0
        });
1841
0
        if (!ret) {
1842
0
            offer_failed(response, done, _light_work_pool);
1843
0
            return;
1844
0
        }
1845
0
    }
1846
0
}
1847
1848
void PInternalService::transmit_block_by_http(google::protobuf::RpcController* controller,
1849
                                              const PEmptyRequest* request,
1850
                                              PTransmitDataResult* response,
1851
0
                                              google::protobuf::Closure* done) {
1852
0
    int64_t receive_time = GetCurrentTimeNanos();
1853
0
    bool ret = _heavy_work_pool.try_offer([this, controller, response, done, receive_time]() {
1854
0
        PTransmitDataParams* new_request = new PTransmitDataParams();
1855
0
        google::protobuf::Closure* new_done =
1856
0
                new NewHttpClosure<PTransmitDataParams>(new_request, done);
1857
0
        brpc::Controller* cntl = static_cast<brpc::Controller*>(controller);
1858
0
        Status st =
1859
0
                attachment_extract_request_contain_block<PTransmitDataParams>(new_request, cntl);
1860
0
        _transmit_block(controller, new_request, response, new_done, st,
1861
0
                        GetCurrentTimeNanos() - receive_time);
1862
0
    });
1863
0
    if (!ret) {
1864
0
        offer_failed(response, done, _heavy_work_pool);
1865
0
        return;
1866
0
    }
1867
0
}
1868
1869
void PInternalService::_transmit_block(google::protobuf::RpcController* controller,
1870
                                       const PTransmitDataParams* request,
1871
                                       PTransmitDataResult* response,
1872
                                       google::protobuf::Closure* done, const Status& extract_st,
1873
0
                                       const int64_t wait_for_worker) {
1874
0
    if (request->has_query_id()) {
1875
0
        VLOG_ROW << "transmit block: fragment_instance_id=" << print_id(request->finst_id())
1876
0
                 << " query_id=" << print_id(request->query_id()) << " node=" << request->node_id();
1877
0
    }
1878
1879
    // The response is accessed when done->Run is called in transmit_block(),
1880
    // give response a default value to avoid null pointers in high concurrency.
1881
0
    Status st;
1882
0
    if (extract_st.ok()) {
1883
0
        st = _exec_env->vstream_mgr()->transmit_block(request, &done, wait_for_worker);
1884
0
        if (!st.ok() && !st.is<END_OF_FILE>()) {
1885
0
            LOG(WARNING) << "transmit_block failed, message=" << st
1886
0
                         << ", fragment_instance_id=" << print_id(request->finst_id())
1887
0
                         << ", node=" << request->node_id()
1888
0
                         << ", from sender_id: " << request->sender_id()
1889
0
                         << ", be_number: " << request->be_number()
1890
0
                         << ", packet_seq: " << request->packet_seq();
1891
0
        }
1892
0
    } else {
1893
0
        st = extract_st;
1894
0
    }
1895
0
    if (done != nullptr) {
1896
0
        st.to_protobuf(response->mutable_status());
1897
0
        done->Run();
1898
0
    }
1899
0
}
1900
1901
void PInternalService::check_rpc_channel(google::protobuf::RpcController* controller,
1902
                                         const PCheckRPCChannelRequest* request,
1903
                                         PCheckRPCChannelResponse* response,
1904
0
                                         google::protobuf::Closure* done) {
1905
0
    bool ret = _light_work_pool.try_offer([request, response, done]() {
1906
0
        brpc::ClosureGuard closure_guard(done);
1907
0
        response->mutable_status()->set_status_code(0);
1908
0
        if (request->data().size() != request->size()) {
1909
0
            std::stringstream ss;
1910
0
            ss << "data size not same, expected: " << request->size()
1911
0
               << ", actual: " << request->data().size();
1912
0
            response->mutable_status()->add_error_msgs(ss.str());
1913
0
            response->mutable_status()->set_status_code(1);
1914
1915
0
        } else {
1916
0
            Md5Digest digest;
1917
0
            digest.update(static_cast<const void*>(request->data().c_str()),
1918
0
                          request->data().size());
1919
0
            digest.digest();
1920
0
            if (!iequal(digest.hex(), request->md5())) {
1921
0
                std::stringstream ss;
1922
0
                ss << "md5 not same, expected: " << request->md5() << ", actual: " << digest.hex();
1923
0
                response->mutable_status()->add_error_msgs(ss.str());
1924
0
                response->mutable_status()->set_status_code(1);
1925
0
            }
1926
0
        }
1927
0
    });
1928
0
    if (!ret) {
1929
0
        offer_failed(response, done, _light_work_pool);
1930
0
        return;
1931
0
    }
1932
0
}
1933
1934
void PInternalService::reset_rpc_channel(google::protobuf::RpcController* controller,
1935
                                         const PResetRPCChannelRequest* request,
1936
                                         PResetRPCChannelResponse* response,
1937
0
                                         google::protobuf::Closure* done) {
1938
0
    bool ret = _light_work_pool.try_offer([request, response, done]() {
1939
0
        brpc::ClosureGuard closure_guard(done);
1940
0
        response->mutable_status()->set_status_code(0);
1941
0
        if (request->all()) {
1942
0
            int size = ExecEnv::GetInstance()->brpc_internal_client_cache()->size();
1943
0
            if (size > 0) {
1944
0
                std::vector<std::string> endpoints;
1945
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->get_all(&endpoints);
1946
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->clear();
1947
0
                *response->mutable_channels() = {endpoints.begin(), endpoints.end()};
1948
0
            }
1949
0
        } else {
1950
0
            for (const std::string& endpoint : request->endpoints()) {
1951
0
                if (!ExecEnv::GetInstance()->brpc_internal_client_cache()->exist(endpoint)) {
1952
0
                    response->mutable_status()->add_error_msgs(endpoint + ": not found.");
1953
0
                    continue;
1954
0
                }
1955
1956
0
                if (ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(endpoint)) {
1957
0
                    response->add_channels(endpoint);
1958
0
                } else {
1959
0
                    response->mutable_status()->add_error_msgs(endpoint + ": reset failed.");
1960
0
                }
1961
0
            }
1962
0
            if (request->endpoints_size() != response->channels_size()) {
1963
0
                response->mutable_status()->set_status_code(1);
1964
0
            }
1965
0
        }
1966
0
    });
1967
0
    if (!ret) {
1968
0
        offer_failed(response, done, _light_work_pool);
1969
0
        return;
1970
0
    }
1971
0
}
1972
1973
void PInternalService::hand_shake(google::protobuf::RpcController* controller,
1974
                                  const PHandShakeRequest* request, PHandShakeResponse* response,
1975
0
                                  google::protobuf::Closure* done) {
1976
    // The light pool may be full. Handshake is used to check the connection state of brpc.
1977
    // Should not be interfered by the thread pool logic.
1978
0
    brpc::ClosureGuard closure_guard(done);
1979
0
    if (request->has_hello()) {
1980
0
        response->set_hello(request->hello());
1981
0
    }
1982
0
    response->mutable_status()->set_status_code(0);
1983
0
}
1984
1985
constexpr char HttpProtocol[] = "http://";
1986
constexpr char DownloadApiPath[] = "/api/_tablet/_download?token=";
1987
constexpr char FileParam[] = "&file=";
1988
1989
static std::string construct_url(const std::string& host_port, const std::string& token,
1990
0
                                 const std::string& path) {
1991
0
    return fmt::format("{}{}{}{}{}{}", HttpProtocol, host_port, DownloadApiPath, token, FileParam,
1992
0
                       path);
1993
0
}
1994
1995
static Status download_file_action(std::string& remote_file_url, std::string& local_file_path,
1996
0
                                   uint64_t estimate_timeout, uint64_t file_size) {
1997
0
    auto download_cb = [remote_file_url, estimate_timeout, local_file_path,
1998
0
                        file_size](HttpClient* client) {
1999
0
        RETURN_IF_ERROR(client->init(remote_file_url));
2000
0
        client->set_timeout_ms(estimate_timeout * 1000);
2001
0
        RETURN_IF_ERROR(client->download(local_file_path));
2002
2003
0
        if (file_size > 0) {
2004
            // Check file length
2005
0
            uint64_t local_file_size = std::filesystem::file_size(local_file_path);
2006
0
            if (local_file_size != file_size) {
2007
0
                LOG(WARNING) << "failed to pull rowset for slave replica. download file "
2008
0
                                "length error"
2009
0
                             << ", remote_path=" << remote_file_url << ", file_size=" << file_size
2010
0
                             << ", local_file_size=" << local_file_size;
2011
0
                return Status::InternalError("downloaded file size is not equal");
2012
0
            }
2013
0
        }
2014
2015
0
        return io::global_local_filesystem()->permission(local_file_path,
2016
0
                                                         io::LocalFileSystem::PERMS_OWNER_RW);
2017
0
    };
2018
0
    return HttpClient::execute_with_retry(DOWNLOAD_FILE_MAX_RETRY, 1, download_cb);
2019
0
}
2020
2021
void PInternalServiceImpl::request_slave_tablet_pull_rowset(
2022
        google::protobuf::RpcController* controller, const PTabletWriteSlaveRequest* request,
2023
0
        PTabletWriteSlaveResult* response, google::protobuf::Closure* done) {
2024
0
    brpc::ClosureGuard closure_guard(done);
2025
0
    const RowsetMetaPB& rowset_meta_pb = request->rowset_meta();
2026
0
    const std::string& rowset_path = request->rowset_path();
2027
0
    google::protobuf::Map<int64_t, int64_t> segments_size = request->segments_size();
2028
0
    google::protobuf::Map<int64_t, PTabletWriteSlaveRequest_IndexSizeMap> indices_size =
2029
0
            request->inverted_indices_size();
2030
0
    std::string host = request->host();
2031
0
    int64_t http_port = request->http_port();
2032
0
    int64_t brpc_port = request->brpc_port();
2033
0
    std::string token = request->token();
2034
0
    int64_t node_id = request->node_id();
2035
0
    bool ret = _heavy_work_pool.try_offer([rowset_meta_pb, host, brpc_port, node_id, segments_size,
2036
0
                                           indices_size, http_port, token, rowset_path, this]() {
2037
0
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(
2038
0
                rowset_meta_pb.tablet_id(), rowset_meta_pb.tablet_schema_hash());
2039
0
        if (tablet == nullptr) {
2040
0
            LOG(WARNING) << "failed to pull rowset for slave replica. tablet ["
2041
0
                         << rowset_meta_pb.tablet_id()
2042
0
                         << "] is not exist. txn_id=" << rowset_meta_pb.txn_id();
2043
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta_pb.txn_id(),
2044
0
                                        rowset_meta_pb.tablet_id(), node_id, false);
2045
0
            return;
2046
0
        }
2047
2048
0
        RowsetMetaSharedPtr rowset_meta(new RowsetMeta());
2049
0
        std::string rowset_meta_str;
2050
0
        bool ret = rowset_meta_pb.SerializeToString(&rowset_meta_str);
2051
0
        if (!ret) {
2052
0
            LOG(WARNING) << "failed to pull rowset for slave replica. serialize rowset meta "
2053
0
                            "failed. rowset_id="
2054
0
                         << rowset_meta_pb.rowset_id()
2055
0
                         << ", tablet_id=" << rowset_meta_pb.tablet_id()
2056
0
                         << ", txn_id=" << rowset_meta_pb.txn_id();
2057
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta_pb.txn_id(),
2058
0
                                        rowset_meta_pb.tablet_id(), node_id, false);
2059
0
            return;
2060
0
        }
2061
0
        bool parsed = rowset_meta->init(rowset_meta_str);
2062
0
        if (!parsed) {
2063
0
            LOG(WARNING) << "failed to pull rowset for slave replica. parse rowset meta string "
2064
0
                            "failed. rowset_id="
2065
0
                         << rowset_meta_pb.rowset_id()
2066
0
                         << ", tablet_id=" << rowset_meta_pb.tablet_id()
2067
0
                         << ", txn_id=" << rowset_meta_pb.txn_id();
2068
            // return false will break meta iterator, return true to skip this error
2069
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2070
0
                                        rowset_meta->tablet_id(), node_id, false);
2071
0
            return;
2072
0
        }
2073
0
        RowsetId remote_rowset_id = rowset_meta->rowset_id();
2074
        // change rowset id because it maybe same as other local rowset
2075
0
        RowsetId new_rowset_id = _engine.next_rowset_id();
2076
0
        auto pending_rs_guard = _engine.pending_local_rowsets().add(new_rowset_id);
2077
0
        rowset_meta->set_rowset_id(new_rowset_id);
2078
0
        rowset_meta->set_tablet_uid(tablet->tablet_uid());
2079
0
        VLOG_CRITICAL << "succeed to init rowset meta for slave replica. rowset_id="
2080
0
                      << rowset_meta->rowset_id() << ", tablet_id=" << rowset_meta->tablet_id()
2081
0
                      << ", txn_id=" << rowset_meta->txn_id();
2082
2083
0
        auto tablet_scheme = rowset_meta->tablet_schema();
2084
0
        for (const auto& segment : segments_size) {
2085
0
            uint64_t file_size = segment.second;
2086
0
            uint64_t estimate_timeout = file_size / config::download_low_speed_limit_kbps / 1024;
2087
0
            if (estimate_timeout < config::download_low_speed_time) {
2088
0
                estimate_timeout = config::download_low_speed_time;
2089
0
            }
2090
2091
0
            std::string remote_file_path =
2092
0
                    local_segment_path(rowset_path, remote_rowset_id.to_string(), segment.first);
2093
0
            std::string remote_file_url =
2094
0
                    construct_url(get_host_port(host, http_port), token, remote_file_path);
2095
2096
0
            std::string local_file_path = local_segment_path(
2097
0
                    tablet->tablet_path(), rowset_meta->rowset_id().to_string(), segment.first);
2098
2099
0
            auto st = download_file_action(remote_file_url, local_file_path, estimate_timeout,
2100
0
                                           file_size);
2101
0
            if (!st.ok()) {
2102
0
                LOG(WARNING) << "failed to pull rowset for slave replica. failed to download "
2103
0
                                "file. url="
2104
0
                             << remote_file_url << ", local_path=" << local_file_path
2105
0
                             << ", txn_id=" << rowset_meta->txn_id();
2106
0
                _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2107
0
                                            rowset_meta->tablet_id(), node_id, false);
2108
0
                return;
2109
0
            }
2110
0
            VLOG_CRITICAL << "succeed to download file for slave replica. url=" << remote_file_url
2111
0
                          << ", local_path=" << local_file_path
2112
0
                          << ", txn_id=" << rowset_meta->txn_id();
2113
0
            if (indices_size.find(segment.first) != indices_size.end()) {
2114
0
                PTabletWriteSlaveRequest_IndexSizeMap segment_indices_size =
2115
0
                        indices_size.at(segment.first);
2116
2117
0
                for (auto index_size : segment_indices_size.index_sizes()) {
2118
0
                    auto index_id = index_size.indexid();
2119
0
                    auto size = index_size.size();
2120
0
                    auto suffix_path = index_size.suffix_path();
2121
0
                    std::string remote_inverted_index_file;
2122
0
                    std::string local_inverted_index_file;
2123
0
                    std::string remote_inverted_index_file_url;
2124
0
                    if (tablet_scheme->get_inverted_index_storage_format() ==
2125
0
                        InvertedIndexStorageFormatPB::V1) {
2126
0
                        remote_inverted_index_file =
2127
0
                                InvertedIndexDescriptor::get_index_file_path_v1(
2128
0
                                        InvertedIndexDescriptor::get_index_file_path_prefix(
2129
0
                                                remote_file_path),
2130
0
                                        index_id, suffix_path);
2131
0
                        remote_inverted_index_file_url = construct_url(
2132
0
                                get_host_port(host, http_port), token, remote_inverted_index_file);
2133
2134
0
                        local_inverted_index_file = InvertedIndexDescriptor::get_index_file_path_v1(
2135
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(
2136
0
                                        local_file_path),
2137
0
                                index_id, suffix_path);
2138
0
                    } else {
2139
0
                        remote_inverted_index_file =
2140
0
                                InvertedIndexDescriptor::get_index_file_path_v2(
2141
0
                                        InvertedIndexDescriptor::get_index_file_path_prefix(
2142
0
                                                remote_file_path));
2143
0
                        remote_inverted_index_file_url = construct_url(
2144
0
                                get_host_port(host, http_port), token, remote_inverted_index_file);
2145
2146
0
                        local_inverted_index_file = InvertedIndexDescriptor::get_index_file_path_v2(
2147
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(
2148
0
                                        local_file_path));
2149
0
                    }
2150
0
                    st = download_file_action(remote_inverted_index_file_url,
2151
0
                                              local_inverted_index_file, estimate_timeout, size);
2152
0
                    if (!st.ok()) {
2153
0
                        LOG(WARNING) << "failed to pull rowset for slave replica. failed to "
2154
0
                                        "download "
2155
0
                                        "file. url="
2156
0
                                     << remote_inverted_index_file_url
2157
0
                                     << ", local_path=" << local_inverted_index_file
2158
0
                                     << ", txn_id=" << rowset_meta->txn_id();
2159
0
                        _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2160
0
                                                    rowset_meta->tablet_id(), node_id, false);
2161
0
                        return;
2162
0
                    }
2163
2164
0
                    VLOG_CRITICAL
2165
0
                            << "succeed to download inverted index file for slave replica. url="
2166
0
                            << remote_inverted_index_file_url
2167
0
                            << ", local_path=" << local_inverted_index_file
2168
0
                            << ", txn_id=" << rowset_meta->txn_id();
2169
0
                }
2170
0
            }
2171
0
        }
2172
2173
0
        RowsetSharedPtr rowset;
2174
0
        Status create_status = RowsetFactory::create_rowset(
2175
0
                tablet->tablet_schema(), tablet->tablet_path(), rowset_meta, &rowset);
2176
0
        if (!create_status) {
2177
0
            LOG(WARNING) << "failed to create rowset from rowset meta for slave replica"
2178
0
                         << ". rowset_id: " << rowset_meta->rowset_id()
2179
0
                         << ", rowset_type: " << rowset_meta->rowset_type()
2180
0
                         << ", rowset_state: " << rowset_meta->rowset_state()
2181
0
                         << ", tablet_id=" << rowset_meta->tablet_id()
2182
0
                         << ", txn_id=" << rowset_meta->txn_id();
2183
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2184
0
                                        rowset_meta->tablet_id(), node_id, false);
2185
0
            return;
2186
0
        }
2187
0
        if (rowset_meta->rowset_state() != RowsetStatePB::COMMITTED) {
2188
0
            LOG(WARNING) << "could not commit txn for slave replica because master rowset state is "
2189
0
                            "not committed, rowset_state="
2190
0
                         << rowset_meta->rowset_state()
2191
0
                         << ", tablet_id=" << rowset_meta->tablet_id()
2192
0
                         << ", txn_id=" << rowset_meta->txn_id();
2193
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2194
0
                                        rowset_meta->tablet_id(), node_id, false);
2195
0
            return;
2196
0
        }
2197
0
        Status commit_txn_status = _engine.txn_manager()->commit_txn(
2198
0
                tablet->data_dir()->get_meta(), rowset_meta->partition_id(), rowset_meta->txn_id(),
2199
0
                rowset_meta->tablet_id(), tablet->tablet_uid(), rowset_meta->load_id(), rowset,
2200
0
                std::move(pending_rs_guard), false);
2201
0
        if (!commit_txn_status && !commit_txn_status.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
2202
0
            LOG(WARNING) << "failed to add committed rowset for slave replica. rowset_id="
2203
0
                         << rowset_meta->rowset_id() << ", tablet_id=" << rowset_meta->tablet_id()
2204
0
                         << ", txn_id=" << rowset_meta->txn_id();
2205
0
            _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2206
0
                                        rowset_meta->tablet_id(), node_id, false);
2207
0
            return;
2208
0
        }
2209
0
        VLOG_CRITICAL << "succeed to pull rowset for slave replica. successfully to add committed "
2210
0
                         "rowset: "
2211
0
                      << rowset_meta->rowset_id()
2212
0
                      << " to tablet, tablet_id=" << rowset_meta->tablet_id()
2213
0
                      << ", schema_hash=" << rowset_meta->tablet_schema_hash()
2214
0
                      << ", txn_id=" << rowset_meta->txn_id();
2215
0
        _response_pull_slave_rowset(host, brpc_port, rowset_meta->txn_id(),
2216
0
                                    rowset_meta->tablet_id(), node_id, true);
2217
0
    });
2218
0
    if (!ret) {
2219
0
        offer_failed(response, closure_guard.release(), _heavy_work_pool);
2220
0
        return;
2221
0
    }
2222
0
    Status::OK().to_protobuf(response->mutable_status());
2223
0
}
2224
2225
void PInternalServiceImpl::_response_pull_slave_rowset(const std::string& remote_host,
2226
                                                       int64_t brpc_port, int64_t txn_id,
2227
                                                       int64_t tablet_id, int64_t node_id,
2228
0
                                                       bool is_succeed) {
2229
0
    std::shared_ptr<PBackendService_Stub> stub =
2230
0
            ExecEnv::GetInstance()->brpc_internal_client_cache()->get_client(remote_host,
2231
0
                                                                             brpc_port);
2232
0
    if (stub == nullptr) {
2233
0
        LOG(WARNING) << "failed to response result of slave replica to master replica. get rpc "
2234
0
                        "stub failed, master host="
2235
0
                     << remote_host << ", port=" << brpc_port << ", tablet_id=" << tablet_id
2236
0
                     << ", txn_id=" << txn_id;
2237
0
        return;
2238
0
    }
2239
2240
0
    auto request = std::make_shared<PTabletWriteSlaveDoneRequest>();
2241
0
    request->set_txn_id(txn_id);
2242
0
    request->set_tablet_id(tablet_id);
2243
0
    request->set_node_id(node_id);
2244
0
    request->set_is_succeed(is_succeed);
2245
0
    auto pull_rowset_callback = DummyBrpcCallback<PTabletWriteSlaveDoneResult>::create_shared();
2246
0
    auto closure = AutoReleaseClosure<
2247
0
            PTabletWriteSlaveDoneRequest,
2248
0
            DummyBrpcCallback<PTabletWriteSlaveDoneResult>>::create_unique(request,
2249
0
                                                                           pull_rowset_callback);
2250
0
    closure->cntl_->set_timeout_ms(config::slave_replica_writer_rpc_timeout_sec * 1000);
2251
0
    closure->cntl_->ignore_eovercrowded();
2252
0
    stub->response_slave_tablet_pull_rowset(closure->cntl_.get(), closure->request_.get(),
2253
0
                                            closure->response_.get(), closure.get());
2254
0
    closure.release();
2255
2256
0
    pull_rowset_callback->join();
2257
0
    if (pull_rowset_callback->cntl_->Failed()) {
2258
0
        LOG(WARNING) << "failed to response result of slave replica to master replica, error="
2259
0
                     << berror(pull_rowset_callback->cntl_->ErrorCode())
2260
0
                     << ", error_text=" << pull_rowset_callback->cntl_->ErrorText()
2261
0
                     << ", master host: " << remote_host << ", tablet_id=" << tablet_id
2262
0
                     << ", txn_id=" << txn_id;
2263
0
    }
2264
0
    VLOG_CRITICAL << "succeed to response the result of slave replica pull rowset to master "
2265
0
                     "replica. master host: "
2266
0
                  << remote_host << ". is_succeed=" << is_succeed << ", tablet_id=" << tablet_id
2267
0
                  << ", slave server=" << node_id << ", txn_id=" << txn_id;
2268
0
}
2269
2270
void PInternalServiceImpl::response_slave_tablet_pull_rowset(
2271
        google::protobuf::RpcController* controller, const PTabletWriteSlaveDoneRequest* request,
2272
0
        PTabletWriteSlaveDoneResult* response, google::protobuf::Closure* done) {
2273
0
    bool ret = _heavy_work_pool.try_offer([txn_mgr = _engine.txn_manager(), request, response,
2274
0
                                           done]() {
2275
0
        brpc::ClosureGuard closure_guard(done);
2276
0
        VLOG_CRITICAL << "receive the result of slave replica pull rowset from slave replica. "
2277
0
                         "slave server="
2278
0
                      << request->node_id() << ", is_succeed=" << request->is_succeed()
2279
0
                      << ", tablet_id=" << request->tablet_id() << ", txn_id=" << request->txn_id();
2280
0
        txn_mgr->finish_slave_tablet_pull_rowset(request->txn_id(), request->tablet_id(),
2281
0
                                                 request->node_id(), request->is_succeed());
2282
0
        Status::OK().to_protobuf(response->mutable_status());
2283
0
    });
2284
0
    if (!ret) {
2285
0
        offer_failed(response, done, _heavy_work_pool);
2286
0
        return;
2287
0
    }
2288
0
}
2289
2290
void PInternalService::multiget_data(google::protobuf::RpcController* controller,
2291
                                     const PMultiGetRequest* request, PMultiGetResponse* response,
2292
0
                                     google::protobuf::Closure* done) {
2293
0
    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
2294
0
        signal::SignalTaskIdKeeper keeper(request->query_id());
2295
        // multi get data by rowid
2296
0
        MonotonicStopWatch watch;
2297
0
        watch.start();
2298
0
        brpc::ClosureGuard closure_guard(done);
2299
0
        response->mutable_status()->set_status_code(0);
2300
0
        SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
2301
0
        Status st = RowIdStorageReader::read_by_rowids(*request, response);
2302
0
        st.to_protobuf(response->mutable_status());
2303
0
        LOG(INFO) << "multiget_data finished, cost(us):" << watch.elapsed_time() / 1000;
2304
0
    });
2305
0
    if (!ret) {
2306
0
        offer_failed(response, done, _heavy_work_pool);
2307
0
        return;
2308
0
    }
2309
0
}
2310
2311
void PInternalService::multiget_data_v2(google::protobuf::RpcController* controller,
2312
                                        const PMultiGetRequestV2* request,
2313
                                        PMultiGetResponseV2* response,
2314
0
                                        google::protobuf::Closure* done) {
2315
0
    std::vector<uint64_t> id_set;
2316
0
    id_set.push_back(request->wg_id());
2317
0
    auto wg = ExecEnv::GetInstance()->workload_group_mgr()->get_group(id_set);
2318
0
    Status st = Status::OK();
2319
2320
0
    if (!wg) [[unlikely]] {
2321
0
        brpc::ClosureGuard closure_guard(done);
2322
0
        st = Status::Error<TStatusCode::CANCELLED>("fail to find wg: wg id:" +
2323
0
                                                   std::to_string(request->wg_id()));
2324
0
        st.to_protobuf(response->mutable_status());
2325
0
        return;
2326
0
    }
2327
2328
0
    doris::TaskScheduler* exec_sched = nullptr;
2329
0
    ScannerScheduler* scan_sched = nullptr;
2330
0
    ScannerScheduler* remote_scan_sched = nullptr;
2331
0
    wg->get_query_scheduler(&exec_sched, &scan_sched, &remote_scan_sched);
2332
0
    DCHECK(remote_scan_sched);
2333
2334
0
    st = remote_scan_sched->submit_scan_task(
2335
0
            SimplifiedScanTask(
2336
0
                    [request, response, done]() {
2337
0
                        SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->rowid_storage_reader_tracker());
2338
0
                        signal::set_signal_task_id(request->query_id());
2339
                        // multi get data by rowid
2340
0
                        MonotonicStopWatch watch;
2341
0
                        watch.start();
2342
0
                        brpc::ClosureGuard closure_guard(done);
2343
0
                        response->mutable_status()->set_status_code(0);
2344
0
                        Status st = RowIdStorageReader::read_by_rowids(*request, response);
2345
0
                        st.to_protobuf(response->mutable_status());
2346
0
                        LOG(INFO) << "multiget_data finished, cost(us):"
2347
0
                                  << watch.elapsed_time() / 1000;
2348
0
                        return true;
2349
0
                    },
2350
0
                    nullptr, nullptr),
2351
0
            fmt::format("{}-multiget_data_v2", print_id(request->query_id())));
2352
2353
0
    if (!st.ok()) {
2354
0
        brpc::ClosureGuard closure_guard(done);
2355
0
        st.to_protobuf(response->mutable_status());
2356
0
    }
2357
0
}
2358
2359
void PInternalServiceImpl::get_tablet_rowset_versions(google::protobuf::RpcController* cntl_base,
2360
                                                      const PGetTabletVersionsRequest* request,
2361
                                                      PGetTabletVersionsResponse* response,
2362
0
                                                      google::protobuf::Closure* done) {
2363
0
    brpc::ClosureGuard closure_guard(done);
2364
0
    VLOG_DEBUG << "receive get tablet versions request: " << request->DebugString();
2365
0
    _engine.get_tablet_rowset_versions(request, response);
2366
0
}
2367
2368
void PInternalService::glob(google::protobuf::RpcController* controller,
2369
                            const PGlobRequest* request, PGlobResponse* response,
2370
0
                            google::protobuf::Closure* done) {
2371
0
    bool ret = _heavy_work_pool.try_offer([request, response, done]() {
2372
0
        brpc::ClosureGuard closure_guard(done);
2373
0
        std::vector<io::FileInfo> files;
2374
0
        Status st = io::global_local_filesystem()->safe_glob(request->pattern(), &files);
2375
0
        if (st.ok()) {
2376
0
            for (auto& file : files) {
2377
0
                PGlobResponse_PFileInfo* pfile = response->add_files();
2378
0
                pfile->set_file(file.file_name);
2379
0
                pfile->set_size(file.file_size);
2380
0
            }
2381
0
        }
2382
0
        st.to_protobuf(response->mutable_status());
2383
0
    });
2384
0
    if (!ret) {
2385
0
        offer_failed(response, done, _heavy_work_pool);
2386
0
        return;
2387
0
    }
2388
0
}
2389
2390
void PInternalService::group_commit_insert(google::protobuf::RpcController* controller,
2391
                                           const PGroupCommitInsertRequest* request,
2392
                                           PGroupCommitInsertResponse* response,
2393
0
                                           google::protobuf::Closure* done) {
2394
0
    TUniqueId load_id;
2395
0
    load_id.__set_hi(request->load_id().hi());
2396
0
    load_id.__set_lo(request->load_id().lo());
2397
0
    std::shared_ptr<std::mutex> lock = std::make_shared<std::mutex>();
2398
0
    std::shared_ptr<bool> is_done = std::make_shared<bool>(false);
2399
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done, load_id, lock,
2400
0
                                           is_done]() {
2401
0
        brpc::ClosureGuard closure_guard(done);
2402
0
        std::shared_ptr<StreamLoadContext> ctx = std::make_shared<StreamLoadContext>(_exec_env);
2403
0
        auto pipe = std::make_shared<io::StreamLoadPipe>(
2404
0
                io::kMaxPipeBufferedBytes /* max_buffered_bytes */, 64 * 1024 /* min_chunk_size */,
2405
0
                -1 /* total_length */, true /* use_proto */);
2406
0
        ctx->pipe = pipe;
2407
0
        Status st = _exec_env->new_load_stream_mgr()->put(load_id, ctx);
2408
0
        if (st.ok()) {
2409
0
            try {
2410
0
                st = _exec_plan_fragment_impl(
2411
0
                        request->exec_plan_fragment_request().request(),
2412
0
                        request->exec_plan_fragment_request().version(),
2413
0
                        request->exec_plan_fragment_request().compact(),
2414
0
                        [&, response, done, load_id, lock, is_done](RuntimeState* state,
2415
0
                                                                    Status* status) {
2416
0
                            std::lock_guard<std::mutex> lock1(*lock);
2417
0
                            if (*is_done) {
2418
0
                                return;
2419
0
                            }
2420
0
                            *is_done = true;
2421
0
                            brpc::ClosureGuard cb_closure_guard(done);
2422
0
                            response->set_label(state->import_label());
2423
0
                            response->set_txn_id(state->wal_id());
2424
0
                            response->set_loaded_rows(state->num_rows_load_success());
2425
0
                            response->set_filtered_rows(state->num_rows_load_filtered());
2426
0
                            status->to_protobuf(response->mutable_status());
2427
0
                            if (!state->get_error_log_file_path().empty()) {
2428
0
                                response->set_error_url(
2429
0
                                        to_load_error_http_path(state->get_error_log_file_path()));
2430
0
                            }
2431
0
                            if (!state->get_first_error_msg().empty()) {
2432
0
                                response->set_first_error_msg(state->get_first_error_msg());
2433
0
                            }
2434
0
                            _exec_env->new_load_stream_mgr()->remove(load_id);
2435
0
                        });
2436
0
            } catch (const Exception& e) {
2437
0
                st = e.to_status();
2438
0
            } catch (const std::exception& e) {
2439
0
                st = Status::Error(ErrorCode::INTERNAL_ERROR, e.what());
2440
0
            } catch (...) {
2441
0
                st = Status::Error(ErrorCode::INTERNAL_ERROR,
2442
0
                                   "_exec_plan_fragment_impl meet unknown error");
2443
0
            }
2444
0
            if (!st.ok()) {
2445
0
                LOG(WARNING) << "exec plan fragment failed, load_id=" << print_id(load_id)
2446
0
                             << ", errmsg=" << st;
2447
0
                std::lock_guard<std::mutex> lock1(*lock);
2448
0
                if (*is_done) {
2449
0
                    closure_guard.release();
2450
0
                } else {
2451
0
                    *is_done = true;
2452
0
                    st.to_protobuf(response->mutable_status());
2453
0
                    _exec_env->new_load_stream_mgr()->remove(load_id);
2454
0
                }
2455
0
            } else {
2456
0
                closure_guard.release();
2457
0
                for (int i = 0; i < request->data().size(); ++i) {
2458
0
                    std::unique_ptr<PDataRow> row(new PDataRow());
2459
0
                    row->CopyFrom(request->data(i));
2460
0
                    st = pipe->append(std::move(row));
2461
0
                    if (!st.ok()) {
2462
0
                        break;
2463
0
                    }
2464
0
                }
2465
0
                if (st.ok()) {
2466
0
                    static_cast<void>(pipe->finish());
2467
0
                }
2468
0
            }
2469
0
        }
2470
0
    });
2471
0
    if (!ret) {
2472
0
        _exec_env->new_load_stream_mgr()->remove(load_id);
2473
0
        offer_failed(response, done, _heavy_work_pool);
2474
0
        return;
2475
0
    }
2476
0
};
2477
2478
void PInternalService::get_wal_queue_size(google::protobuf::RpcController* controller,
2479
                                          const PGetWalQueueSizeRequest* request,
2480
                                          PGetWalQueueSizeResponse* response,
2481
0
                                          google::protobuf::Closure* done) {
2482
0
    bool ret = _heavy_work_pool.try_offer([this, request, response, done]() {
2483
0
        brpc::ClosureGuard closure_guard(done);
2484
0
        Status st = Status::OK();
2485
0
        auto table_id = request->table_id();
2486
0
        auto count = _exec_env->wal_mgr()->get_wal_queue_size(table_id);
2487
0
        response->set_size(count);
2488
0
        response->mutable_status()->set_status_code(st.code());
2489
0
    });
2490
0
    if (!ret) {
2491
0
        offer_failed(response, done, _heavy_work_pool);
2492
0
    }
2493
0
}
2494
2495
void PInternalService::get_be_resource(google::protobuf::RpcController* controller,
2496
                                       const PGetBeResourceRequest* request,
2497
                                       PGetBeResourceResponse* response,
2498
0
                                       google::protobuf::Closure* done) {
2499
0
    bool ret = _heavy_work_pool.try_offer([response, done]() {
2500
0
        brpc::ClosureGuard closure_guard(done);
2501
0
        int64_t mem_limit = MemInfo::mem_limit();
2502
0
        int64_t mem_usage = PerfCounters::get_vm_rss();
2503
2504
0
        PGlobalResourceUsage* global_resource_usage = response->mutable_global_be_resource_usage();
2505
0
        global_resource_usage->set_mem_limit(mem_limit);
2506
0
        global_resource_usage->set_mem_usage(mem_usage);
2507
2508
0
        Status st = Status::OK();
2509
0
        response->mutable_status()->set_status_code(st.code());
2510
0
    });
2511
0
    if (!ret) {
2512
0
        offer_failed(response, done, _heavy_work_pool);
2513
0
    }
2514
0
}
2515
2516
void PInternalService::delete_dictionary(google::protobuf::RpcController* controller,
2517
                                         const PDeleteDictionaryRequest* request,
2518
                                         PDeleteDictionaryResponse* response,
2519
0
                                         google::protobuf::Closure* done) {
2520
0
    brpc::ClosureGuard closure_guard(done);
2521
0
    Status st = ExecEnv::GetInstance()->dict_factory()->delete_dict(request->dictionary_id());
2522
0
    st.to_protobuf(response->mutable_status());
2523
0
}
2524
2525
void PInternalService::commit_refresh_dictionary(google::protobuf::RpcController* controller,
2526
                                                 const PCommitRefreshDictionaryRequest* request,
2527
                                                 PCommitRefreshDictionaryResponse* response,
2528
0
                                                 google::protobuf::Closure* done) {
2529
0
    brpc::ClosureGuard closure_guard(done);
2530
0
    Status st = ExecEnv::GetInstance()->dict_factory()->commit_refresh_dict(
2531
0
            request->dictionary_id(), request->version_id());
2532
0
    st.to_protobuf(response->mutable_status());
2533
0
}
2534
2535
void PInternalService::abort_refresh_dictionary(google::protobuf::RpcController* controller,
2536
                                                const PAbortRefreshDictionaryRequest* request,
2537
                                                PAbortRefreshDictionaryResponse* response,
2538
0
                                                google::protobuf::Closure* done) {
2539
0
    brpc::ClosureGuard closure_guard(done);
2540
0
    Status st = ExecEnv::GetInstance()->dict_factory()->abort_refresh_dict(request->dictionary_id(),
2541
0
                                                                           request->version_id());
2542
0
    st.to_protobuf(response->mutable_status());
2543
0
}
2544
2545
void PInternalService::get_tablet_rowsets(google::protobuf::RpcController* controller,
2546
                                          const PGetTabletRowsetsRequest* request,
2547
                                          PGetTabletRowsetsResponse* response,
2548
0
                                          google::protobuf::Closure* done) {
2549
0
    DCHECK(config::is_cloud_mode());
2550
0
    auto start_time = GetMonoTimeMicros();
2551
0
    Defer defer {
2552
0
            [&]() { g_process_remote_fetch_rowsets_latency << GetMonoTimeMicros() - start_time; }};
2553
0
    brpc::ClosureGuard closure_guard(done);
2554
0
    LOG(INFO) << "process get tablet rowsets, request=" << request->ShortDebugString();
2555
0
    if (!request->has_tablet_id() || !request->has_version_start() || !request->has_version_end()) {
2556
0
        Status::InvalidArgument("missing params tablet/version_start/version_end")
2557
0
                .to_protobuf(response->mutable_status());
2558
0
        return;
2559
0
    }
2560
0
    CloudStorageEngine& storage = ExecEnv::GetInstance()->storage_engine().to_cloud();
2561
2562
0
    auto maybe_tablet =
2563
0
            storage.tablet_mgr().get_tablet(request->tablet_id(), /*warmup data*/ false,
2564
0
                                            /*syn_delete_bitmap*/ false, /*delete_bitmap*/ nullptr,
2565
0
                                            /*local_only*/ true);
2566
0
    if (!maybe_tablet) {
2567
0
        maybe_tablet.error().to_protobuf(response->mutable_status());
2568
0
        return;
2569
0
    }
2570
0
    auto tablet = maybe_tablet.value();
2571
0
    Result<CaptureRowsetResult> ret;
2572
0
    {
2573
0
        std::shared_lock l(tablet->get_header_lock());
2574
0
        ret = tablet->capture_consistent_rowsets_unlocked(
2575
0
                {request->version_start(), request->version_end()},
2576
0
                CaptureRowsetOps {.enable_fetch_rowsets_from_peers = false});
2577
0
    }
2578
0
    if (!ret) {
2579
0
        ret.error().to_protobuf(response->mutable_status());
2580
0
        return;
2581
0
    }
2582
0
    auto rowsets = std::move(ret.value().rowsets);
2583
0
    for (const auto& rs : rowsets) {
2584
0
        RowsetMetaPB meta;
2585
0
        rs->rowset_meta()->to_rowset_pb(&meta);
2586
0
        response->mutable_rowsets()->Add(std::move(meta));
2587
0
    }
2588
0
    if (request->has_delete_bitmap_keys()) {
2589
0
        DCHECK(tablet->enable_unique_key_merge_on_write());
2590
0
        auto delete_bitmap = std::move(ret.value().delete_bitmap);
2591
0
        auto keys_pb = request->delete_bitmap_keys();
2592
0
        size_t len = keys_pb.rowset_ids().size();
2593
0
        DCHECK_EQ(len, keys_pb.segment_ids().size());
2594
0
        DCHECK_EQ(len, keys_pb.versions().size());
2595
0
        std::set<DeleteBitmap::BitmapKey> keys;
2596
0
        for (size_t i = 0; i < len; ++i) {
2597
0
            RowsetId rs_id;
2598
0
            rs_id.init(keys_pb.rowset_ids(i));
2599
0
            keys.emplace(rs_id, keys_pb.segment_ids(i), keys_pb.versions(i));
2600
0
        }
2601
0
        auto diffset = delete_bitmap->diffset(keys).to_pb();
2602
0
        *response->mutable_delete_bitmap() = std::move(diffset);
2603
0
    }
2604
0
    Status::OK().to_protobuf(response->mutable_status());
2605
0
}
2606
2607
void PInternalService::request_cdc_client(google::protobuf::RpcController* controller,
2608
                                          const PRequestCdcClientRequest* request,
2609
                                          PRequestCdcClientResult* result,
2610
0
                                          google::protobuf::Closure* done) {
2611
0
    bool ret = _heavy_work_pool.try_offer([this, request, result, done]() {
2612
0
        _exec_env->cdc_client_mgr()->request_cdc_client_impl(request, result, done);
2613
0
    });
2614
2615
0
    if (!ret) {
2616
0
        offer_failed(result, done, _heavy_work_pool);
2617
0
        return;
2618
0
    }
2619
0
}
2620
2621
#include "common/compile_check_avoid_end.h"
2622
} // namespace doris