Coverage Report

Created: 2025-03-11 12:30

/root/doris/be/src/runtime/load_channel.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 "runtime/load_channel.h"
19
20
#include <gen_cpp/internal_service.pb.h>
21
#include <glog/logging.h>
22
23
#include "cloud/cloud_tablets_channel.h"
24
#include "cloud/config.h"
25
#include "common/logging.h"
26
#include "olap/storage_engine.h"
27
#include "runtime/exec_env.h"
28
#include "runtime/fragment_mgr.h"
29
#include "runtime/memory/mem_tracker.h"
30
#include "runtime/tablets_channel.h"
31
#include "runtime/thread_context.h"
32
#include "runtime/workload_group/workload_group_manager.h"
33
34
namespace doris {
35
36
bvar::Adder<int64_t> g_loadchannel_cnt("loadchannel_cnt");
37
38
LoadChannel::LoadChannel(const UniqueId& load_id, int64_t timeout_s, bool is_high_priority,
39
                         std::string sender_ip, int64_t backend_id, bool enable_profile,
40
                         int64_t wg_id)
41
        : _load_id(load_id),
42
          _timeout_s(timeout_s),
43
          _is_high_priority(is_high_priority),
44
          _sender_ip(std::move(sender_ip)),
45
          _backend_id(backend_id),
46
0
          _enable_profile(enable_profile) {
47
0
    std::shared_ptr<QueryContext> query_context =
48
0
            ExecEnv::GetInstance()->fragment_mgr()->get_query_ctx(_load_id.to_thrift());
49
50
0
    if (query_context != nullptr) {
51
0
        _resource_ctx = query_context->resource_ctx();
52
0
    } else {
53
0
        _resource_ctx = ResourceContext::create_shared();
54
0
        _resource_ctx->task_controller()->set_task_id(_load_id.to_thrift());
55
        // when memtable on sink is not enabled, load can not find queryctx
56
0
        std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
57
0
                MemTrackerLimiter::Type::LOAD,
58
0
                fmt::format("(FromLoadChannel)Load#Id={}", _load_id.to_string()));
59
0
        _resource_ctx->memory_context()->set_mem_tracker(mem_tracker);
60
0
        WorkloadGroupPtr wg_ptr = nullptr;
61
0
        if (wg_id > 0) {
62
0
            wg_ptr = ExecEnv::GetInstance()->workload_group_mgr()->get_group(wg_id);
63
0
            if (wg_ptr != nullptr) {
64
0
                wg_ptr->add_mem_tracker_limiter(mem_tracker);
65
0
                _resource_ctx->set_workload_group(wg_ptr);
66
0
            }
67
0
        }
68
0
    }
69
70
0
    g_loadchannel_cnt << 1;
71
    // _last_updated_time should be set before being inserted to
72
    // _load_channels in load_channel_mgr, or it may be erased
73
    // immediately by gc thread.
74
0
    _last_updated_time.store(time(nullptr));
75
0
    _init_profile();
76
0
}
77
78
0
LoadChannel::~LoadChannel() {
79
0
    g_loadchannel_cnt << -1;
80
0
    std::stringstream rows_str;
81
0
    for (const auto& entry : _tablets_channels_rows) {
82
0
        rows_str << ", index id: " << entry.first << ", total_received_rows: " << entry.second.first
83
0
                 << ", num_rows_filtered: " << entry.second.second;
84
0
    }
85
0
    LOG(INFO) << "load channel removed"
86
0
              << " load_id=" << _load_id << ", is high priority=" << _is_high_priority
87
0
              << ", sender_ip=" << _sender_ip << rows_str.str();
88
0
}
89
90
0
void LoadChannel::_init_profile() {
91
0
    _profile = std::make_unique<RuntimeProfile>("LoadChannels");
92
0
    _mgr_add_batch_timer = ADD_TIMER(_profile, "LoadChannelMgrAddBatchTime");
93
0
    _handle_mem_limit_timer = ADD_TIMER(_profile, "HandleMemLimitTime");
94
0
    _self_profile =
95
0
            _profile->create_child(fmt::format("LoadChannel load_id={} (host={}, backend_id={})",
96
0
                                               _load_id.to_string(), _sender_ip, _backend_id),
97
0
                                   true, true);
98
0
    _add_batch_number_counter = ADD_COUNTER(_self_profile, "NumberBatchAdded", TUnit::UNIT);
99
0
    _add_batch_timer = ADD_TIMER(_self_profile, "AddBatchTime");
100
0
    _handle_eos_timer = ADD_CHILD_TIMER(_self_profile, "HandleEosTime", "AddBatchTime");
101
0
    _add_batch_times = ADD_COUNTER(_self_profile, "AddBatchTimes", TUnit::UNIT);
102
0
}
103
104
0
Status LoadChannel::open(const PTabletWriterOpenRequest& params) {
105
0
    if (config::is_cloud_mode() && params.txn_expiration() <= 0) {
106
0
        return Status::InternalError(
107
0
                "The txn expiration of PTabletWriterOpenRequest is invalid, value={}",
108
0
                params.txn_expiration());
109
0
    }
110
0
    SCOPED_ATTACH_TASK(_resource_ctx);
111
112
0
    int64_t index_id = params.index_id();
113
0
    std::shared_ptr<BaseTabletsChannel> channel;
114
0
    {
115
0
        std::lock_guard<std::mutex> l(_lock);
116
0
        auto it = _tablets_channels.find(index_id);
117
0
        if (it != _tablets_channels.end()) {
118
0
            channel = it->second;
119
0
        } else {
120
            // just for VLOG
121
0
            if (_txn_id == 0) [[unlikely]] {
122
0
                _txn_id = params.txn_id();
123
0
            }
124
            // create a new tablets channel
125
0
            TabletsChannelKey key(params.id(), index_id);
126
0
            BaseStorageEngine& engine = ExecEnv::GetInstance()->storage_engine();
127
0
            if (config::is_cloud_mode()) {
128
0
                channel = std::make_shared<CloudTabletsChannel>(engine.to_cloud(), key, _load_id,
129
0
                                                                _is_high_priority, _self_profile);
130
0
            } else {
131
0
                channel = std::make_shared<TabletsChannel>(engine.to_local(), key, _load_id,
132
0
                                                           _is_high_priority, _self_profile);
133
0
            }
134
0
            {
135
0
                std::lock_guard<std::mutex> l(_tablets_channels_lock);
136
0
                _tablets_channels.insert({index_id, channel});
137
0
            }
138
0
        }
139
0
    }
140
141
0
    if (params.is_incremental()) {
142
        // incremental open would ensure not to open tablet repeatedly
143
0
        RETURN_IF_ERROR(channel->incremental_open(params));
144
0
    } else {
145
0
        RETURN_IF_ERROR(channel->open(params));
146
0
    }
147
148
0
    _opened = true;
149
0
    _last_updated_time.store(time(nullptr));
150
0
    return Status::OK();
151
0
}
152
153
Status LoadChannel::_get_tablets_channel(std::shared_ptr<BaseTabletsChannel>& channel,
154
0
                                         bool& is_finished, const int64_t index_id) {
155
0
    std::lock_guard<std::mutex> l(_lock);
156
0
    auto it = _tablets_channels.find(index_id);
157
0
    if (it == _tablets_channels.end()) {
158
0
        if (_finished_channel_ids.find(index_id) != _finished_channel_ids.end()) {
159
            // this channel is already finished, just return OK
160
0
            is_finished = true;
161
0
            return Status::OK();
162
0
        }
163
0
        std::stringstream ss;
164
0
        ss << "load channel " << _load_id << " add batch with unknown index id: " << index_id;
165
0
        return Status::InternalError(ss.str());
166
0
    }
167
168
0
    is_finished = false;
169
0
    channel = it->second;
170
0
    return Status::OK();
171
0
}
172
173
Status LoadChannel::add_batch(const PTabletWriterAddBlockRequest& request,
174
0
                              PTabletWriterAddBlockResult* response) {
175
0
    SCOPED_TIMER(_add_batch_timer);
176
0
    COUNTER_UPDATE(_add_batch_times, 1);
177
0
    SCOPED_ATTACH_TASK(_resource_ctx);
178
0
    int64_t index_id = request.index_id();
179
    // 1. get tablets channel
180
0
    std::shared_ptr<BaseTabletsChannel> channel;
181
0
    bool is_finished = false;
182
0
    Status st = _get_tablets_channel(channel, is_finished, index_id);
183
0
    if (!st.ok() || is_finished) {
184
0
        return st;
185
0
    }
186
187
    // 2. add block to tablets channel
188
0
    if (request.has_block()) {
189
0
        RETURN_IF_ERROR(channel->add_batch(request, response));
190
0
        _add_batch_number_counter->update(1);
191
0
    }
192
193
    // 3. handle eos
194
    // if channel is incremental, maybe hang on close until all close request arrived.
195
0
    if (request.has_eos() && request.eos()) {
196
0
        st = _handle_eos(channel.get(), request, response);
197
0
        _report_profile(response);
198
0
        if (!st.ok()) {
199
0
            return st;
200
0
        }
201
0
    } else if (_add_batch_number_counter->value() % 100 == 1) {
202
0
        _report_profile(response);
203
0
    }
204
0
    _last_updated_time.store(time(nullptr));
205
0
    return st;
206
0
}
207
208
Status LoadChannel::_handle_eos(BaseTabletsChannel* channel,
209
                                const PTabletWriterAddBlockRequest& request,
210
0
                                PTabletWriterAddBlockResult* response) {
211
0
    _self_profile->add_info_string("EosHost", fmt::format("{}", request.backend_id()));
212
0
    bool finished = false;
213
0
    auto index_id = request.index_id();
214
215
0
    RETURN_IF_ERROR(channel->close(this, request, response, &finished));
216
217
    // for init node, we close waiting(hang on) all close request and let them return together.
218
0
    if (request.has_hang_wait() && request.hang_wait()) {
219
0
        DCHECK(!channel->is_incremental_channel());
220
0
        VLOG_DEBUG << fmt::format("txn {}: reciever index {} close waiting by sender {}", _txn_id,
221
0
                                  request.index_id(), request.sender_id());
222
0
        int count = 0;
223
0
        while (!channel->is_finished()) {
224
0
            bthread_usleep(1000);
225
0
            count++;
226
0
        }
227
        // now maybe finished or cancelled.
228
0
        VLOG_TRACE << "reciever close wait finished!" << request.sender_id();
229
0
        if (count >= 1000 * _timeout_s) { // maybe config::streaming_load_rpc_max_alive_time_sec
230
0
            return Status::InternalError("Tablets channel didn't wait all close");
231
0
        }
232
0
    }
233
234
0
    if (finished) {
235
0
        std::lock_guard<std::mutex> l(_lock);
236
0
        {
237
0
            std::lock_guard<std::mutex> l(_tablets_channels_lock);
238
0
            _tablets_channels_rows.insert(std::make_pair(
239
0
                    index_id,
240
0
                    std::make_pair(channel->total_received_rows(), channel->num_rows_filtered())));
241
0
            _tablets_channels.erase(index_id);
242
0
        }
243
0
        LOG(INFO) << "txn " << _txn_id << " closed tablets_channel " << index_id;
244
0
        _finished_channel_ids.emplace(index_id);
245
0
    }
246
0
    return Status::OK();
247
0
}
248
249
0
void LoadChannel::_report_profile(PTabletWriterAddBlockResult* response) {
250
0
    if (!_enable_profile) {
251
0
        return;
252
0
    }
253
254
    // TabletSink and LoadChannel in BE are M: N relationship,
255
    // Every once in a while LoadChannel will randomly return its own runtime profile to a TabletSink,
256
    // so usually all LoadChannel runtime profiles are saved on each TabletSink,
257
    // and the timeliness of the same LoadChannel profile saved on different TabletSinks is different,
258
    // and each TabletSink will periodically send fe reports all the LoadChannel profiles saved by itself,
259
    // and ensures to update the latest LoadChannel profile according to the timestamp.
260
0
    _self_profile->set_timestamp(_last_updated_time);
261
262
0
    {
263
0
        std::lock_guard<std::mutex> l(_tablets_channels_lock);
264
0
        for (auto& it : _tablets_channels) {
265
0
            it.second->refresh_profile();
266
0
        }
267
0
    }
268
269
0
    TRuntimeProfileTree tprofile;
270
0
    ThriftSerializer ser(false, 4096);
271
0
    uint8_t* buf = nullptr;
272
0
    uint32_t len = 0;
273
0
    std::lock_guard<SpinLock> l(_profile_serialize_lock);
274
0
    _profile->to_thrift(&tprofile);
275
0
    auto st = ser.serialize(&tprofile, &len, &buf);
276
0
    if (st.ok()) {
277
0
        response->set_load_channel_profile(std::string((const char*)buf, len));
278
0
    } else {
279
0
        LOG(WARNING) << "load channel TRuntimeProfileTree serialize failed, errmsg=" << st;
280
0
    }
281
0
}
282
283
0
bool LoadChannel::is_finished() {
284
0
    if (!_opened) {
285
0
        return false;
286
0
    }
287
0
    std::lock_guard<std::mutex> l(_lock);
288
0
    return _tablets_channels.empty();
289
0
}
290
291
0
Status LoadChannel::cancel() {
292
0
    std::lock_guard<std::mutex> l(_lock);
293
0
    for (auto& it : _tablets_channels) {
294
0
        static_cast<void>(it.second->cancel());
295
0
    }
296
0
    return Status::OK();
297
0
}
298
299
} // namespace doris