This repository has been archived by the owner on Mar 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathtransaction.hpp
707 lines (631 loc) · 19.1 KB
/
transaction.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2016-2020, Intel Corporation */
/**
* @file
* C++ pmemobj transactions.
*/
#ifndef LIBPMEMOBJ_CPP_TRANSACTION_HPP
#define LIBPMEMOBJ_CPP_TRANSACTION_HPP
#include <array>
#include <functional>
#include <string>
#include <vector>
#include <libpmemobj++/detail/common.hpp>
#include <libpmemobj++/pexceptions.hpp>
#include <libpmemobj++/pool.hpp>
#include <libpmemobj/tx_base.h>
#ifndef LIBPMEMOBJ_CPP_TX_FAILURE_ABORT
#define LIBPMEMOBJ_CPP_TX_FAILURE_EVENT return_error
#else
#define LIBPMEMOBJ_CPP_TX_FAILURE_EVENT abort
#endif
namespace pmem
{
namespace detail
{
/**
* A structure that checks if it is possible to snapshot the specified memory.
* Can have specialization.
*/
template <typename T>
struct can_do_snapshot {
static constexpr bool value = LIBPMEMOBJ_CPP_IS_TRIVIALLY_COPYABLE(T);
};
} /* namespace detail */
namespace obj
{
/**
* C++ transaction handler class.
*
* This class is the pmemobj transaction handler. Scoped transactions
* are handled through two internal classes: @ref manual and
* @ref automatic.
* - @ref manual transactions need to be committed manually, otherwise
* they will be aborted on object destruction.\n
* - @ref automatic transactions are only available in C++17. They
* handle transaction commit/abort automatically.
*
* This class also exposes a closure-like transaction API, which is the
* preferred way of handling transactions.
*
* Transactions can be configured using transaction::options structure. It
* allows to change transaction's behavior on failure. See
* transaction::failure_behavior for more details.
*
* This API should NOT be mixed with C transactions API. One issue is that
* C++ callbacks registered using transaction::register_callback() would not
* be called if C++ transaction is created inside C transaction.
* The same is true if user calls pmemobj_tx_set_user_data() inside a C++
* transaction.
*
* The typical usage example would be:
* @snippet transaction/transaction.cpp general_tx_example
*/
class transaction {
public:
class manual;
/** Specifies failure event in case of transaction error */
enum class failure_behavior {
abort = POBJ_TX_FAILURE_ABORT, /**< each transactional function
* will abort the transaction on
* error. */
return_error =
POBJ_TX_FAILURE_RETURN /**< transactional functions will
* throw an exception but will
* leave the transaction in work
* stage. */
};
/**
* options structure which can be used to control transaction
* behavior.
*/
struct options {
/** Controls behavior of transaction in case of errors. It can
* be failure_behavior::abort or failure_behavior::return_error.
* This setting is inherited by inner transactions.
* 'return_error' is the default behavior (unless
* LIBPMEMOBJ_CPP_TX_FAILURE_ABORT macro is defined). It is not
* possible to start an 'abort' transaction within
* 'return_error' transaction. */
::pmem::obj::transaction::failure_behavior failure_behavior =
::pmem::obj::transaction::failure_behavior::
LIBPMEMOBJ_CPP_TX_FAILURE_EVENT;
};
/**
* C++ manual scope transaction class.
*
* This class is one of pmemobj transaction handlers. All
* operations between creating and destroying the transaction
* object are treated as performed in a transaction block and
* can be rolled back. The manual transaction has to be
* committed explicitly otherwise it will abort.
*
* The locks are held for the entire duration of the transaction. They
* are released at the end of the scope, so within the `catch` block,
* they are already unlocked. If the cleanup action requires access to
* data within a critical section, the locks have to be manually
* acquired once again.
*
*The typical usage example would be:
* @snippet transaction/transaction.cpp manual_tx_example
*/
class manual {
public:
/**
* RAII constructor with pmem resident locks.
*
* Start pmemobj transaction and add list of locks to
* new transaction. The list of locks may be empty.
*
* @param[in,out] pop pool object.
* @param[in] opts options for controlling transaction behavior
* @param[in,out] locks locks of obj::mutex or
* obj::shared_mutex type.
*
* @throw pmem::transaction_error when pmemobj_tx_begin
* function or locks adding failed.
*/
template <typename... L>
manual(obj::pool_base &pop, options opts, L &... locks)
{
int ret = 0;
bool nested = pmemobj_tx_stage() == TX_STAGE_WORK;
if (nested) {
if (opts.failure_behavior ==
failure_behavior::abort &&
pmemobj_tx_get_failure_behavior() ==
POBJ_TX_FAILURE_RETURN)
throw pmem::transaction_error(
"Cannot start transaction with failure_behavior::abort. Outer transaction was configured with failure_behavior::return_error");
ret = pmemobj_tx_begin(pop.handle(), nullptr,
TX_PARAM_NONE);
} else if (pmemobj_tx_stage() == TX_STAGE_NONE) {
ret = pmemobj_tx_begin(pop.handle(), nullptr,
TX_PARAM_CB,
transaction::c_callback,
nullptr, TX_PARAM_NONE);
} else {
throw pmem::transaction_scope_error(
"Cannot start transaction in stage different than WORK or NONE");
}
if (ret != 0)
throw pmem::transaction_error(
"failed to start transaction")
.with_pmemobj_errormsg();
pmemobj_tx_set_failure_behavior(
(pobj_tx_failure_behavior)
opts.failure_behavior);
/*
* Even if opts.failure_behavior is set to return_error
* we have to abort the transaction if there is an
* active exception in the outer most transaction.
*/
should_abort_on_failure = opts.failure_behavior ==
failure_behavior::abort ||
!nested;
auto err = add_lock(locks...);
if (err) {
pmemobj_tx_abort(EINVAL);
(void)pmemobj_tx_end();
throw pmem::transaction_error(
"failed to add lock")
.with_pmemobj_errormsg();
}
}
template <typename... L>
manual(obj::pool_base &pop, L &... locks)
: manual(pop, options{}, locks...)
{
}
/**
* Destructor.
*
* End pmemobj transaction. If the transaction has not
* been committed before object destruction, an abort
* will be issued.
*/
~manual() noexcept
{
/* normal exit or with an active exception */
if (pmemobj_tx_stage() == TX_STAGE_WORK) {
if (should_abort_on_failure)
pmemobj_tx_abort(ECANCELED);
else
pmemobj_tx_commit();
}
(void)pmemobj_tx_end();
}
/**
* Deleted copy constructor.
*/
manual(const manual &p) = delete;
/**
* Deleted move constructor.
*/
manual(const manual &&p) = delete;
/**
* Deleted assignment operator.
*/
manual &operator=(const manual &p) = delete;
/**
* Deleted move assignment operator.
*/
manual &operator=(manual &&p) = delete;
private:
bool should_abort_on_failure;
};
/*
* XXX The Microsoft compiler does not follow the ISO SD-6: SG10 Feature
* Test Recommendations. "|| _MSC_VER >= 1900" is a workaround.
*/
#if __cpp_lib_uncaught_exceptions || _MSC_VER >= 1900
/**
* C++ automatic scope transaction class.
*
* This class is one of pmemobj transaction handlers. All
* operations between creating and destroying the transaction
* object are treated as performed in a transaction block and
* can be rolled back. If you have a C++17 compliant compiler,
* the automatic transaction will commit and abort
* automatically depending on the context of object destruction.
*
* The locks are held for the entire duration of the transaction. They
* are released at the end of the scope, so within the `catch` block,
* they are already unlocked. If the cleanup action requires access to
* data within a critical section, the locks have to be manually
* acquired once again.
*
* The typical usage example would be:
* @snippet transaction/transaction.cpp automatic_tx_example
*/
class automatic {
public:
/**
* RAII constructor with pmem resident locks.
*
* Start pmemobj transaction and add list of locks to
* new transaction. The list of locks may be empty.
*
* This class is only available if the
* `__cpp_lib_uncaught_exceptions` feature macro is
* defined. This is a C++17 feature.
*
* @param[in,out] pop pool object.
* @param[in] opts options for controlling transaction behavior
* @param[in,out] locks locks of obj::mutex or
* obj::shared_mutex type.
*
* @throw pmem::transaction_error when pmemobj_tx_begin
* function or locks adding failed.
*/
template <typename... L>
automatic(obj::pool_base &pop, options opts, L &... locks)
: tx_worker(pop, opts, locks...)
{
}
template <typename... L>
automatic(obj::pool_base &pop, L &... locks)
: automatic(pop, options{}, locks...)
{
}
/**
* Destructor.
*
* End pmemobj transaction. Depending on the context
* of object destruction, the transaction will
* automatically be either committed or aborted.
*
* @throw pmem::transaction_error if the transaction got aborted
* without an active exception.
*/
~automatic() noexcept(false)
{
/* active exception, abort handled by tx_worker */
if (exceptions.new_uncaught_exception())
return;
/* transaction ended normally */
if (pmemobj_tx_stage() == TX_STAGE_WORK)
pmemobj_tx_commit();
/* transaction aborted, throw an exception */
else if (pmemobj_tx_stage() == TX_STAGE_ONABORT ||
(pmemobj_tx_stage() == TX_STAGE_FINALLY &&
pmemobj_tx_errno() != 0))
throw pmem::transaction_error(
"Transaction aborted");
}
/**
* Deleted copy constructor.
*/
automatic(const automatic &p) = delete;
/**
* Deleted move constructor.
*/
automatic(const automatic &&p) = delete;
/**
* Deleted assignment operator.
*/
automatic &operator=(const automatic &p) = delete;
/**
* Deleted move assignment operator.
*/
automatic &operator=(automatic &&p) = delete;
private:
/**
* Internal class for counting active exceptions.
*/
class uncaught_exception_counter {
public:
/**
* Default constructor.
*
* Sets the number of active exceptions on
* object creation.
*/
uncaught_exception_counter()
: count(std::uncaught_exceptions())
{
}
/**
* Notifies is a new exception is being handled.
*
* @return true if a new exception was throw
* in the scope of the object, false
* otherwise.
*/
bool
new_uncaught_exception()
{
return std::uncaught_exceptions() > this->count;
}
private:
/**
* The number of active exceptions.
*/
int count;
} exceptions;
transaction::manual tx_worker;
};
#endif /* __cpp_lib_uncaught_exceptions */
/*
* Deleted default constructor.
*/
transaction() = delete;
/**
* Default destructor.
*
* End pmemobj transaction. If the transaction has not been
* committed before object destruction, an abort will be issued.
*/
~transaction() noexcept = delete;
/**
* Manually abort the current transaction.
*
* If called within an inner transaction, the outer transactions
* will also be aborted.
*
* @param[in] err the error to be reported as the reason of the
* abort.
*
* @throw transaction_error if the transaction is in an invalid
* state.
* @throw manual_tx_abort this exception is thrown to
* signify a transaction abort.
*/
static void
abort(int err)
{
if (pmemobj_tx_stage() != TX_STAGE_WORK)
throw pmem::transaction_error("wrong stage for abort");
pmemobj_tx_abort(err);
throw pmem::manual_tx_abort("explicit abort " +
std::to_string(err));
}
/**
* Manually commit a transaction.
*
* It is the sole responsibility of the caller, that after the
* call to transaction::commit() no other operations are done
* within the transaction.
*
* @throw transaction_error on any errors with ending the
* transaction.
*/
static void
commit()
{
if (pmemobj_tx_stage() != TX_STAGE_WORK)
throw pmem::transaction_error("wrong stage for commit");
pmemobj_tx_commit();
}
static int
error() noexcept
{
return pmemobj_tx_errno();
}
POBJ_CPP_DEPRECATED static int
get_last_tx_error() noexcept
{
return transaction::error();
}
template <typename... Locks>
static void
run(pool_base &pool, std::function<void()> tx, Locks &... locks)
{
run(pool, options{}, tx, locks...);
}
/**
* Execute a closure-like transaction and lock `locks`.
*
* The locks have to be persistent memory resident locks. An
* attempt to lock the locks will be made. If any of the
* specified locks is already locked, the method will block.
* The locks are held until the end of the transaction. The
* transaction does not have to be committed manually. Manual
* aborts will end the transaction with an active exception.
*
* If an exception is thrown within the transaction, it gets aborted
* and the exception is rethrown. Therefore extra care has to be taken
* with proper error handling.
*
* The locks are held for the entire duration of the transaction. They
* are released at the end of the scope, so within the `catch` block,
* they are already unlocked. If the cleanup action requires access to
* data within a critical section, the locks have to be manually
* acquired once again.
*
* @param[in,out] pool the pool in which the transaction will take
* place.
* @param[in] tx an std::function<void ()> which will perform
* operations within this transaction.
* @param[in] opts optional options object which affects transaction
* behavior.
* @param[in,out] locks locks to be taken for the duration of
* the transaction.
*
* @throw transaction_error on any error pertaining the execution
* of the transaction.
* @throw manual_tx_abort on manual transaction abort.
*/
template <typename... Locks>
static void
run(pool_base &pool, options opts, std::function<void()> tx,
Locks &... locks)
{
manual worker(pool, opts, locks...);
tx();
auto stage = pmemobj_tx_stage();
if (stage == TX_STAGE_WORK) {
pmemobj_tx_commit();
} else if (stage == TX_STAGE_ONABORT) {
throw pmem::transaction_error("transaction aborted");
} else if (stage == TX_STAGE_NONE) {
throw pmem::transaction_error(
"transaction ended prematurely");
}
}
template <typename... Locks>
POBJ_CPP_DEPRECATED static void
exec_tx(pool_base &pool, std::function<void()> tx, Locks &... locks)
{
transaction::run(pool, tx, locks...);
}
/**
* Takes a “snapshot” of given elements of type T number (1 by default),
* located at the given address ptr in the virtual memory space and
* saves it to the undo log. The application is then free to directly
* modify the object in that memory range. In case of a failure or
* abort, all the changes within this range will be rolled back. The
* supplied block of memory has to be within the pool registered in the
* transaction. This function must be called during transaction. This
* overload only participates in overload resolution of function
* template if T is either a trivially copyable type or some PMDK
* provided type.
*
* @param[in] addr pointer to the first object to be snapshotted.
* @param[in] num number of elements to be snapshotted.
*
* @pre this function must be called during transaction.
*
* @throw transaction_error when snapshotting failed or if function
* wasn't called during transaction.
*/
template <typename T,
typename std::enable_if<detail::can_do_snapshot<T>::value,
T>::type * = nullptr>
static void
snapshot(const T *addr, size_t num = 1)
{
if (TX_STAGE_WORK != pmemobj_tx_stage())
throw pmem::transaction_error(
"wrong stage for taking a snapshot.");
if (pmemobj_tx_add_range_direct(addr, sizeof(*addr) * num)) {
if (errno == ENOMEM)
throw pmem::transaction_out_of_memory(
"Could not take a snapshot of given memory range.")
.with_pmemobj_errormsg();
else
throw pmem::transaction_error(
"Could not take a snapshot of given memory range.")
.with_pmemobj_errormsg();
}
}
/**
* Possible stages of a transaction, for every stage one or more
* callbacks can be registered.
*/
enum class stage {
work = TX_STAGE_WORK, /* transaction in progress */
oncommit = TX_STAGE_ONCOMMIT, /* successfully committed */
onabort = TX_STAGE_ONABORT, /* tx_begin failed or transaction
aborted */
finally = TX_STAGE_FINALLY, /* ready for cleanup */
};
/**
* Registers callback to be called on specified stage for the
* transaction. In case of nested transactions those callbacks
* are called when the outer most transaction enters a specified stage.
*
* @pre this function must be called during a transaction.
*
* @throw transaction_scope_error when called outside of a transaction
* scope
*
* The typical usage example would be:
* @snippet transaction/transaction.cpp tx_callback_example
*/
static void
register_callback(stage stg, std::function<void()> cb)
{
if (pmemobj_tx_stage() != TX_STAGE_WORK)
throw pmem::transaction_scope_error(
"register_callback must be called during a transaction");
get_tx_data()->callbacks[static_cast<size_t>(stg)].push_back(
cb);
}
private:
/**
* Recursively add locks to the active transaction.
*
* The locks are taken in the provided order.
*
* @param[in,out] lock the lock to add.
* @param[in,out] locks the rest of the locks to be added to the
* active transaction.
*
* @return error number if adding any of the locks failed,
* 0 otherwise.
*/
template <typename L, typename... Locks>
static int
add_lock(L &lock, Locks &... locks) noexcept
{
auto err =
pmemobj_tx_lock(lock.lock_type(), lock.native_handle());
if (err)
return err;
return add_lock(locks...);
}
/**
* Method ending the recursive algorithm.
*/
static inline int
add_lock() noexcept
{
return 0;
}
using callbacks_list_type = std::vector<std::function<void()>>;
using callbacks_map_type =
std::array<callbacks_list_type, MAX_TX_STAGE>;
/**
* C-style function which is passed as callback to pmemobj_begin.
* It executes previously registered callbacks for all stages.
*/
static void
c_callback(PMEMobjpool *pop, enum pobj_tx_stage obj_stage, void *arg)
{
/*
* We cannot do anything when in TX_STAGE_NONE because
* pmemobj_tx_get_user_data() can only be called when there is
* an active transaction.
*/
if (obj_stage == TX_STAGE_NONE)
return;
auto *data = static_cast<tx_data *>(pmemobj_tx_get_user_data());
if (data == nullptr)
return;
for (auto &cb : data->callbacks[obj_stage])
cb();
/*
* Callback for TX_STAGE_FINALLY is called as the last one so we
* can free tx_data here
*/
if (obj_stage == TX_STAGE_FINALLY) {
delete data;
pmemobj_tx_set_user_data(NULL);
}
}
/**
* This data is stored along with the pmemobj transaction data using
* pmemobj_tx_set_data().
*/
struct tx_data {
callbacks_map_type callbacks;
};
/**
* Gets tx user data from pmemobj or creates it if this is a first
* call to this function inside a transaction.
*/
static tx_data *
get_tx_data()
{
auto *data = static_cast<tx_data *>(pmemobj_tx_get_user_data());
if (data == nullptr) {
data = new tx_data;
pmemobj_tx_set_user_data(data);
}
return data;
}
};
} /* namespace obj */
} /* namespace pmem */
#endif /* LIBPMEMOBJ_CPP_TRANSACTION_HPP */