Coverage Report

Created: 2025-07-23 20:08

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