Coverage Report

Created: 2026-08-31 16:25

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