Coverage Report

Created: 2026-10-04 12:22

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