Coverage Report

Created: 2025-07-28 22:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/olap/txn_manager.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "txn_manager.h"
19
20
#include <bvar/bvar.h>
21
#include <fmt/format.h>
22
#include <fmt/ranges.h>
23
#include <thrift/protocol/TDebugProtocol.h>
24
#include <time.h>
25
26
#include <filesystem>
27
#include <iterator>
28
#include <list>
29
#include <new>
30
#include <ostream>
31
#include <queue>
32
#include <set>
33
#include <string>
34
35
#include "common/config.h"
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "olap/data_dir.h"
39
#include "olap/delta_writer.h"
40
#include "olap/olap_common.h"
41
#include "olap/partial_update_info.h"
42
#include "olap/rowset/beta_rowset.h"
43
#include "olap/rowset/pending_rowset_helper.h"
44
#include "olap/rowset/rowset_meta.h"
45
#include "olap/rowset/rowset_meta_manager.h"
46
#include "olap/schema_change.h"
47
#include "olap/segment_loader.h"
48
#include "olap/storage_engine.h"
49
#include "olap/tablet_manager.h"
50
#include "olap/tablet_meta.h"
51
#include "olap/tablet_meta_manager.h"
52
#include "olap/task/engine_publish_version_task.h"
53
#include "util/debug_points.h"
54
#include "util/time.h"
55
56
namespace doris {
57
class OlapMeta;
58
} // namespace doris
59
60
using std::map;
61
using std::pair;
62
using std::set;
63
using std::string;
64
using std::stringstream;
65
using std::vector;
66
67
namespace doris {
68
using namespace ErrorCode;
69
70
bvar::Adder<int64_t> g_tablet_txn_info_txn_partitions_count("tablet_txn_info_txn_partitions_count");
71
72
TxnManager::TxnManager(StorageEngine& engine, int32_t txn_map_shard_size, int32_t txn_shard_size)
73
756
        : _engine(engine),
74
756
          _txn_map_shard_size(txn_map_shard_size),
75
756
          _txn_shard_size(txn_shard_size) {
76
756
    DCHECK_GT(_txn_map_shard_size, 0);
77
756
    DCHECK_GT(_txn_shard_size, 0);
78
756
    DCHECK_EQ(_txn_map_shard_size & (_txn_map_shard_size - 1), 0);
79
756
    DCHECK_EQ(_txn_shard_size & (_txn_shard_size - 1), 0);
80
756
    _txn_map_locks = new std::shared_mutex[_txn_map_shard_size];
81
756
    _txn_tablet_maps = new txn_tablet_map_t[_txn_map_shard_size];
82
756
    _txn_partition_maps = new txn_partition_map_t[_txn_map_shard_size];
83
756
    _txn_mutex = new std::shared_mutex[_txn_shard_size];
84
756
    _txn_tablet_delta_writer_map = new txn_tablet_delta_writer_map_t[_txn_map_shard_size];
85
756
    _txn_tablet_delta_writer_map_locks = new std::shared_mutex[_txn_map_shard_size];
86
    // For debugging
87
756
    _tablet_version_cache = std::make_unique<TabletVersionCache>(100000);
88
756
}
89
90
// prepare txn should always be allowed because ingest task will be retried
91
// could not distinguish rollup, schema change or base table, prepare txn successfully will allow
92
// ingest retried
93
Status TxnManager::prepare_txn(TPartitionId partition_id, const Tablet& tablet,
94
                               TTransactionId transaction_id, const PUniqueId& load_id,
95
84
                               bool ingest) {
96
    // check if the tablet has already been shutdown. If it has, it indicates that
97
    // it is an old tablet, and data should not be imported into the old tablet.
98
    // Otherwise, it may lead to data loss during migration.
99
84
    if (tablet.tablet_state() == TABLET_SHUTDOWN) {
100
0
        return Status::InternalError<false>(
101
0
                "The tablet's state is shutdown, tablet_id: {}. The tablet may have been dropped "
102
0
                "or migrationed. Please check if the table has been dropped or try again.",
103
0
                tablet.tablet_id());
104
0
    }
105
84
    return prepare_txn(partition_id, transaction_id, tablet.tablet_id(), tablet.tablet_uid(),
106
84
                       load_id, ingest);
107
84
}
108
109
// most used for ut
110
Status TxnManager::prepare_txn(TPartitionId partition_id, TTransactionId transaction_id,
111
                               TTabletId tablet_id, TabletUid tablet_uid, const PUniqueId& load_id,
112
108
                               bool ingest) {
113
108
    TxnKey key(partition_id, transaction_id);
114
108
    TabletInfo tablet_info(tablet_id, tablet_uid);
115
108
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
116
108
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
117
118
108
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.random_failed", {
119
108
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
120
108
            LOG_WARNING("TxnManager.prepare_txn.random_failed random failed")
121
108
                    .tag("txn_id", transaction_id)
122
108
                    .tag("tablet_id", tablet_id);
123
108
            return Status::InternalError("debug prepare txn random failed");
124
108
        }
125
108
    });
126
108
    DBUG_EXECUTE_IF("TxnManager.prepare_txn.wait", {
127
108
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
128
108
            LOG_WARNING("TxnManager.prepare_txn.wait")
129
108
                    .tag("txn_id", transaction_id)
130
108
                    .tag("tablet_id", tablet_id)
131
108
                    .tag("wait ms", wait);
132
108
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
133
108
        }
134
108
    });
135
136
    /// Step 1: check if the transaction is already exist
137
108
    do {
138
108
        auto iter = txn_tablet_map.find(key);
139
108
        if (iter == txn_tablet_map.end()) {
140
96
            break;
141
96
        }
142
143
        // exist TxnKey
144
12
        auto& txn_tablet_info_map = iter->second;
145
12
        auto load_itr = txn_tablet_info_map.find(tablet_info);
146
12
        if (load_itr == txn_tablet_info_map.end()) {
147
6
            break;
148
6
        }
149
150
        // found load for txn,tablet
151
6
        auto& load_info = load_itr->second;
152
        // case 1: user commit rowset, then the load id must be equal
153
        // check if load id is equal
154
6
        auto& load_id = load_info->load_id;
155
6
        if (load_info->load_id.hi() == load_id.hi() && load_info->load_id.lo() == load_id.lo() &&
156
6
            load_info->rowset != nullptr) {
157
3
            LOG(WARNING) << "find transaction exists when add to engine."
158
3
                         << "partition_id: " << key.first << ", transaction_id: " << key.second
159
3
                         << ", tablet: " << tablet_info.to_string();
160
3
            return Status::OK();
161
3
        }
162
6
    } while (false);
