Coverage Report

Created: 2025-07-27 01:13

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