Coverage Report

Created: 2026-10-13 04:32

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