163
164
    /// Step 2: check if there are too many transactions on running.
165
    // check if there are too many transactions on running.
166
    // if yes, reject the request.
167
105
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
168
105
    if (txn_partition_map.size() > config::max_runnings_transactions_per_txn_map) {
169
0
        return Status::Error<TOO_MANY_TRANSACTIONS>("too many transactions: {}, limit: {}",
170
0
                                                    txn_tablet_map.size(),
171
0
                                                    config::max_runnings_transactions_per_txn_map);
172
0
    }
173
174
    /// Step 3: Add transaction to engine
175
    // not found load id
176
    // case 1: user start a new txn, rowset = null
177
    // case 2: loading txn from meta env
178
105
    auto load_info = std::make_shared<TabletTxnInfo>(load_id, nullptr, ingest);
179
105
    load_info->prepare();
180
105
    if (!txn_tablet_map.contains(key)) {
181
96
        g_tablet_txn_info_txn_partitions_count << 1;
182
96
    }
183
105
    txn_tablet_map[key][tablet_info] = std::move(load_info);
184
105
    _insert_txn_partition_map_unlocked(transaction_id, partition_id);
185
105
    VLOG_NOTICE << "add transaction to engine successfully."
186
0
                << "partition_id: " << key.first << ", transaction_id: " << key.second
187
0
                << ", tablet: " << tablet_info.to_string();
188
105
    return Status::OK();
189
105
}
190
191
Status TxnManager::commit_txn(TPartitionId partition_id, const Tablet& tablet,
192
                              TTransactionId transaction_id, const PUniqueId& load_id,
193
                              const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard,
194
                              bool is_recovery,
195
69
                              std::shared_ptr<PartialUpdateInfo> partial_update_info) {
196
69
    return commit_txn(tablet.data_dir()->get_meta(), partition_id, transaction_id,
197
69
                      tablet.tablet_id(), tablet.tablet_uid(), load_id, rowset_ptr,
198
69
                      std::move(guard), is_recovery, partial_update_info);
199
69
}
200
201
Status TxnManager::publish_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
202
                               TTransactionId transaction_id, const Version& version,
203
                               TabletPublishStatistics* stats,
204
9
                               std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info) {
205
9
    return publish_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
206
9
                       tablet->tablet_id(), tablet->tablet_uid(), version, stats,
207
9
                       extend_tablet_txn_info);
208
9
}
209
210
void TxnManager::abort_txn(TPartitionId partition_id, TTransactionId transaction_id,
211
0
                           TTabletId tablet_id, TabletUid tablet_uid) {
212
0
    pair<int64_t, int64_t> key(partition_id, transaction_id);
213
0
    TabletInfo tablet_info(tablet_id, tablet_uid);
214
215
0
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
216
217
0
    auto& txn_tablet_map = _get_txn_tablet_map(transaction_id);
218
0
    auto it = txn_tablet_map.find(key);
219
0
    if (it == txn_tablet_map.end()) {
220
0
        return;
221
0
    }
222
223
0
    auto& tablet_txn_info_map = it->second;
224
0
    auto tablet_txn_info_iter = tablet_txn_info_map.find(tablet_info);
225
0
    if (tablet_txn_info_iter == tablet_txn_info_map.end()) {
226
0
        return;
227
0
    }
228
229
0
    auto& txn_info = tablet_txn_info_iter->second;
230
0
    txn_info->abort();
231
0
}
232
233
// delete the txn from manager if it is not committed(not have a valid rowset)
234
Status TxnManager::rollback_txn(TPartitionId partition_id, const Tablet& tablet,
235
15
                                TTransactionId transaction_id) {
236
15
    return rollback_txn(partition_id, transaction_id, tablet.tablet_id(), tablet.tablet_uid());
237
15
}
238
239
Status TxnManager::delete_txn(TPartitionId partition_id, const TabletSharedPtr& tablet,
240
0
                              TTransactionId transaction_id) {
241
0
    return delete_txn(tablet->data_dir()->get_meta(), partition_id, transaction_id,
242
0
                      tablet->tablet_id(), tablet->tablet_uid());
243
0
}
244
245
void TxnManager::set_txn_related_delete_bitmap(
246
        TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id,
247
        TabletUid tablet_uid, bool unique_key_merge_on_write, DeleteBitmapPtr delete_bitmap,
248
        const RowsetIdUnorderedSet& rowset_ids,
249
15
        std::shared_ptr<PartialUpdateInfo> partial_update_info) {
250
15
    pair<int64_t, int64_t> key(partition_id, transaction_id);
251
15
    TabletInfo tablet_info(tablet_id, tablet_uid);
252
253
15
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
254
15
    {
255
        // get tx
256
15
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
257
15
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
258
15
        auto it = txn_tablet_map.find(key);
259
15
        if (it == txn_tablet_map.end()) {
260
3
            LOG(WARNING) << "transaction_id: " << transaction_id
261
3
                         << " partition_id: " << partition_id << " may be cleared";
262
3
            return;
263
3
        }
264
12
        auto load_itr = it->second.find(tablet_info);
265
12
        if (load_itr == it->second.end()) {
266
0
            LOG(WARNING) << "transaction_id: " << transaction_id
267
0
                         << " partition_id: " << partition_id << " tablet_id: " << tablet_id
268
0
                         << " may be cleared";
269
0
            return;
270
0
        }
271
12
        auto& load_info = load_itr->second;
272
12
        load_info->unique_key_merge_on_write = unique_key_merge_on_write;
273
12
        load_info->delete_bitmap = delete_bitmap;
274
12
        load_info->rowset_ids = rowset_ids;
275
12
        load_info->partial_update_info = partial_update_info;
276
12
    }
277
12
}
278
279
Status TxnManager::commit_txn(OlapMeta* meta, TPartitionId partition_id,
280
                              TTransactionId transaction_id, TTabletId tablet_id,
281
                              TabletUid tablet_uid, const PUniqueId& load_id,
282
                              const RowsetSharedPtr& rowset_ptr, PendingRowsetGuard guard,
283
                              bool is_recovery,
284
105
                              std::shared_ptr<PartialUpdateInfo> partial_update_info) {
285
105
    if (partition_id < 1 || transaction_id < 1 || tablet_id < 1) {
286
0
        LOG(WARNING) << "invalid commit req "
287
0
                     << " partition_id=" << partition_id << " transaction_id=" << transaction_id
288
0
                     << " tablet_id=" << tablet_id;
289
0
        return Status::InternalError("invalid partition id");
290
0
    }
291
292
105
    pair<int64_t, int64_t> key(partition_id, transaction_id);
293
105
    TabletInfo tablet_info(tablet_id, tablet_uid);
294
105
    if (rowset_ptr == nullptr) {
295
0
        return Status::Error<ROWSET_INVALID>(
296
0
                "could not commit txn because rowset ptr is null. partition_id: {}, "
297
0
                "transaction_id: {}, tablet: {}",
298
0
                key.first, key.second, tablet_info.to_string());
299
0
    }
300
301
105
    DBUG_EXECUTE_IF("TxnManager.commit_txn.random_failed", {
302
105
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
303
105
            LOG_WARNING("TxnManager.commit_txn.random_failed")
304
105
                    .tag("txn_id", transaction_id)
305
105
                    .tag("tablet_id", tablet_id);
306
105
            return Status::InternalError("debug commit txn random failed");
307
105
        }
308
105
    });
