Coverage Report

Created: 2024-11-20 21:21

/root/doris/be/src/olap/memtable_writer.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 "olap/memtable_writer.h"
19
20
#include <fmt/format.h>
21
22
#include <filesystem>
23
#include <ostream>
24
#include <string>
25
#include <utility>
26
27
#include "common/compiler_util.h" // IWYU pragma: keep
28
#include "common/config.h"
29
#include "common/logging.h"
30
#include "common/status.h"
31
#include "exec/tablet_info.h"
32
#include "gutil/strings/numbers.h"
33
#include "io/fs/file_writer.h" // IWYU pragma: keep
34
#include "olap/memtable.h"
35
#include "olap/memtable_flush_executor.h"
36
#include "olap/memtable_memory_limiter.h"
37
#include "olap/rowset/beta_rowset_writer.h"
38
#include "olap/rowset/rowset_writer.h"
39
#include "olap/schema_change.h"
40
#include "olap/storage_engine.h"
41
#include "olap/tablet_schema.h"
42
#include "runtime/exec_env.h"
43
#include "runtime/memory/mem_tracker.h"
44
#include "service/backend_options.h"
45
#include "util/mem_info.h"
46
#include "util/stopwatch.hpp"
47
#include "vec/core/block.h"
48
49
namespace doris {
50
using namespace ErrorCode;
51
52
14
MemTableWriter::MemTableWriter(const WriteRequest& req) : _req(req) {}
53
54
14
MemTableWriter::~MemTableWriter() {
55
14
    if (!_is_init) {
56
2
        return;
57
2
    }
58
12
    if (_flush_token != nullptr) {
59
        // cancel and wait all memtables in flush queue to be finished
60
12
        _flush_token->cancel();
61
12
    }
62
12
    _mem_table.reset();
63
12
}
64
65
Status MemTableWriter::init(std::shared_ptr<RowsetWriter> rowset_writer,
66
                            TabletSchemaSPtr tablet_schema,
67
                            std::shared_ptr<PartialUpdateInfo> partial_update_info,
68
12
                            std::shared_ptr<WorkloadGroup> wg_sptr, bool unique_key_mow) {
69
12
    _rowset_writer = rowset_writer;
70
12
    _tablet_schema = tablet_schema;
71
12
    _unique_key_mow = unique_key_mow;
72
12
    _partial_update_info = partial_update_info;
73
12
    _query_thread_context.init_unlocked();
74
75
12
    _reset_mem_table();
76
77
    // create flush handler
78
    // by assigning segment_id to memtable before submiting to flush executor,
79
    // we can make sure same keys sort in the same order in all replicas.
80
12
    RETURN_IF_ERROR(
81
12
            ExecEnv::GetInstance()->storage_engine().memtable_flush_executor()->create_flush_token(
82
12
                    _flush_token, _rowset_writer, _req.is_high_priority, wg_sptr));
83
84
12
    _is_init = true;
85
12
    return Status::OK();
86
12
}
87
88
Status MemTableWriter::write(const vectorized::Block* block,
89
17
                             const std::vector<uint32_t>& row_idxs) {
90
17
    if (UNLIKELY(row_idxs.empty())) {
91
0
        return Status::OK();
92
0
    }
93
17
    _lock_watch.start();
94
17
    std::lock_guard<std::mutex> l(_lock);
95
17
    _lock_watch.stop();
96
17
    if (_is_cancelled) {
97
0
        return _cancel_status;
98
0
    }
99
17
    if (!_is_init) {
100
0
        return Status::Error<NOT_INITIALIZED>("delta segment writer has not been initialized");
101
0
    }
102
17
    if (_is_closed) {
103
0
        return Status::Error<ALREADY_CLOSED>("write block after closed tablet_id={}, load_id={}-{}",
104
0
                                             _req.tablet_id, _req.load_id.hi(), _req.load_id.lo());
105
0
    }
106
107
17
    _total_received_rows += row_idxs.size();
108
17
    RETURN_IF_ERROR(_mem_table->insert(block, row_idxs));
109
110
17
    if (UNLIKELY(_mem_table->need_agg() && config::enable_shrink_memory)) {
111
0
        _mem_table->shrink_memtable_by_agg();
112
0
    }
113
17
    if (UNLIKELY(_mem_table->need_flush())) {
114
0
        auto s = _flush_memtable_async();
115
0
        _reset_mem_table();
116
0
        if (UNLIKELY(!s.ok())) {
117
0
            return s;
118
0
        }
119
0
    }
120
121
17
    return Status::OK();
122
17
}
123
124
12
Status MemTableWriter::_flush_memtable_async() {
125
12
    DCHECK(_flush_token != nullptr);
126
12
    std::shared_ptr<MemTable> memtable;
127
12
    {
128
12
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
129
12
        memtable = _mem_table;
130
12
        _mem_table = nullptr;
131
12
    }
132
12
    {
133
12
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
134
12
        memtable->update_mem_type(MemType::WRITE_FINISHED);
135
12
        _freezed_mem_tables.push_back(memtable);
136
12
    }
137
12
    return _flush_token->submit(memtable);
138
12
}
139
140
0
Status MemTableWriter::flush_async() {
141
0
    std::lock_guard<std::mutex> l(_lock);
142
    // In order to avoid repeated ATTACH, use SWITCH here. have two calling paths:
143
    // 1. call by local, from `VTabletWriterV2::_write_memtable`, has been ATTACH Load memory tracker
144
    // into thread context, ATTACH cannot be repeated here.
145
    // 2. call by remote, from `LoadChannelMgr::_get_load_channel`, no ATTACH because LoadChannelMgr
146
    // not know Load context.
147
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_query_thread_context.query_mem_tracker);
148
0
    if (!_is_init || _is_closed) {
149
        // This writer is uninitialized or closed before flushing, do nothing.
150
        // We return OK instead of NOT_INITIALIZED or ALREADY_CLOSED.
151
        // Because this method maybe called when trying to reduce mem consumption,
152
        // and at that time, the writer may not be initialized yet and that is a normal case.
153
0
        return Status::OK();
154
0
    }
155
156
0
    if (_is_cancelled) {
157
0
        return _cancel_status;
158
0
    }
159
160
0
    VLOG_NOTICE << "flush memtable to reduce mem consumption. memtable size: "
161
0
                << _mem_table->memory_usage() << ", tablet: " << _req.tablet_id
162
0
                << ", load id: " << print_id(_req.load_id);
163
0
    auto s = _flush_memtable_async();
164
0
    _reset_mem_table();
165
0
    return s;
166
0
}
167
168
6
Status MemTableWriter::wait_flush() {
169
6
    {
170
6
        std::lock_guard<std::mutex> l(_lock);
171
6
        if (!_is_init || _is_closed) {
172
            // return OK instead of NOT_INITIALIZED or ALREADY_CLOSED for same reason
173
            // as described in flush_async()
174
6
            return Status::OK();
175
6
        }
176
0
        if (_is_cancelled) {
177
0
            return _cancel_status;
178
0
        }
179
0
    }
180
0
    SCOPED_RAW_TIMER(&_wait_flush_time_ns);
181
0
    RETURN_IF_ERROR(_flush_token->wait());
182
0
    return Status::OK();
183
0
}
184
185
12
void MemTableWriter::_reset_mem_table() {
186
12
    {
187
12
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
188
12
        _mem_table.reset(new MemTable(_req.tablet_id, _tablet_schema, _req.slots, _req.tuple_desc,
189
12
                                      _unique_key_mow, _partial_update_info.get()));
190
12
    }
191
192
12
    _segment_num++;
193
12
}
194
195
12
Status MemTableWriter::close() {
196
12
    _lock_watch.start();
197
12
    std::lock_guard<std::mutex> l(_lock);
198
12
    _lock_watch.stop();
199
12
    if (_is_cancelled) {
200
0
        return _cancel_status;
201
0
    }
202
12
    if (!_is_init) {
203
0
        return Status::Error<NOT_INITIALIZED>("delta segment writer has not been initialized");
204
0
    }
205
12
    if (_is_closed) {
206
0
        LOG(WARNING) << "close after closed tablet_id=" << _req.tablet_id
207
0
                     << " load_id=" << _req.load_id;
208
0
        return Status::OK();
209
0
    }
210
211
12
    auto s = _flush_memtable_async();
212
12
    {
213
12
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
214
12
        _mem_table.reset();
215
12
    }
216
12
    _is_closed = true;
217
12
    if (UNLIKELY(!s.ok())) {
218
0
        return s;
219
12
    } else {
220
12
        return Status::OK();
221
12
    }
222
12
}
223
224
12
Status MemTableWriter::_do_close_wait() {
225
12
    SCOPED_RAW_TIMER(&_close_wait_time_ns);
226
12
    std::lock_guard<std::mutex> l(_lock);
227
12
    DCHECK(_is_init)
228
0
            << "delta writer is supposed be to initialized before close_wait() being called";
229
230
12
    if (_is_cancelled) {
231
0
        return _cancel_status;
232
0
    }
233
234
12
    Status st;
235
    // return error if previous flush failed
236
12
    {
237
12
        SCOPED_RAW_TIMER(&_wait_flush_time_ns);
238
12
        st = _flush_token->wait();
239
12
    }
240
12
    if (UNLIKELY(!st.ok())) {
241
0
        LOG(WARNING) << "previous flush failed tablet " << _req.tablet_id;
242
0
        return st;
243
0
    }
244
245
12
    if (_rowset_writer->num_rows() + _flush_token->memtable_stat().merged_rows !=
246
12
        _total_received_rows) {
247
0
        LOG(WARNING) << "the rows number written doesn't match, rowset num rows written to file: "
248
0
                     << _rowset_writer->num_rows()
249
0
                     << ", merged_rows: " << _flush_token->memtable_stat().merged_rows
250
0
                     << ", total received rows: " << _total_received_rows;
251
0
        return Status::InternalError("rows number written by delta writer dosen't match");
252
0
    }
253
254
    // const FlushStatistic& stat = _flush_token->get_stats();
255
    // print slow log if wait more than 1s
256
    /*if (_wait_flush_timer->elapsed_time() > 1000UL * 1000 * 1000) {
257
        LOG(INFO) << "close delta writer for tablet: " << req.tablet_id
258
                  << ", load id: " << print_id(_req.load_id) << ", wait close for "
259
                  << _wait_flush_timer->elapsed_time() << "(ns), stats: " << stat;
260
    }*/
261
262
12
    return Status::OK();
263
12
}
264
265
12
void MemTableWriter::_update_profile(RuntimeProfile* profile) {
266
    // NOTE: MemTableWriter may be accessed when profile is out of scope, in MemTableMemoryLimiter.
267
    // To avoid accessing dangling pointers, we cannot make profile as a member of MemTableWriter.
268
12
    auto child =
269
12
            profile->create_child(fmt::format("MemTableWriter {}", _req.tablet_id), true, true);
270
12
    auto lock_timer = ADD_TIMER(child, "LockTime");
271
12
    auto sort_timer = ADD_TIMER(child, "MemTableSortTime");
272
12
    auto agg_timer = ADD_TIMER(child, "MemTableAggTime");
273
12
    auto memtable_duration_timer = ADD_TIMER(child, "MemTableDurationTime");
274
12
    auto segment_writer_timer = ADD_TIMER(child, "SegmentWriterTime");
275
12
    auto wait_flush_timer = ADD_TIMER(child, "MemTableWaitFlushTime");
276
12
    auto put_into_output_timer = ADD_TIMER(child, "MemTablePutIntoOutputTime");
277
12
    auto delete_bitmap_timer = ADD_TIMER(child, "DeleteBitmapTime");
278
12
    auto close_wait_timer = ADD_TIMER(child, "CloseWaitTime");
279
12
    auto sort_times = ADD_COUNTER(child, "MemTableSortTimes", TUnit::UNIT);
280
12
    auto agg_times = ADD_COUNTER(child, "MemTableAggTimes", TUnit::UNIT);
281
12
    auto segment_num = ADD_COUNTER(child, "SegmentNum", TUnit::UNIT);
282
12
    auto raw_rows_num = ADD_COUNTER(child, "RawRowNum", TUnit::UNIT);
283
12
    auto merged_rows_num = ADD_COUNTER(child, "MergedRowNum", TUnit::UNIT);
284
285
12
    COUNTER_UPDATE(lock_timer, _lock_watch.elapsed_time());
286
12
    COUNTER_SET(delete_bitmap_timer, _rowset_writer->delete_bitmap_ns());
287
12
    COUNTER_SET(segment_writer_timer, _rowset_writer->segment_writer_ns());
288
12
    COUNTER_SET(wait_flush_timer, _wait_flush_time_ns);
289
12
    COUNTER_SET(close_wait_timer, _close_wait_time_ns);
290
12
    COUNTER_SET(segment_num, _segment_num);
291
12
    const auto& memtable_stat = _flush_token->memtable_stat();
292
12
    COUNTER_SET(sort_timer, memtable_stat.sort_ns);
293
12
    COUNTER_SET(agg_timer, memtable_stat.agg_ns);
294
12
    COUNTER_SET(memtable_duration_timer, memtable_stat.duration_ns);
295
12
    COUNTER_SET(put_into_output_timer, memtable_stat.put_into_output_ns);
296
12
    COUNTER_SET(sort_times, memtable_stat.sort_times);
297
12
    COUNTER_SET(agg_times, memtable_stat.agg_times);
298
12
    COUNTER_SET(raw_rows_num, memtable_stat.raw_rows);
299
12
    COUNTER_SET(merged_rows_num, memtable_stat.merged_rows);
300
12
}
301
302
12
Status MemTableWriter::cancel() {
303
12
    return cancel_with_status(Status::Cancelled("already cancelled"));
304
12
}
305
306
12
Status MemTableWriter::cancel_with_status(const Status& st) {
307
12
    std::lock_guard<std::mutex> l(_lock);
308
12
    if (_is_cancelled) {
309
0
        return Status::OK();
310
0
    }
311
12
    {
312
12
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
313
12
        _mem_table.reset();
314
12
    }
315
12
    if (_flush_token != nullptr) {
316
        // cancel and wait all memtables in flush queue to be finished
317
12
        _flush_token->cancel();
318
12
    }
319
12
    _is_cancelled = true;
320
12
    _cancel_status = st;
321
12
    return Status::OK();
322
12
}
323
324
12
const FlushStatistic& MemTableWriter::get_flush_token_stats() {
325
12
    return _flush_token->get_stats();
326
12
}
327
328
17
uint64_t MemTableWriter::flush_running_count() const {
329
17
    return _flush_token == nullptr ? 0 : _flush_token->get_stats().flush_running_count.load();
330
17
}
331
332
0
int64_t MemTableWriter::mem_consumption(MemType mem) {
333
0
    if (!_is_init) {
334
        // This method may be called before this writer is initialized.
335
        // So _flush_token may be null.
336
0
        return 0;
337
0
    }
338
0
    int64_t mem_usage = 0;
339
0
    {
340
0
        std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
341
0
        for (const auto& mem_table : _freezed_mem_tables) {
342
0
            auto mem_table_sptr = mem_table.lock();
343
0
            if (mem_table_sptr != nullptr && mem_table_sptr->get_mem_type() == mem) {
344
0
                mem_usage += mem_table_sptr->memory_usage();
345
0
            }
346
0
        }
347
0
    }
348
0
    return mem_usage;
349
0
}
350
351
0
int64_t MemTableWriter::active_memtable_mem_consumption() {
352
0
    std::lock_guard<SpinLock> l(_mem_table_ptr_lock);
353
0
    return _mem_table != nullptr ? _mem_table->memory_usage() : 0;
354
0
}
355
356
} // namespace doris