Coverage Report

Created: 2026-10-27 18:17

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