309
105
    DBUG_EXECUTE_IF("TxnManager.commit_txn.wait", {
310
105
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
311
105
            LOG_WARNING("TxnManager.commit_txn.wait")
312
105
                    .tag("txn_id", transaction_id)
313
105
                    .tag("tablet_id", tablet_id)
314
105
                    .tag("wait ms", wait);
315
105
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
316
105
        }
317
105
    });
318
319
105
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
320
    // this while loop just run only once, just for if break
321
105
    do {
322
        // get tx
323
105
        std::shared_lock rdlock(_get_txn_map_lock(transaction_id));
324
105
        auto rs_pb = rowset_ptr->rowset_meta()->get_rowset_pb();
325
        // TODO(dx): remove log after fix partition id eq 0 bug
326
105
        if (!rs_pb.has_partition_id() || rs_pb.partition_id() == 0) {
327
3
            rowset_ptr->rowset_meta()->set_partition_id(partition_id);
328
3
            LOG(WARNING) << "cant get partition id from rs pb, get from func arg partition_id="
329
3
                         << partition_id;
330
3
        }
331
105
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
332
105
        auto it = txn_tablet_map.find(key);
333
105
        if (it == txn_tablet_map.end()) {
334
27
            break;
335
27
        }
336
337
78
        auto load_itr = it->second.find(tablet_info);
338
78
        if (load_itr == it->second.end()) {
339
0
            break;
340
0
        }
341
342
        // found load for txn,tablet
343
        // case 1: user commit rowset, then the load id must be equal
344
78
        auto& load_info = load_itr->second;
345
        // check if load id is equal
346
78
        if (load_info->rowset == nullptr) {
347
72
            break;
348
72
        }
349
350
6
        if (load_info->load_id.hi() != load_id.hi() || load_info->load_id.lo() != load_id.lo()) {
351
0
            break;
352
0
        }
353
354
        // find a rowset with same rowset id, then it means a duplicate call
355
6
        if (load_info->rowset->rowset_id() == rowset_ptr->rowset_id()) {
356
3
            LOG(INFO) << "find rowset exists when commit transaction to engine."
357
3
                      << "partition_id: " << key.first << ", transaction_id: " << key.second
358
3
                      << ", tablet: " << tablet_info.to_string()
359
3
                      << ", rowset_id: " << load_info->rowset->rowset_id();
360
            // Should not remove this rowset from pending rowsets
361
3
            load_info->pending_rs_guard = std::move(guard);
362
3
            return Status::OK();
363
3
        }
364
365
        // find a rowset with different rowset id, then it should not happen, just return errors
366
3
        return Status::Error<PUSH_TRANSACTION_ALREADY_EXIST>(
367
3
                "find rowset exists when commit transaction to engine. but rowset ids are not "
368
3
                "same. partition_id: {}, transaction_id: {}, tablet: {}, exist rowset_id: {}, new "
369
3
                "rowset_id: {}",
370
3
                key.first, key.second, tablet_info.to_string(),
371
3
                load_info->rowset->rowset_id().to_string(), rowset_ptr->rowset_id().to_string());
372
6
    } while (false);
373
374
    // if not in recovery mode, then should persist the meta to meta env
375
    // save meta need access disk, it maybe very slow, so that it is not in global txn lock
376
    // it is under a single txn lock
377
99
    if (!is_recovery) {
378
99
        Status save_status =
379
99
                RowsetMetaManager::save(meta, tablet_uid, rowset_ptr->rowset_id(),
380
99
                                        rowset_ptr->rowset_meta()->get_rowset_pb(), false);
381
99
        DBUG_EXECUTE_IF("TxnManager.RowsetMetaManager.save_wait", {
382
99
            if (auto wait = dp->param<int>("duration", 0); wait > 0) {
383
99
                LOG_WARNING("TxnManager.RowsetMetaManager.save_wait")
384
99
                        .tag("txn_id", transaction_id)
385
99
                        .tag("tablet_id", tablet_id)
386
99
                        .tag("wait ms", wait);
387
99
                std::this_thread::sleep_for(std::chrono::milliseconds(wait));
388
99
            }
389
99
        });
390
99
        if (!save_status.ok()) {
391
0
            save_status.append(fmt::format(", txn id: {}", transaction_id));
392
0
            return save_status;
393
0
        }
394
395
99
        if (partial_update_info && partial_update_info->is_partial_update()) {
396
0
            PartialUpdateInfoPB partial_update_info_pb;
397
0
            partial_update_info->to_pb(&partial_update_info_pb);
398
0
            save_status = RowsetMetaManager::save_partial_update_info(
399
0
                    meta, tablet_id, partition_id, transaction_id, partial_update_info_pb);
400
0
            if (!save_status.ok()) {
401
0
                save_status.append(fmt::format(", txn_id: {}", transaction_id));
402
0
                return save_status;
403
0
            }
404
0
        }
405
99
    }
406
407
99
    TabletSharedPtr tablet;
408
99
    std::shared_ptr<PartialUpdateInfo> decoded_partial_update_info {nullptr};
