Coverage Report

Created: 2026-10-12 17:28

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