Coverage Report

Created: 2026-09-18 19:52

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