409
99
    if (is_recovery) {
410
0
        tablet = _engine.tablet_manager()->get_tablet(tablet_id, tablet_uid);
411
0
        if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
412
0
            PartialUpdateInfoPB partial_update_info_pb;
413
0
            auto st = RowsetMetaManager::try_get_partial_update_info(
414
0
                    meta, tablet_id, partition_id, transaction_id, &partial_update_info_pb);
415
0
            if (st.ok()) {
416
0
                decoded_partial_update_info = std::make_shared<PartialUpdateInfo>();
417
0
                decoded_partial_update_info->from_pb(&partial_update_info_pb);
418
0
                DCHECK(decoded_partial_update_info->is_partial_update());
419
0
            } else if (!st.is<META_KEY_NOT_FOUND>()) {
420
                // the load is not a partial update
421
0
                return st;
422
0
            }
423
0
        }
424
0
    }
425
426
99
    {
427
99
        std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
428
99
        auto load_info = std::make_shared<TabletTxnInfo>(load_id, rowset_ptr);
429
99
        load_info->pending_rs_guard = std::move(guard);
430
99
        if (is_recovery) {
431
0
            if (tablet != nullptr && tablet->enable_unique_key_merge_on_write()) {
432
0
                load_info->unique_key_merge_on_write = true;
433
0
                load_info->delete_bitmap.reset(new DeleteBitmap(tablet->tablet_id()));
434
0
                if (decoded_partial_update_info) {
435
0
                    LOG_INFO(
436
0
                            "get partial update info from RocksDB during recovery. txn_id={}, "
437
0
                            "partition_id={}, tablet_id={}, partial_update_info=[{}]",
438
0
                            transaction_id, partition_id, tablet_id,
439
0
                            decoded_partial_update_info->summary());
440
0
                    load_info->partial_update_info = decoded_partial_update_info;
441
0
                }
442
0
            }
443
0
        }
444
99
        load_info->commit();
445
446
99
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
447
99
        txn_tablet_map[key][tablet_info] = std::move(load_info);
448
99
        _insert_txn_partition_map_unlocked(transaction_id, partition_id);
449
99
        VLOG_NOTICE << "commit transaction to engine successfully."
450
0
                    << " partition_id: " << key.first << ", transaction_id: " << key.second
451
0
                    << ", tablet: " << tablet_info.to_string()
452
0
                    << ", rowsetid: " << rowset_ptr->rowset_id()
453
0
                    << ", version: " << rowset_ptr->version().first;
454
99
    }
455
99
    return Status::OK();
456
99
}
457
458
// remove a txn from txn manager
459
Status TxnManager::publish_txn(OlapMeta* meta, TPartitionId partition_id,
460
                               TTransactionId transaction_id, TTabletId tablet_id,
461
                               TabletUid tablet_uid, const Version& version,
462
                               TabletPublishStatistics* stats,
463
45
                               std::shared_ptr<TabletTxnInfo>& extend_tablet_txn_info) {
464
45
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
465
45
    if (tablet == nullptr) {
466
0
        return Status::OK();
467
0
    }
468
45
    DCHECK(stats != nullptr);
469
470
45
    pair<int64_t, int64_t> key(partition_id, transaction_id);
471
45
    TabletInfo tablet_info(tablet_id, tablet_uid);
472
45
    RowsetSharedPtr rowset;
473
45
    std::shared_ptr<TabletTxnInfo> tablet_txn_info;
474
45
    int64_t t1 = MonotonicMicros();
475
    /// Step 1: get rowset, tablet_txn_info by key
476
45
    {
477
45
        std::shared_lock txn_rlock(_get_txn_lock(transaction_id));
478
45
        std::shared_lock txn_map_rlock(_get_txn_map_lock(transaction_id));
479
45
        stats->lock_wait_time_us += MonotonicMicros() - t1;
480
481
45
        txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
482
45
        if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
483
42
            auto& tablet_map = it->second;
484
42
            if (auto txn_info_iter = tablet_map.find(tablet_info);
485
42
                txn_info_iter != tablet_map.end()) {
486
                // found load for txn,tablet
487
                // case 1: user commit rowset, then the load id must be equal
488
42
                tablet_txn_info = txn_info_iter->second;
489
42
                extend_tablet_txn_info = tablet_txn_info;
490
42
                rowset = tablet_txn_info->rowset;
491
42
            }
492
42
        }
493
45
    }
494
45
    if (rowset == nullptr) {
495
3
        return Status::Error<TRANSACTION_NOT_EXIST>(
496
3
                "publish txn failed, rowset not found. partition_id={}, transaction_id={}, "
497
3
                "tablet={}",
498
3
                partition_id, transaction_id, tablet_info.to_string());
499
3
    }
500
42
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_before_save_rs_meta", {
501
42
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
502
42
            LOG_WARNING("TxnManager.publish_txn.random_failed_before_save_rs_meta")
503
42
                    .tag("txn_id", transaction_id)
504
42
                    .tag("tablet_id", tablet_id);
505
42
            return Status::InternalError("debug publish txn before save rs meta random failed");
506
42
        }
507
42
    });
508
42
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_before_save_rs_meta", {
509
42
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
510
42
            LOG_WARNING("TxnManager.publish_txn.wait_before_save_rs_meta")
511
42
                    .tag("txn_id", transaction_id)
512
42
                    .tag("tablet_id", tablet_id)
513
42
                    .tag("wait ms", wait);
514
42
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
515
42
        }
516
42
    });
517
518
    /// Step 2: make rowset visible
519
    // save meta need access disk, it maybe very slow, so that it is not in global txn lock
520
    // it is under a single txn lock
521
    // TODO(ygl): rowset is already set version here, memory is changed, if save failed
522
    // it maybe a fatal error
523
42
    rowset->make_visible(version);
524
525
42
    DBUG_EXECUTE_IF("TxnManager.publish_txn.random_failed_after_save_rs_meta", {
526
42
        if (rand() % 100 < (100 * dp->param("percent", 0.5))) {
527
42
            LOG_WARNING("TxnManager.publish_txn.random_failed_after_save_rs_meta")
528
42
                    .tag("txn_id", transaction_id)
529
42
                    .tag("tablet_id", tablet_id);
530
42
            return Status::InternalError("debug publish txn after save rs meta random failed");
531
42
        }
532
42
    });
533
42
    DBUG_EXECUTE_IF("TxnManager.publish_txn.wait_after_save_rs_meta", {
534
42
        if (auto wait = dp->param<int>("duration", 0); wait > 0) {
535
42
            LOG_WARNING("TxnManager.publish_txn.wait_after_save_rs_meta")
536
42
                    .tag("txn_id", transaction_id)
537
42
                    .tag("tablet_id", tablet_id)
538
42
                    .tag("wait ms", wait);
539
42
            std::this_thread::sleep_for(std::chrono::milliseconds(wait));
540
42
        }
541
42
    });
