Coverage Report

Created: 2026-07-12 08:23

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