Coverage Report

Created: 2026-11-06 13:21

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