542
    // update delete_bitmap
543
42
    if (tablet_txn_info->unique_key_merge_on_write) {
544
9
        int64_t t2 = MonotonicMicros();
545
9
        if (rowset->num_segments() > 1 &&
546
9
            !tablet_txn_info->delete_bitmap->has_calculated_for_multi_segments(
547
0
                    rowset->rowset_id())) {
548
            // delete bitmap is empty, should re-calculate delete bitmaps between segments
549
0
            std::vector<segment_v2::SegmentSharedPtr> segments;
550
0
            RETURN_IF_ERROR(std::static_pointer_cast<BetaRowset>(rowset)->load_segments(&segments));
551
0
            RETURN_IF_ERROR(tablet->calc_delete_bitmap_between_segments(
552
0
                    rowset->rowset_id(), segments, tablet_txn_info->delete_bitmap));
553
0
        }
554
555
9
        RETURN_IF_ERROR(
556
9
                Tablet::update_delete_bitmap(tablet, tablet_txn_info.get(), transaction_id));
557
9
        int64_t t3 = MonotonicMicros();
558
9
        stats->calc_delete_bitmap_time_us = t3 - t2;
559
9
        RETURN_IF_ERROR(TabletMetaManager::save_delete_bitmap(
560
9
                tablet->data_dir(), tablet->tablet_id(), tablet_txn_info->delete_bitmap,
561
9
                version.second));
562
9
        stats->save_meta_time_us = MonotonicMicros() - t3;
563
9
    }
564
565
    /// Step 3:  add to binlog
566
42
    auto enable_binlog = tablet->is_enable_binlog();
567
42
    if (enable_binlog) {
568
0
        auto status = rowset->add_to_binlog();
569
0
        if (!status.ok()) {
570
0
            return Status::Error<ROWSET_ADD_TO_BINLOG_FAILED>(
571
0
                    "add rowset to binlog failed. when publish txn rowset_id: {}, tablet id: {}, "
572
0
                    "txn id: {}, status: {}",
573
0
                    rowset->rowset_id().to_string(), tablet_id, transaction_id,
574
0
                    status.to_string_no_stack());
575
0
        }
576
0
    }
577
578
    /// Step 4: save meta
579
42
    int64_t t5 = MonotonicMicros();
580
42
    auto status = RowsetMetaManager::save(meta, tablet_uid, rowset->rowset_id(),
581
42
                                          rowset->rowset_meta()->get_rowset_pb(), enable_binlog);
582
42
    stats->save_meta_time_us += MonotonicMicros() - t5;
583
42
    if (!status.ok()) {
584
0
        status.append(fmt::format(", txn id: {}", transaction_id));
585
0
        return status;
586
0
    }
587
588
42
    if (tablet_txn_info->unique_key_merge_on_write && tablet_txn_info->partial_update_info &&
589
42
        tablet_txn_info->partial_update_info->is_partial_update()) {
590
0
        status = RowsetMetaManager::remove_partial_update_info(meta, tablet_id, partition_id,
591
0
                                                               transaction_id);
592
0
        if (!status) {
593
            // discard the error status and print the warning log
594
0
            LOG_WARNING(
595
0
                    "fail to remove partial update info from RocksDB. txn_id={}, rowset_id={}, "
596
0
                    "tablet_id={}, tablet_uid={}",
597
0
                    transaction_id, rowset->rowset_id().to_string(), tablet_id,
598
0
                    tablet_uid.to_string());
599
0
        }
600
0
    }
601
602
    // TODO(Drogon): remove these test codes
603
42
    if (enable_binlog) {
604
0
        auto version_str = fmt::format("{}", version.first);
605
0
        VLOG_DEBUG << fmt::format("tabletid: {}, version: {}, binlog filepath: {}", tablet_id,
606
0
                                  version_str, tablet->get_binlog_filepath(version_str));
607
0
    }
608
609
    /// Step 5: remove tablet_info from tnx_tablet_map
610
    // txn_tablet_map[key] empty, remove key from txn_tablet_map
611
42
    int64_t t6 = MonotonicMicros();
612
42
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
613
42
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
614
42
    stats->lock_wait_time_us += MonotonicMicros() - t6;
615
42
    _remove_txn_tablet_info_unlocked(partition_id, transaction_id, tablet_id, tablet_uid, txn_lock,
616
42
                                     wrlock);
617
42
    VLOG_NOTICE << "publish txn successfully."
618
0
                << " partition_id: " << key.first << ", txn_id: " << key.second
619
0
                << ", tablet_id: " << tablet_info.tablet_id << ", rowsetid: " << rowset->rowset_id()
620
0
                << ", version: " << version.first << "," << version.second;
621
42
    return status;
