Coverage Report

Created: 2026-10-08 09:40

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