Coverage Report

Created: 2026-10-15 15:03

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