622
42
}
623
624
void TxnManager::_remove_txn_tablet_info_unlocked(TPartitionId partition_id,
625
                                                  TTransactionId transaction_id,
626
                                                  TTabletId tablet_id, TabletUid tablet_uid,
627
                                                  std::lock_guard<std::shared_mutex>& txn_lock,
628
42
                                                  std::lock_guard<std::shared_mutex>& wrlock) {
629
42
    std::pair<int64_t, int64_t> key {partition_id, transaction_id};
630
42
    TabletInfo tablet_info {tablet_id, tablet_uid};
631
42
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
632
42
    if (auto it = txn_tablet_map.find(key); it != txn_tablet_map.end()) {
633
42
        it->second.erase(tablet_info);
634
42
        if (it->second.empty()) {
635
42
            txn_tablet_map.erase(it);
636
42
            g_tablet_txn_info_txn_partitions_count << -1;
637
42
            _clear_txn_partition_map_unlocked(transaction_id, partition_id);
638
42
        }
639
42
    }
640
42
}
641
642
void TxnManager::remove_txn_tablet_info(TPartitionId partition_id, TTransactionId transaction_id,
643
0
                                        TTabletId tablet_id, TabletUid tablet_uid) {
644
0
    std::lock_guard<std::shared_mutex> txn_lock(_get_txn_lock(transaction_id));
645
0
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
646
0
    _remove_txn_tablet_info_unlocked(partition_id, transaction_id, tablet_id, tablet_uid, txn_lock,
647
0
                                     wrlock);
648
0
}
649
650
// txn could be rollbacked if it does not have related rowset
651
// if the txn has related rowset then could not rollback it, because it
652
// may be committed in another thread and our current thread meets errors when writing to data file
653
// BE has to wait for fe call clear txn api
654
Status TxnManager::rollback_txn(TPartitionId partition_id, TTransactionId transaction_id,
655
21
                                TTabletId tablet_id, TabletUid tablet_uid) {
656
21
    pair<int64_t, int64_t> key(partition_id, transaction_id);
657
21
    TabletInfo tablet_info(tablet_id, tablet_uid);
658
659
21
    std::lock_guard<std::shared_mutex> wrlock(_get_txn_map_lock(transaction_id));
660
21
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
661
662
21
    auto it = txn_tablet_map.find(key);
663
21
    if (it == txn_tablet_map.end()) {
664
0
        return Status::OK();
665
0
    }
666
667
21
    auto& tablet_txn_info_map = it->second;
668
21
    if (auto load_itr = tablet_txn_info_map.find(tablet_info);
669
21
        load_itr != tablet_txn_info_map.end()) {
670
        // found load for txn,tablet
671
        // case 1: user commit rowset, then the load id must be equal
672
21
        const auto& load_info = load_itr->second;
673
21
        if (load_info->rowset != nullptr) {
674
3
            return Status::Error<TRANSACTION_ALREADY_COMMITTED>(
675
3
                    "if rowset is not null, it means other thread may commit the rowset should "
676
3
                    "not delete txn any more");
677
3
        }
678
21
    }
679
680
18
    tablet_txn_info_map.erase(tablet_info);
681
18
    LOG(INFO) << "rollback transaction from engine successfully."
682
18
              << " partition_id: " << key.first << ", transaction_id: " << key.second
683
18
              << ", tablet: " << tablet_info.to_string();
684
18
    if (tablet_txn_info_map.empty()) {
685
18
        txn_tablet_map.erase(it);
686
18
        g_tablet_txn_info_txn_partitions_count << -1;
687
18
        _clear_txn_partition_map_unlocked(transaction_id, partition_id);
688
18
    }
689
18
    return Status::OK();
690
21
}
691
692
// fe call this api to clear unused rowsets in be
693
// could not delete the rowset if it already has a valid version
694
Status TxnManager::delete_txn(OlapMeta* meta, TPartitionId partition_id,
695
                              TTransactionId transaction_id, TTabletId tablet_id,
696
12
                              TabletUid tablet_uid) {
697
12
    pair<int64_t, int64_t> key(partition_id, transaction_id);
698
12
    TabletInfo tablet_info(tablet_id, tablet_uid);
699
12
    std::lock_guard<std::shared_mutex> txn_wrlock(_get_txn_map_lock(transaction_id));
700
12
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
701
12
    auto it = txn_tablet_map.find(key);
702
12
    if (it == txn_tablet_map.end()) {
703
0
        return Status::Error<TRANSACTION_NOT_EXIST>("key not founded from txn_tablet_map");
704
0
    }
705
12
    Status st = Status::OK();
706
12
    auto load_itr = it->second.find(tablet_info);
707
12
    if (load_itr != it->second.end()) {
708
        // found load for txn,tablet
709
        // case 1: user commit rowset, then the load id must be equal
710
12
        auto& load_info = load_itr->second;
711
12
        auto& rowset = load_info->rowset;
712
12
        if (rowset != nullptr && meta != nullptr) {
713
9
            if (!rowset->is_pending()) {
714
3
                st = Status::Error<TRANSACTION_ALREADY_COMMITTED>(
715
3
                        "could not delete transaction from engine, just remove it from memory not "
716
3
                        "delete from disk, because related rowset already published. partition_id: "
717
3
                        "{}, transaction_id: {}, tablet: {}, rowset id: {}, version: {}, state: {}",
718
3
                        key.first, key.second, tablet_info.to_string(),
719
3
                        rowset->rowset_id().to_string(), rowset->version().to_string(),
720
3
                        RowsetStatePB_Name(rowset->rowset_meta_state()));
721
6
            } else {
722
6
                static_cast<void>(RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
723
#ifndef BE_TEST
724
                _engine.add_unused_rowset(rowset);
725
#endif
726
6
                VLOG_NOTICE << "delete transaction from engine successfully."
727
0
                            << " partition_id: " << key.first << ", transaction_id: " << key.second
728
0
                            << ", tablet: " << tablet_info.to_string() << ", rowset: "
729
0
                            << (rowset != nullptr ? rowset->rowset_id().to_string() : "0");
730
6
            }
731
9
        }
732
12
        it->second.erase(load_itr);
733
12
    }
734
12
    if (it->second.empty()) {
735
12
        txn_tablet_map.erase(it);
736
12
        g_tablet_txn_info_txn_partitions_count << -1;
737
12
        _clear_txn_partition_map_unlocked(transaction_id, partition_id);
738
12
    }
739
12
    return st;
740
12
}
741
742
void TxnManager::get_tablet_related_txns(TTabletId tablet_id, TabletUid tablet_uid,
743
                                         int64_t* partition_id,
744
18
                                         std::set<int64_t>* transaction_ids) {
745
18
    if (partition_id == nullptr || transaction_ids == nullptr) {
746
0
        LOG(WARNING) << "parameter is null when get transactions by tablet";
747
0
        return;
748
0
    }
749
750
18
    TabletInfo tablet_info(tablet_id, tablet_uid);
751
36
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
752
18
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
753
18
        txn_tablet_map_t& txn_tablet_map = _txn_tablet_maps[i];
754
18
        for (auto& it : txn_tablet_map) {
755
3
            if (it.second.find(tablet_info) != it.second.end()) {
756
3
                *partition_id = it.first.first;
757
3
                transaction_ids->insert(it.first.second);
758
3
                VLOG_NOTICE << "find transaction on tablet."
759
0
                            << "partition_id: " << it.first.first
760
0
                            << ", transaction_id: " << it.first.second
761
0
                            << ", tablet: " << tablet_info.to_string();
762
3
            }
763
3
        }
764
18
    }
765
18
}
766
767
// force drop all txns related with the tablet
768
// maybe lock error, because not get txn lock before remove from meta
769
void TxnManager::force_rollback_tablet_related_txns(OlapMeta* meta, TTabletId tablet_id,
770
0
                                                    TabletUid tablet_uid) {
771
0
    TabletInfo tablet_info(tablet_id, tablet_uid);
772
0
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
773
0
        std::lock_guard<std::shared_mutex> txn_wrlock(_txn_map_locks[i]);
774
0
        txn_tablet_map_t& txn_tablet_map = _txn_tablet_maps[i];
775
0
        for (auto it = txn_tablet_map.begin(); it != txn_tablet_map.end();) {
776
0
            auto load_itr = it->second.find(tablet_info);
777
0
            if (load_itr != it->second.end()) {
778
0
                auto& load_info = load_itr->second;
779
0
                auto& rowset = load_info->rowset;
780
0
                if (rowset != nullptr && meta != nullptr) {
781
0
                    LOG(INFO) << " delete transaction from engine "
782
0
                              << ", tablet: " << tablet_info.to_string()
783
0
                              << ", rowset id: " << rowset->rowset_id();
784
0
                    static_cast<void>(
785
0
                            RowsetMetaManager::remove(meta, tablet_uid, rowset->rowset_id()));
786
0
                }
787
0
                LOG(INFO) << "remove tablet related txn."
788
0
                          << " partition_id: " << it->first.first
789
0
                          << ", transaction_id: " << it->first.second
790
0
                          << ", tablet: " << tablet_info.to_string() << ", rowset: "
791
0
                          << (rowset != nullptr ? rowset->rowset_id().to_string() : "0");
792
0
                it->second.erase(load_itr);
793
0
            }
794
0
            if (it->second.empty()) {
795
0
                _clear_txn_partition_map_unlocked(it->first.second, it->first.first);
796
0
                it = txn_tablet_map.erase(it);
797
0
                g_tablet_txn_info_txn_partitions_count << -1;
798
0
            } else {
799
0
                ++it;
800
0
            }
801
0
        }
802
0
    }
