Coverage Report

Created: 2026-09-20 22:42

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