Coverage Report

Created: 2026-10-23 15:33

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