803
0
    if (meta != nullptr) {
804
0
        Status st = RowsetMetaManager::remove_tablet_related_partial_update_info(meta, tablet_id);
805
0
        if (!st.ok()) {
806
0
            LOG_WARNING("failed to partial update info, tablet_id={}, err={}", tablet_id,
807
0
                        st.to_string());
808
0
        }
809
0
    }
810
0
}
811
812
void TxnManager::get_txn_related_tablets(const TTransactionId transaction_id,
813
                                         TPartitionId partition_id,
814
105
                                         std::map<TabletInfo, RowsetSharedPtr>* tablet_infos) {
815
    // get tablets in this transaction
816
105
    pair<int64_t, int64_t> key(partition_id, transaction_id);
817
105
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
818
105
    txn_tablet_map_t& txn_tablet_map = _get_txn_tablet_map(transaction_id);
819
105
    auto it = txn_tablet_map.find(key);
820
105
    if (it == txn_tablet_map.end()) {
821
6
        VLOG_NOTICE << "could not find tablet for"
822
0
                    << " partition_id=" << partition_id << ", transaction_id=" << transaction_id;
823
6
        return;
824
6
    }
825
99
    auto& load_info_map = it->second;
826
827
    // each tablet
828
117
    for (auto& load_info : load_info_map) {
829
117
        const TabletInfo& tablet_info = load_info.first;
830
        // must not check rowset == null here, because if rowset == null
831
        // publish version should failed
832
117
        tablet_infos->emplace(tablet_info, load_info.second->rowset);
833
117
    }
834
99
}
835
836
0
void TxnManager::get_all_related_tablets(std::set<TabletInfo>* tablet_infos) {
837
0
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
838
0
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
839
0
        for (auto& it : _txn_tablet_maps[i]) {
840
0
            for (auto& tablet_load_it : it.second) {
841
0
                tablet_infos->emplace(tablet_load_it.first);
842
0
            }
843
0
        }
844
0
    }
845
0
}
846
847
void TxnManager::get_all_commit_tablet_txn_info_by_tablet(
848
3
        const Tablet& tablet, CommitTabletTxnInfoVec* commit_tablet_txn_info_vec) {
849
6
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
850
3
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
851
6
        for (const auto& [txn_key, load_info_map] : _txn_tablet_maps[i]) {
852
6
            auto tablet_load_it = load_info_map.find(tablet.get_tablet_info());
853
6
            if (tablet_load_it != load_info_map.end()) {
854
6
                const auto& [_, load_info] = *tablet_load_it;
855
6
                const auto& rowset = load_info->rowset;
856
6
                const auto& delete_bitmap = load_info->delete_bitmap;
857
6
                if (!rowset || !delete_bitmap) {
858
3
                    continue;
859
3
                }
860
3
                commit_tablet_txn_info_vec->push_back({
861
3
                        .transaction_id = txn_key.second,
862
3
                        .partition_id = txn_key.first,
863
3
                        .delete_bitmap = delete_bitmap,
864
3
                        .rowset_ids = load_info->rowset_ids,
865
3
                        .partial_update_info = load_info->partial_update_info,
866
3
                });
867
3
            }
868
6
        }
869
3
    }
870
3
}
871
872
0
void TxnManager::build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map) {
873
0
    int64_t now = UnixSeconds();
874
    // traverse the txn map, and get all expired txns
875
0
    for (int32_t i = 0; i < _txn_map_shard_size; i++) {
876
0
        std::shared_lock txn_rdlock(_txn_map_locks[i]);
877
0
        for (auto&& [txn_key, tablet_txn_infos] : _txn_tablet_maps[i]) {
878
0
            auto txn_id = txn_key.second;
879
0
            for (auto&& [tablet_info, txn_info] : tablet_txn_infos) {
880
0
                double diff = difftime(now, txn_info->creation_time);
881
0
                if (diff < config::pending_data_expire_time_sec) {
882
0
                    continue;
883
0
                }
884
885
0
                (*expire_txn_map)[tablet_info].push_back(txn_id);
886
0
                if (VLOG_IS_ON(3)) {
887
0
                    VLOG_NOTICE << "find expired txn."
888
0
                                << " tablet=" << tablet_info.to_string()
889
0
                                << " transaction_id=" << txn_id << " exist_sec=" << diff;
890
0
                }
891
0
            }
892
0
        }
893
0
    }
894
0
}
895
896
void TxnManager::get_partition_ids(const TTransactionId transaction_id,
897
6
                                   std::vector<TPartitionId>* partition_ids) {
898
6
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
899
6
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
900
6
    auto it = txn_partition_map.find(transaction_id);
901
6
    if (it != txn_partition_map.end()) {
902
3
        for (int64_t partition_id : it->second) {
903
3
            partition_ids->push_back(partition_id);
904
3
        }
905
3
    }
906
6
}
907
908
204
void TxnManager::_insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
909
204
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
910
204
    auto find = txn_partition_map.find(transaction_id);
