-
Notifications
You must be signed in to change notification settings - Fork 46
/
storage.py
1606 lines (1369 loc) · 55.3 KB
/
storage.py
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""The core of RelStorage, a ZODB storage for relational databases.
Stores pickles in the database.
"""
from ZODB import ConflictResolution
from ZODB import POSException
from ZODB.BaseStorage import DataRecord
from ZODB.BaseStorage import TransactionRecord
from ZODB.POSException import POSKeyError
from ZODB.UndoLogCompatible import UndoLogCompatible
from ZODB.utils import p64
from ZODB.utils import u64
from perfmetrics import Metric
from perfmetrics import metricmethod
from persistent.TimeStamp import TimeStamp
from relstorage.blobhelper import BlobHelper
from relstorage.blobhelper import is_blob_record
from relstorage.cache import StorageCache
from relstorage.options import Options
from zope.interface import implements
import ZODB.interfaces
import base64
import cPickle
import logging
import os
import tempfile
import threading
import time
import weakref
try:
from ZODB.interfaces import StorageStopIteration
except ImportError:
class StorageStopIteration(IndexError, StopIteration):
"""A combination of StopIteration and IndexError to provide a
backwards-compatible exception.
"""
_relstorage_interfaces = []
for name in (
'IStorage',
'IMVCCStorage',
'IStorageRestoreable',
'IStorageIteration',
'IStorageUndoable',
'IBlobStorage',
'IBlobStorageRestoreable',
):
if hasattr(ZODB.interfaces, name):
_relstorage_interfaces.append(getattr(ZODB.interfaces, name))
log = logging.getLogger("relstorage")
# Set the RELSTORAGE_ABORT_EARLY environment variable when debugging
# a failure revealed by the ZODB test suite. The test suite often fails
# to call tpc_abort in the event of an error, leading to deadlocks.
# This variable causes RelStorage to abort failed transactions
# early rather than wait for an explicit abort.
abort_early = os.environ.get('RELSTORAGE_ABORT_EARLY')
z64 = '\0' * 8
class RelStorage(
UndoLogCompatible,
ConflictResolution.ConflictResolvingStorage
):
"""Storage to a relational database, based on invalidation polling"""
implements(*_relstorage_interfaces)
_transaction = None # Transaction that is being committed
_tstatus = ' ' # Transaction status, used for copying data
_is_read_only = False
# load_conn and load_cursor are open most of the time.
_load_conn = None
_load_cursor = None
# _load_transaction_open is:
# - an empty string when the load transaction is not open.
# - 'active' when the load connection has begun a read-only transaction.
# - 'idle' when the load transaction has been left open but nothing
# is using it. At those times, the load transaction can be closed
# by another thread (with the protection of the lock).
_load_transaction_open = ''
# store_conn and store_cursor are open during commit,
# but not necessarily open at other times.
_store_conn = None
_store_cursor = None
# _tid is the current transaction ID being committed; generally
# only set after tpc_vote().
_tid = None
# _ltid is the ID of the last transaction committed by this instance.
_ltid = z64
# _prepared_txn is the name of the transaction to commit in the
# second phase.
_prepared_txn = None
# _closed is True after self.close() is called. Since close()
# can be called from another thread, access to self._closed should
# be inside a _lock_acquire()/_lock_release() block.
_closed = False
# _max_stored_oid is the highest OID stored by the current
# transaction
_max_stored_oid = 0
# _max_new_oid is the highest OID provided by new_oid()
_max_new_oid = 0
# _cache, if set, is a StorageCache object.
_cache = None
# _prev_polled_tid contains the tid at the previous poll
_prev_polled_tid = None
# _poll_at is the time to force a poll
_poll_at = 0
# If the blob directory is set, blobhelper is a BlobHelper.
# Otherwise, blobhelper is None.
blobhelper = None
# _txn_check_serials: {oid, serial}; confirms that certain objects
# have not changed at commit.
_txn_check_serials = None
# _batcher: An object that accumulates store operations
# so they can be executed in batch (to minimize latency).
_batcher = None
# _batcher_row_limit: The number of rows to queue before
# calling the database.
_batcher_row_limit = 100
# _stale_error is None most of the time. It's a ReadConflictError
# when the database connection is stale (due to async replication).
_stale_error = None
def __init__(self, adapter, name=None, create=None,
options=None, cache=None, blobhelper=None, **kwoptions):
self._adapter = adapter
if options is None:
options = Options(**kwoptions)
elif kwoptions:
raise TypeError("The RelStorage constructor accepts either "
"an options parameter or keyword arguments, not both")
self._options = options
if not name:
name = options.name
if not name:
name = 'RelStorage: %s' % adapter
self.__name__ = name
self._is_read_only = options.read_only
if create is None:
create = options.create_schema
if create:
self._adapter.schema.prepare()
self.__lock = threading.RLock()
self.__commit_lock = threading.Lock()
self._lock_acquire = self.__lock.acquire
self._lock_release = self.__lock.release
self._commit_lock_acquire = self.__commit_lock.acquire
self._commit_lock_release = self.__commit_lock.release
# _instances is a list of weak references to storage instances bound
# to the same database.
self._instances = []
# _preallocated_oids contains OIDs provided by the database
# but not yet used.
self._preallocated_oids = []
if cache is not None:
self._cache = cache
else:
prefix = options.cache_prefix
if not prefix:
# Use the database name as the cache prefix.
self._open_load_connection()
prefix = adapter.schema.get_database_name(self._load_cursor)
self._drop_load_connection()
prefix = prefix.replace(' ', '_')
self._cache = StorageCache(adapter, options, prefix)
if blobhelper is not None:
self.blobhelper = blobhelper
elif options.blob_dir:
self.blobhelper = BlobHelper(options=options, adapter=adapter)
def new_instance(self):
"""Creates and returns another storage instance.
See ZODB.interfaces.IMVCCStorage.
"""
adapter = self._adapter.new_instance()
cache = self._cache.new_instance()
if self.blobhelper is not None:
blobhelper = self.blobhelper.new_instance(adapter=adapter)
else:
blobhelper = None
other = RelStorage(adapter=adapter, name=self.__name__,
create=False, options=self._options, cache=cache,
blobhelper=blobhelper)
self._instances.append(weakref.ref(other, self._instances.remove))
return other
@property
def fshelper(self):
"""Used in tests"""
return self.blobhelper.fshelper
def _open_load_connection(self):
"""Open the load connection to the database. Return nothing."""
conn, cursor = self._adapter.connmanager.open_for_load()
self._drop_load_connection()
self._load_conn, self._load_cursor = conn, cursor
self._load_transaction_open = 'active'
def _drop_load_connection(self):
"""Unconditionally drop the load connection"""
conn, cursor = self._load_conn, self._load_cursor
self._load_conn, self._load_cursor = None, None
self._adapter.connmanager.close(conn, cursor)
self._load_transaction_open = ''
def _rollback_load_connection(self):
if self._load_conn is not None:
try:
self._load_conn.rollback()
except:
self._drop_load_connection()
raise
self._load_transaction_open = ''
def _restart_load_and_call(self, f, *args, **kw):
"""Restart the load connection and call a function.
The first two function parameters are the load connection and cursor.
"""
if self._load_cursor is None:
need_restart = False
self._open_load_connection()
else:
need_restart = True
try:
if need_restart:
self._adapter.connmanager.restart_load(
self._load_conn, self._load_cursor)
self._load_transaction_open = 'active'
return f(self._load_conn, self._load_cursor, *args, **kw)
except self._adapter.connmanager.disconnected_exceptions, e:
log.warning("Reconnecting load_conn: %s", e)
self._drop_load_connection()
try:
self._open_load_connection()
except:
log.exception("Reconnect failed.")
raise
log.info("Reconnected.")
return f(self._load_conn, self._load_cursor, *args, **kw)
def _open_store_connection(self):
"""Open the store connection to the database. Return nothing."""
conn, cursor = self._adapter.connmanager.open_for_store()
self._drop_store_connection()
self._store_conn, self._store_cursor = conn, cursor
def _drop_store_connection(self):
"""Unconditionally drop the store connection"""
conn, cursor = self._store_conn, self._store_cursor
self._store_conn, self._store_cursor = None, None
self._adapter.connmanager.close(conn, cursor)
def _restart_store(self):
"""Restart the store connection, creating a new connection if needed"""
if self._store_cursor is None:
self._open_store_connection()
return
try:
self._adapter.connmanager.restart_store(
self._store_conn, self._store_cursor)
except self._adapter.connmanager.disconnected_exceptions, e:
log.warning("Reconnecting store_conn: %s", e)
self._drop_store_connection()
try:
self._open_store_connection()
except:
log.exception("Reconnect failed.")
raise
else:
log.info("Reconnected.")
def _with_store(self, f, *args, **kw):
"""Call a function with the store connection and cursor."""
if self._store_cursor is None:
self._open_store_connection()
try:
return f(self._store_conn, self._store_cursor, *args, **kw)
except self._adapter.connmanager.disconnected_exceptions, e:
if self._transaction is not None:
# If transaction commit is in progress, it's too late
# to reconnect.
raise
log.warning("Reconnecting store_conn: %s", e)
self._drop_store_connection()
try:
self._open_store_connection()
except:
log.exception("Reconnect failed.")
raise
log.info("Reconnected.")
return f(self._store_conn, self._store_cursor, *args, **kw)
def zap_all(self, reset_oid=True):
"""Clear all objects and transactions out of the database.
Used by the test suite and the ZODBConvert script.
"""
self._adapter.schema.zap_all(reset_oid=reset_oid)
self._rollback_load_connection()
self._cache.clear()
def release(self):
"""Release database sessions used by this storage instance.
"""
self._lock_acquire()
try:
self._drop_load_connection()
self._drop_store_connection()
finally:
self._lock_release()
def close(self):
"""Close the storage and all instances."""
self._lock_acquire()
try:
self._closed = True
self._drop_load_connection()
self._drop_store_connection()
if self.blobhelper is not None:
self.blobhelper.close()
for wref in self._instances:
instance = wref()
if instance is not None:
instance.close()
finally:
self._lock_release()
def __len__(self):
return self._adapter.stats.get_object_count()
def sortKey(self):
"""Return a string that can be used to sort storage instances.
The key must uniquely identify a storage and must be the same
across multiple instantiations of the same storage.
"""
return self.__name__
def getName(self):
return self.__name__
def getSize(self):
"""Return database size in bytes"""
return self._adapter.stats.get_db_size()
def registerDB(self, db, limit=None):
pass # we don't care
def isReadOnly(self):
return self._is_read_only
def abortVersion(self, src, transaction):
# this method is only here for b/w compat with ZODB 3.7
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
return self._tid, []
def commitVersion(self, src, dest, transaction):
# this method is only here for b/w compat with ZODB 3.7
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
return self._tid, []
def getExtensionMethods(self):
# this method is only here for b/w compat with ZODB 3.7
return {}
def versionEmpty(self, version):
# this method is only here for b/w compat with ZODB 3.7
return 1
def versions(self, max=None):
# this method is only here for b/w compat with ZODB 3.7
return ()
def _log_keyerror(self, oid_int, reason):
"""Log just before raising POSKeyError in load().
KeyErrors in load() are generally not supposed to happen,
so this is a good place to gather information.
"""
cursor = self._load_cursor
adapter = self._adapter
logfunc = log.warning
msg = ["POSKeyError on oid %d: %s" % (oid_int, reason)]
if adapter.keep_history:
tid = adapter.txncontrol.get_tid(cursor)
if not tid:
# This happens when initializing a new database or
# after packing, so it's not a warning.
logfunc = log.debug
msg.append("No previous transactions exist")
else:
msg.append("Current transaction is %d" % tid)
tids = []
try:
rows = adapter.dbiter.iter_object_history(cursor, oid_int)
except KeyError:
# The object has no history, at least from the point of view
# of the current database load connection.
pass
else:
for row in rows:
tids.append(row[0])
if len(tids) >= 10:
break
msg.append("Recent object tids: %s" % repr(tids))
else:
if oid_int == 0:
# This happens when initializing a new database or
# after packing, so it's usually not a warning.
logfunc = log.debug
msg.append("history-free adapter")
logfunc('; '.join(msg))
def _before_load(self):
state = self._load_transaction_open
if not state:
self._restart_load_and_poll()
elif state == 'idle':
self._load_transaction_open = 'active'
@Metric(method=True, rate=0.1)
def load(self, oid, version=''):
if self._stale_error is not None:
raise self._stale_error
oid_int = u64(oid)
cache = self._cache
self._lock_acquire()
try:
self._before_load()
cursor = self._load_cursor
state, tid_int = cache.load(cursor, oid_int)
finally:
self._lock_release()
if tid_int is not None:
if not state:
# This can happen if something attempts to load
# an object whose creation has been undone.
self._log_keyerror(oid_int, "creation has been undone")
raise POSKeyError(oid)
state = str(state or '')
return state, p64(tid_int)
else:
self._log_keyerror(oid_int, "no tid found")
raise POSKeyError(oid)
def getTid(self, oid):
if self._stale_error is not None:
raise self._stale_error
_state, serial = self.load(oid, '')
return serial
getSerial = getTid # ZODB 3.7
def loadEx(self, oid, version=''):
# Since we don't support versions, just tack the empty version
# string onto load's result.
return self.load(oid, version) + ("",)
@Metric(method=True, rate=0.1)
def loadSerial(self, oid, serial):
"""Load a specific revision of an object"""
oid_int = u64(oid)
tid_int = u64(serial)
self._lock_acquire()
try:
self._before_load()
state = self._adapter.mover.load_revision(
self._load_cursor, oid_int, tid_int)
if state is None and self._store_cursor is not None:
# Allow loading data from later transactions
# for conflict resolution.
state = self._adapter.mover.load_revision(
self._store_cursor, oid_int, tid_int)
finally:
self._lock_release()
if state is not None:
state = str(state)
if not state:
raise POSKeyError(oid)
return state
else:
raise POSKeyError(oid)
@Metric(method=True, rate=0.1)
def loadBefore(self, oid, tid):
"""Return the most recent revision of oid before tid committed."""
if self._stale_error is not None:
raise self._stale_error
oid_int = u64(oid)
self._lock_acquire()
try:
if self._store_cursor is not None:
# Allow loading data from later transactions
# for conflict resolution.
cursor = self._store_cursor
else:
self._before_load()
cursor = self._load_cursor
if not self._adapter.mover.exists(cursor, u64(oid)):
raise POSKeyError(oid)
state, start_tid = self._adapter.mover.load_before(
cursor, oid_int, u64(tid))
if start_tid is not None:
if state is None:
# This can happen if something attempts to load
# an object whose creation has been undone, see load()
# This change fixes the test in TransactionalUndoStorage.checkUndoCreationBranch1
# self._log_keyerror doesn't work here, only in certain states.
raise POSKeyError(oid)
end_int = self._adapter.mover.get_object_tid_after(
cursor, oid_int, start_tid)
if end_int is not None:
end = p64(end_int)
else:
end = None
state = str(state)
return state, p64(start_tid), end
else:
return None
finally:
self._lock_release()
@Metric(method=True, rate=0.1)
def store(self, oid, serial, data, version, transaction):
if self._stale_error is not None:
raise self._stale_error
if self._is_read_only:
raise POSException.ReadOnlyError()
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
if version:
raise POSException.Unsupported("Versions aren't supported")
# If self._prepared_txn is not None, that means something is
# attempting to store objects after the vote phase has finished.
# That should not happen, should it?
assert self._prepared_txn is None
adapter = self._adapter
cache = self._cache
cursor = self._store_cursor
assert cursor is not None
oid_int = u64(oid)
if serial:
prev_tid_int = u64(serial)
else:
prev_tid_int = 0
self._lock_acquire()
try:
self._max_stored_oid = max(self._max_stored_oid, oid_int)
# save the data in a temporary table
adapter.mover.store_temp(
cursor, self._batcher, oid_int, prev_tid_int, data)
cache.store_temp(oid_int, data)
return None
finally:
self._lock_release()
def restore(self, oid, serial, data, version, prev_txn, transaction):
# Like store(), but used for importing transactions. See the
# comments in FileStorage.restore(). The prev_txn optimization
# is not used.
if self._stale_error is not None:
raise self._stale_error
if self._is_read_only:
raise POSException.ReadOnlyError()
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
if version:
raise POSException.Unsupported("Versions aren't supported")
assert self._tid is not None
assert self._prepared_txn is None
adapter = self._adapter
cursor = self._store_cursor
assert cursor is not None
oid_int = u64(oid)
tid_int = u64(serial)
self._lock_acquire()
try:
self._max_stored_oid = max(self._max_stored_oid, oid_int)
# save the data. Note that data can be None.
adapter.mover.restore(
cursor, self._batcher, oid_int, tid_int, data)
finally:
self._lock_release()
def checkCurrentSerialInTransaction(self, oid, serial, transaction):
if self._stale_error is not None:
raise self._stale_error
if transaction is not self._transaction:
raise POSException.StorageTransactionError(self, transaction)
_, committed_tid = self.load(oid, '')
if committed_tid != serial:
raise POSException.ReadConflictError(
oid=oid, serials=(committed_tid, serial))
if self._txn_check_serials is None:
self._txn_check_serials = {}
else:
# If this transaction already specified a different serial for
# this oid, the transaction conflicts with itself.
previous_serial = self._txn_check_serials.get(oid, serial)
if previous_serial != serial:
raise POSException.ReadConflictError(
oid=oid, serials=(previous_serial, serial))
self._txn_check_serials[oid] = serial
@metricmethod
def tpc_begin(self, transaction, tid=None, status=' '):
if self._stale_error is not None:
raise self._stale_error
if self._is_read_only:
raise POSException.ReadOnlyError()
self._lock_acquire()
try:
if self._transaction is transaction:
if self._options.strict_tpc:
raise POSException.StorageTransactionError(
"Duplicate tpc_begin calls for same transaction")
return
self._lock_release()
self._commit_lock_acquire()
self._lock_acquire()
self._clear_temp()
self._transaction = transaction
user = str(transaction.user)
desc = str(transaction.description)
ext = transaction._extension
if ext:
ext = cPickle.dumps(ext, 1)
else:
ext = ""
self._ude = user, desc, ext
self._tstatus = status
self._restart_store()
adapter = self._adapter
self._cache.tpc_begin()
self._batcher = self._adapter.mover.make_batcher(
self._store_cursor, self._batcher_row_limit)
if tid is not None:
# hold the commit lock and add the transaction now
cursor = self._store_cursor
packed = (status == 'p')
adapter.locker.hold_commit_lock(cursor, ensure_current=True)
tid_int = u64(tid)
try:
adapter.txncontrol.add_transaction(
cursor, tid_int, user, desc, ext, packed)
except:
self._drop_store_connection()
raise
# else choose the tid later
self._tid = tid
finally:
self._lock_release()
def tpc_transaction(self):
return self._transaction
def _prepare_tid(self):
"""Choose a tid for the current transaction.
This should be done as late in the commit as possible, since
it must hold an exclusive commit lock.
"""
if self._tid is not None:
return
if self._transaction is None:
raise POSException.StorageError("No transaction in progress")
adapter = self._adapter
cursor = self._store_cursor
adapter.locker.hold_commit_lock(cursor, ensure_current=True)
user, desc, ext = self._ude
# Choose a transaction ID.
# Base the transaction ID on the current time,
# but ensure that the tid of this transaction
# is greater than any existing tid.
last_tid = adapter.txncontrol.get_tid(cursor)
now = time.time()
stamp = TimeStamp(*(time.gmtime(now)[:5] + (now % 60,)))
stamp = stamp.laterThan(TimeStamp(p64(last_tid)))
tid = stamp.raw()
tid_int = u64(tid)
adapter.txncontrol.add_transaction(cursor, tid_int, user, desc, ext)
self._tid = tid
def _clear_temp(self):
# Clear all attributes used for transaction commit.
# It is assumed that self._lock_acquire was called before this
# method was called.
self._transaction = None
self._ude = None
self._tid = None
self._prepared_txn = None
self._max_stored_oid = 0
self._batcher = None
self._txn_check_serials = None
self._cache.clear_temp()
blobhelper = self.blobhelper
if blobhelper is not None:
blobhelper.clear_temp()
def _finish_store(self):
"""Move stored objects from the temporary table to final storage.
Returns a list of (oid, tid) to be received by
Connection._handle_serial().
"""
assert self._tid is not None
cursor = self._store_cursor
adapter = self._adapter
cache = self._cache
# Detect conflicting changes.
# Try to resolve the conflicts.
resolved = set() # a set of OIDs
while True:
conflict = adapter.mover.detect_conflict(cursor)
if conflict is None:
break
oid_int, prev_tid_int, serial_int, data = conflict
oid = p64(oid_int)
prev_tid = p64(prev_tid_int)
serial = p64(serial_int)
rdata = self.tryToResolveConflict(oid, prev_tid, serial, data)
if rdata is None:
# unresolvable; kill the whole transaction
raise POSException.ConflictError(
oid=oid, serials=(prev_tid, serial), data=data)
else:
# resolved
data = rdata
self._adapter.mover.replace_temp(
cursor, oid_int, prev_tid_int, data)
resolved.add(oid)
cache.store_temp(oid_int, data)
# Move the new states into the permanent table
tid_int = u64(self._tid)
serials = []
if self.blobhelper is not None:
txn_has_blobs = self.blobhelper.txn_has_blobs
else:
txn_has_blobs = False
oid_ints = adapter.mover.move_from_temp(cursor, tid_int, txn_has_blobs)
for oid_int in oid_ints:
oid = p64(oid_int)
if oid in resolved:
serial = ConflictResolution.ResolvedSerial
else:
serial = self._tid
serials.append((oid, serial))
return serials
@metricmethod
def tpc_vote(self, transaction):
self._lock_acquire()
try:
if transaction is not self._transaction:
if self._options.strict_tpc:
raise POSException.StorageTransactionError(
"tpc_vote called with wrong transaction")
return
try:
return self._vote()
except:
if abort_early:
# abort early to avoid lockups while running the
# somewhat brittle ZODB test suite
self.tpc_abort(transaction)
raise
finally:
self._lock_release()
def _vote(self):
"""Prepare the transaction for final commit."""
# This method initiates a two-phase commit process,
# saving the name of the prepared transaction in self._prepared_txn.
# It is assumed that self._lock_acquire was called before this
# method was called.
if self._prepared_txn is not None:
# the vote phase has already completed
return
cursor = self._store_cursor
assert cursor is not None
conn = self._store_conn
# execute all remaining batch store operations
self._batcher.flush()
# Reserve all OIDs used by this transaction
if self._max_stored_oid > self._max_new_oid:
self._adapter.oidallocator.set_min_oid(
cursor, self._max_stored_oid + 1)
self._prepare_tid()
tid_int = u64(self._tid)
if self._txn_check_serials:
oid_ints = [u64(oid) for oid in self._txn_check_serials.iterkeys()]
current = self._adapter.mover.current_object_tids(cursor, oid_ints)
for oid, expect in self._txn_check_serials.iteritems():
oid_int = u64(oid)
actual = p64(current.get(oid_int, 0))
if actual != expect:
raise POSException.ReadConflictError(
oid=oid, serials=(actual, expect))
serials = self._finish_store()
self._adapter.mover.update_current(cursor, tid_int)
self._prepared_txn = self._adapter.txncontrol.commit_phase1(
conn, cursor, tid_int)
if self.blobhelper is not None:
self.blobhelper.vote(self._tid)
return serials
@metricmethod
def tpc_finish(self, transaction, f=None):
self._lock_acquire()
try:
if transaction is not self._transaction:
if self._options.strict_tpc:
raise POSException.StorageTransactionError(
"tpc_finish called with wrong transaction")
return
try:
try:
if f is not None:
f(self._tid)
u, d, e = self._ude
self._finish(self._tid, u, d, e)
finally:
self._clear_temp()
finally:
self._commit_lock_release()
finally:
self._lock_release()
def _finish(self, tid, user, desc, ext):
"""Commit the transaction."""
# It is assumed that self._lock_acquire was called before this
# method was called.
assert self._tid is not None
self._rollback_load_connection()
txn = self._prepared_txn
assert txn is not None
self._adapter.txncontrol.commit_phase2(
self._store_conn, self._store_cursor, txn)
self._adapter.locker.release_commit_lock(self._store_cursor)
self._cache.after_tpc_finish(self._tid)
# N.B. only set _ltid after the commit succeeds,
# including cache updates.
self._ltid = self._tid
@metricmethod
def tpc_abort(self, transaction):
self._lock_acquire()
try:
if transaction is not self._transaction:
return
try:
try:
self._abort()
finally:
self._clear_temp()
finally:
self._commit_lock_release()
finally:
self._lock_release()
def _abort(self):
# the lock is held here
self._rollback_load_connection()
if self._store_cursor is not None:
self._adapter.txncontrol.abort(
self._store_conn, self._store_cursor, self._prepared_txn)
self._adapter.locker.release_commit_lock(self._store_cursor)
if self.blobhelper is not None:
self.blobhelper.abort()
def lastTransaction(self):
self._lock_acquire()
try:
return self._ltid
finally:
self._lock_release()
def new_oid(self):
if self._stale_error is not None:
raise self._stale_error
if self._is_read_only:
raise POSException.ReadOnlyError()
self._lock_acquire()
try:
if self._preallocated_oids:
oid_int = self._preallocated_oids.pop()
else:
def f(conn, cursor):
return list(self._adapter.oidallocator.new_oids(cursor))
preallocated = self._with_store(f)
preallocated.sort(reverse=True)
oid_int = preallocated.pop()
self._preallocated_oids = preallocated
self._max_new_oid = max(self._max_new_oid, oid_int)
return p64(oid_int)
finally:
self._lock_release()
def cleanup(self):
pass
def supportsVersions(self):
return False
def modifiedInVersion(self, oid):
return ''
def supportsUndo(self):