Coverage Report

Created: 2026-09-09 07:07

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