911
204
    if (find == txn_partition_map.end()) {
912
123
        txn_partition_map[transaction_id] = std::unordered_set<int64_t>();
913
123
    }
914
204
    txn_partition_map[transaction_id].insert(partition_id);
915
204
}
916
917
72
void TxnManager::_clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id) {
918
72
    txn_partition_map_t& txn_partition_map = _get_txn_partition_map(transaction_id);
919
72
    auto it = txn_partition_map.find(transaction_id);
920
72
    if (it != txn_partition_map.end()) {
921
72
        it->second.erase(partition_id);
922
72
        if (it->second.empty()) {
923
72
            txn_partition_map.erase(it);
924
72
        }
925
72
    }
926
72
}
927
928
void TxnManager::add_txn_tablet_delta_writer(int64_t transaction_id, int64_t tablet_id,
929
0
                                             DeltaWriter* delta_writer) {
930
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
931
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
932
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
933
0
            _get_txn_tablet_delta_writer_map(transaction_id);
934
0
    auto find = txn_tablet_delta_writer_map.find(transaction_id);
935
0
    if (find == txn_tablet_delta_writer_map.end()) {
936
0
        txn_tablet_delta_writer_map[transaction_id] = std::map<int64_t, DeltaWriter*>();
937
0
    }
938
0
    txn_tablet_delta_writer_map[transaction_id][tablet_id] = delta_writer;
939
0
}
940
941
void TxnManager::finish_slave_tablet_pull_rowset(int64_t transaction_id, int64_t tablet_id,
942
0
                                                 int64_t node_id, bool is_succeed) {
943
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
944
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
945
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
946
0
            _get_txn_tablet_delta_writer_map(transaction_id);
947
0
    auto find_txn = txn_tablet_delta_writer_map.find(transaction_id);
948
0
    if (find_txn == txn_tablet_delta_writer_map.end()) {
949
0
        LOG(WARNING) << "delta writer manager is not exist, txn_id=" << transaction_id
950
0
                     << ", tablet_id=" << tablet_id;
951
0
        return;
952
0
    }
953
0
    auto find_tablet = txn_tablet_delta_writer_map[transaction_id].find(tablet_id);
954
0
    if (find_tablet == txn_tablet_delta_writer_map[transaction_id].end()) {
955
0
        LOG(WARNING) << "delta writer is not exist, txn_id=" << transaction_id
956
0
                     << ", tablet_id=" << tablet_id;
957
0
        return;
958
0
    }
959
0
    DeltaWriter* delta_writer = txn_tablet_delta_writer_map[transaction_id][tablet_id];
960
0
    delta_writer->finish_slave_tablet_pull_rowset(node_id, is_succeed);
961
0
}
962
963
0
void TxnManager::clear_txn_tablet_delta_writer(int64_t transaction_id) {
964
0
    std::lock_guard<std::shared_mutex> txn_wrlock(
965
0
            _get_txn_tablet_delta_writer_map_lock(transaction_id));
966
0
    txn_tablet_delta_writer_map_t& txn_tablet_delta_writer_map =
967
0
            _get_txn_tablet_delta_writer_map(transaction_id);
968
0
    auto it = txn_tablet_delta_writer_map.find(transaction_id);
969
0
    if (it != txn_tablet_delta_writer_map.end()) {
970
0
        txn_tablet_delta_writer_map.erase(it);
971
0
    }
972
0
    VLOG_CRITICAL << "remove delta writer manager, txn_id=" << transaction_id;
973
0
}
974
975
18
int64_t TxnManager::get_txn_by_tablet_version(int64_t tablet_id, int64_t version) {
976
18
    char key[16];
977
18
    memcpy(key, &tablet_id, sizeof(int64_t));
978
18
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
979
18
    CacheKey cache_key((const char*)&key, sizeof(key));
980
981
18
    auto* handle = _tablet_version_cache->lookup(cache_key);
982
18
    if (handle == nullptr) {
983
3
        return -1;
984
3
    }
985
15
    int64_t res = ((CacheValue*)_tablet_version_cache->value(handle))->value;
986
15
    _tablet_version_cache->release(handle);
987
15
    return res;
988
18
}
989
990
12
void TxnManager::update_tablet_version_txn(int64_t tablet_id, int64_t version, int64_t txn_id) {
991
12
    char key[16];
992
12
    memcpy(key, &tablet_id, sizeof(int64_t));
993
12
    memcpy(key + sizeof(int64_t), &version, sizeof(int64_t));
994
12
    CacheKey cache_key((const char*)&key, sizeof(key));
995
996
12
    auto* value = new CacheValue;
997
12
    value->value = txn_id;
998
12
    auto* handle = _tablet_version_cache->insert(cache_key, value, 1, sizeof(txn_id),
999
12
                                                 CachePriority::NORMAL);
1000
12
    _tablet_version_cache->release(handle);
1001
12
}
1002
1003
TxnState TxnManager::get_txn_state(TPartitionId partition_id, TTransactionId transaction_id,
1004
0
                                   TTabletId tablet_id, TabletUid tablet_uid) {
1005
0
    pair<int64_t, int64_t> key(partition_id, transaction_id);
1006
0
    TabletInfo tablet_info(tablet_id, tablet_uid);
1007
1008
0
    std::shared_lock txn_rdlock(_get_txn_map_lock(transaction_id));
1009
1010
0
    auto& txn_tablet_map = _get_txn_tablet_map(transaction_id);
1011
0
    auto it = txn_tablet_map.find(key);
1012
0
    if (it == txn_tablet_map.end()) {
1013
0
        return TxnState::NOT_FOUND;
1014
0
    }
1015
1016
0
    auto& tablet_txn_info_map = it->second;
1017
0
    auto tablet_txn_info_iter = tablet_txn_info_map.find(tablet_info);
1018
0
    if (tablet_txn_info_iter == tablet_txn_info_map.end()) {
1019
0
        return TxnState::NOT_FOUND;
1020
0
    }
1021
1022
0
    const auto& txn_info = tablet_txn_info_iter->second;
1023
0
    return txn_info->state;
1024
0
}
1025
1026
} // namespace doris