Coverage Report

Created: 2026-09-10 07:21

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