Coverage Report

Created: 2026-09-15 13:26

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