FileStorage.py 68.4 KB
Newer Older
1 2 3 4 5 6
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
Jim Fulton's avatar
Jim Fulton committed
7
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
8 9 10 11 12 13 14 15 16 17
# 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
#
##############################################################################
"""Storage implementation using a log written to a single file.
"""

from cPickle import Pickler, Unpickler, loads
18 19 20 21
from persistent.TimeStamp import TimeStamp
from struct import pack, unpack
from types import StringType
from zc.lockfile import LockFile
22
from ZODB.FileStorage.format import CorruptedError, CorruptedDataError
23 24 25 26 27 28 29 30 31 32 33
from ZODB.FileStorage.format import FileStorageFormatter, DataHeader
from ZODB.FileStorage.format import TRANS_HDR, TRANS_HDR_LEN
from ZODB.FileStorage.format import TxnHeader, DATA_HDR, DATA_HDR_LEN
from ZODB.FileStorage.fspack import FileStoragePacker
from ZODB.fsIndex import fsIndex
from ZODB import BaseStorage, ConflictResolution, POSException
from ZODB.loglevels import BLATHER
from ZODB.POSException import UndoError, POSKeyError, MultipleUndoErrors
from ZODB.utils import p64, u64, z64

import base64
Jim Fulton's avatar
Jim Fulton committed
34
import BTrees.OOBTree
35
import errno
36
import logging
37 38 39
import os
import sys
import time
40 41 42 43
import ZODB.blob
import ZODB.interfaces
import zope.interface
import ZODB.utils
44 45 46 47 48 49

# Not all platforms have fsync
fsync = getattr(os, "fsync", None)

packed_version = "FS21"

50
logger = logging.getLogger('ZODB.FileStorage')
51 52

def panic(message, *data):
53
    logger.critical(message, *data)
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
    raise CorruptedTransactionError(message)

class FileStorageError(POSException.StorageError):
    pass

class PackError(FileStorageError):
    pass

class FileStorageFormatError(FileStorageError):
    """Invalid file format

    The format of the given file is not valid.
    """

class CorruptedFileStorageError(FileStorageError,
                                POSException.StorageSystemError):
    """Corrupted file storage."""

class CorruptedTransactionError(CorruptedFileStorageError):
    pass

class FileStorageQuotaError(FileStorageError,
                            POSException.StorageSystemError):
    """File storage quota exceeded."""

79 80 81 82
# Intended to be raised only in fspack.py, and ignored here.
class RedundantPackWarning(FileStorageError):
    pass

83 84 85 86 87 88
class TempFormatter(FileStorageFormatter):
    """Helper class used to read formatted FileStorage data."""

    def __init__(self, afile):
        self._file = afile

89 90 91 92 93 94
class FileStorage(
    FileStorageFormatter,
    ZODB.blob.BlobStorageMixin,
    ConflictResolution.ConflictResolvingStorage,
    BaseStorage.BaseStorage,
    ):
95

96 97 98 99 100 101
    zope.interface.implements(
        ZODB.interfaces.IStorage,
        ZODB.interfaces.IStorageRestoreable,
        ZODB.interfaces.IStorageIteration,
        ZODB.interfaces.IStorageUndoable,
        ZODB.interfaces.IStorageCurrentRecordIteration,
102
        ZODB.interfaces.IExternalGC,
103
        )
104

105 106
    # Set True while a pack is in progress; undo is blocked for the duration.
    _pack_is_in_progress = False
107 108

    def __init__(self, file_name, create=False, read_only=False, stop=None,
109 110
                 quota=None, pack_gc=True, pack_keep_old=True, packer=None,
                 blob_dir=None):
111 112

        if read_only:
113
            self._is_read_only = True
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
            if create:
                raise ValueError("can't create a read-only file")
        elif stop is not None:
            raise ValueError("time-travel only supported in read-only mode")

        if stop is None:
            stop='\377'*8

        # Lock the database and set up the temp file.
        if not read_only:
            # Create the lock file
            self._lock_file = LockFile(file_name + '.lock')
            self._tfile = open(file_name + '.tmp', 'w+b')
            self._tfmt = TempFormatter(self._tfile)
        else:
            self._tfile = None

        self._file_name = file_name

133
        self._pack_gc = pack_gc
134
        self.pack_keep_old = pack_keep_old
135 136 137
        if packer is not None:
            self.packer = packer

138 139
        BaseStorage.BaseStorage.__init__(self, file_name)

140 141
        index, tindex = self._newIndexes()
        self._initIndex(index, tindex)
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

        # Now open the file

        self._file = None
        if not create:
            try:
                self._file = open(file_name, read_only and 'rb' or 'r+b')
            except IOError, exc:
                if exc.errno == errno.EFBIG:
                    # The file is too big to open.  Fail visibly.
                    raise
                if exc.errno == errno.ENOENT:
                    # The file doesn't exist.  Create it.
                    create = 1
                # If something else went wrong, it's hard to guess
                # what the problem was.  If the file does not exist,
                # create it.  Otherwise, fail.
                if os.path.exists(file_name):
                    raise
                else:
                    create = 1

        if self._file is None and create:
            if os.path.exists(file_name):
                os.remove(file_name)
            self._file = open(file_name, 'w+b')
            self._file.write(packed_version)

        r = self._restore_index()
        if r is not None:
            self._used_index = 1 # Marker for testing
173
            index, start, ltid = r
174

175
            self._initIndex(index, tindex)
176
            self._pos, self._oid, tid = read_index(
177
                self._file, file_name, index, tindex, stop,
178
                ltid=ltid, start=start, read_only=read_only,
179 180 181 182
                )
        else:
            self._used_index = 0 # Marker for testing
            self._pos, self._oid, tid = read_index(
183
                self._file, file_name, index, tindex, stop,
184 185 186 187 188 189 190 191 192 193 194 195 196 197
                read_only=read_only,
                )
            self._save_index()

        self._ltid = tid

        # self._pos should always point just past the last
        # transaction.  During 2PC, data is written after _pos.
        # invariant is restored at tpc_abort() or tpc_finish().

        self._ts = tid = TimeStamp(tid)
        t = time.time()
        t = TimeStamp(*time.gmtime(t)[:5] + (t % 60,))
        if tid > t:
Tim Peters's avatar
Tim Peters committed
198 199 200 201 202 203
            seconds = tid.timeTime() - t.timeTime()
            complainer = logger.warning
            if seconds > 30 * 60:   # 30 minutes -- way screwed up
                complainer = logger.critical
            complainer("%s Database records %d seconds in the future",
                       file_name, seconds)
204 205 206

        self._quota = quota

207
        if blob_dir:
208 209 210
            self.blob_dir = os.path.abspath(blob_dir)
            if create and os.path.exists(self.blob_dir):
                ZODB.blob.remove_committed_dir(self.blob_dir)
211

212 213 214 215
            self._blob_init(blob_dir)
            zope.interface.alsoProvides(self,
                                        ZODB.interfaces.IBlobStorageRestoreable)
        else:
216
            self.blob_dir = None
217 218 219 220 221 222 223 224
            self._blob_init_no_blobs()

    def copyTransactionsFrom(self, other):
        if self.blob_dir:
            return ZODB.blob.BlobStorageMixin.copyTransactionsFrom(self, other)
        else:
            return BaseStorage.BaseStorage.copyTransactionsFrom(self, other)

225
    def _initIndex(self, index, tindex):
226 227 228 229 230 231 232 233 234
        self._index=index
        self._tindex=tindex
        self._index_get=index.get

    def __len__(self):
        return len(self._index)

    def _newIndexes(self):
        # hook to use something other than builtin dict
235
        return fsIndex(), {}
236 237 238 239 240

    _saved = 0
    def _save_index(self):
        """Write the database index to a file to support quick startup."""

241 242 243
        if self._is_read_only:
            return

244 245 246 247 248 249
        index_name = self.__name__ + '.index'
        tmp_name = index_name + '.index_tmp'

        f=open(tmp_name,'wb')
        p=Pickler(f,1)

Jim Fulton's avatar
Jim Fulton committed
250 251 252 253 254 255 256 257 258 259
        # Pickle the index buckets first to avoid deep recursion:
        buckets = []
        bucket = self._index._data._firstbucket
        while bucket is not None:
            buckets.append(bucket)
            bucket = bucket._next
        buckets.reverse()

        info=BTrees.OOBTree.Bucket(dict(
            _buckets=buckets, index=self._index, pos=self._pos))
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

        p.dump(info)
        f.flush()
        f.close()

        try:
            try:
                os.remove(index_name)
            except OSError:
                pass
            os.rename(tmp_name, index_name)
        except: pass

        self._saved += 1

    def _clear_index(self):
        index_name = self.__name__ + '.index'
        if os.path.exists(index_name):
            try:
                os.remove(index_name)
            except OSError:
                pass

    def _sane(self, index, pos):
        """Sanity check saved index data by reading the last undone trans

        Basically, we read the last not undone transaction and
        check to see that the included records are consistent
        with the index.  Any invalid record records or inconsistent
        object positions cause zero to be returned.
        """
        r = self._check_sanity(index, pos)
        if not r:
293
            logger.warning("Ignoring index for %s", self._file_name)
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
        return r

    def _check_sanity(self, index, pos):

        if pos < 100:
            return 0 # insane
        self._file.seek(0, 2)
        if self._file.tell() < pos:
            return 0 # insane
        ltid = None

        max_checked = 5
        checked = 0

        while checked < max_checked:
            self._file.seek(pos - 8)
            rstl = self._file.read(8)
            tl = u64(rstl)
            pos = pos - tl - 8
            if pos < 4:
                return 0 # insane
            h = self._read_txn_header(pos)
            if not ltid:
                ltid = h.tid
            if h.tlen != tl:
                return 0 # inconsistent lengths
            if h.status == 'u':
                continue # undone trans, search back
            if h.status not in ' p':
                return 0 # insane
            if tl < h.headerlen():
                return 0 # insane
            tend = pos + tl
            opos = pos + h.headerlen()
            if opos == tend:
                continue # empty trans

            while opos < tend and checked < max_checked:
                # Read the data records for this transaction
                h = self._read_data_header(opos)

                if opos + h.recordlen() > tend or h.tloc != pos:
                    return 0

                if index.get(h.oid, 0) != opos:
                    return 0 # insane

                checked += 1

                opos = opos + h.recordlen()

            return ltid

    def _restore_index(self):
        """Load database index to support quick startup."""
349
        # Returns (index, pos, tid), or None in case of error.
350 351 352 353 354
        # The index returned is always an instance of fsIndex.  If the
        # index cached in the file is a Python dict, it's converted to
        # fsIndex here, and, if we're not in read-only mode, the .index
        # file is rewritten with the converted fsIndex so we don't need to
        # convert it again the next time.
355 356 357
        file_name=self.__name__
        index_name=file_name+'.index'

358 359 360 361
        try:
            f = open(index_name, 'rb')
        except:
            return None
362 363 364 365 366 367 368

        p=Unpickler(f)

        try:
            info=p.load()
        except:
            exc, err = sys.exc_info()[:2]
369
            logger.warning("Failed to load database index: %s: %s", exc, err)
370 371 372
            return None
        index = info.get('index')
        pos = info.get('pos')
373
        if index is None or pos is None:
374 375 376
            return None
        pos = long(pos)

377 378 379
        if (isinstance(index, dict) or
                (isinstance(index, fsIndex) and
                 isinstance(index._data, dict))):
380
            # Convert dictionary indexes to fsIndexes *or* convert fsIndexes
381 382
            # which have a dict `_data` attribute to a new fsIndex (newer
            # fsIndexes have an OOBTree as `_data`).
383
            newindex = fsIndex()
384 385 386 387
            newindex.update(index)
            index = newindex
            if not self._is_read_only:
                # Save the converted index.
388 389
                f = open(index_name, 'wb')
                p = Pickler(f, 1)
390
                info['index'] = index
391 392
                p.dump(info)
                f.close()
393
                # Now call this method again to get the new data.
394 395 396 397 398 399
                return self._restore_index()

        tid = self._sane(index, pos)
        if not tid:
            return None

400
        return index, pos, tid
401 402 403 404 405 406 407 408 409 410 411

    def close(self):
        self._file.close()
        if hasattr(self,'_lock_file'):
            self._lock_file.close()
        if self._tfile:
            self._tfile.close()
        try:
            self._save_index()
        except:
            # Log the error and continue
412
            logger.error("Error saving index on close()", exc_info=True)
413 414 415 416 417 418 419 420 421 422 423 424

    def getSize(self):
        return self._pos

    def _lookup_pos(self, oid):
        try:
            return self._index[oid]
        except KeyError:
            raise POSKeyError(oid)
        except TypeError:
            raise TypeError("invalid oid %r" % (oid,))

425
    def load(self, oid, version=''):
426
        """Return pickle data and serial number."""
427 428
        assert not version

429 430 431 432 433
        self._lock_acquire()
        try:
            pos = self._lookup_pos(oid)
            h = self._read_data_header(pos, oid)
            if h.plen:
434 435
                data = self._file.read(h.plen)
                return data, h.tid
436
            elif h.back:
437
                # Get the data from the backpointer, but tid from
438
                # current txn.
439 440
                data = self._loadBack_impl(oid, h.back)[0]
                return data, h.tid
441 442
            else:
                raise POSKeyError(oid)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        finally:
            self._lock_release()

    def loadSerial(self, oid, serial):
        self._lock_acquire()
        try:
            pos = self._lookup_pos(oid)
            while 1:
                h = self._read_data_header(pos, oid)
                if h.tid == serial:
                    break
                pos = h.prev
                if not pos:
                    raise POSKeyError(oid)
            if h.plen:
                return self._file.read(h.plen)
            else:
                return self._loadBack_impl(oid, h.back)[0]
        finally:
            self._lock_release()

    def loadBefore(self, oid, tid):
465 466 467 468 469 470 471 472 473 474 475 476
        self._lock_acquire()
        try:
            pos = self._lookup_pos(oid)
            end_tid = None
            while True:
                h = self._read_data_header(pos, oid)
                if h.tid < tid:
                    break

                pos = h.prev
                end_tid = h.tid
                if not pos:
477
                    return None
478 479 480 481 482 483 484 485 486

            if h.back:
                data, _, _, _ = self._loadBack_impl(oid, h.back)
                return data, h.tid, end_tid
            else:
                return self._file.read(h.plen), h.tid, end_tid

        finally:
            self._lock_release()
487

488
    def store(self, oid, oldserial, data, version, transaction):
489 490 491 492
        if self._is_read_only:
            raise POSException.ReadOnlyError()
        if transaction is not self._transaction:
            raise POSException.StorageTransactionError(self, transaction)
493
        assert not version
494

495 496
        self._lock_acquire()
        try:
497 498
            if oid > self._oid:
                self.set_max_oid(oid)
499
            old = self._index_get(oid, 0)
500
            committed_tid = None
501 502
            pnv = None
            if old:
503 504
                h = self._read_data_header(old, oid)
                committed_tid = h.tid
505

506 507
                if oldserial != committed_tid:
                    rdata = self.tryToResolveConflict(oid, committed_tid,
508
                                                     oldserial, data)
509 510
                    if rdata is None:
                        raise POSException.ConflictError(
511 512
                            oid=oid, serials=(committed_tid, oldserial),
                            data=data)
513 514 515 516 517 518
                    else:
                        data = rdata

            pos = self._pos
            here = pos + self._tfile.tell() + self._thl
            self._tindex[oid] = here
519 520
            new = DataHeader(oid, self._tid, old, pos, 0, len(data))

521 522 523 524 525 526 527 528
            self._tfile.write(new.asString())
            self._tfile.write(data)

            # Check quota
            if self._quota is not None and here > self._quota:
                raise FileStorageQuotaError(
                    "The storage quota has been exceeded.")

529
            if old and oldserial != committed_tid:
530 531 532 533 534 535
                return ConflictResolution.ResolvedSerial
            else:
                return self._tid

        finally:
            self._lock_release()
536 537 538 539 540 541

    def deleteObject(self, oid, oldserial, transaction):
        if self._is_read_only:
            raise POSException.ReadOnlyError()
        if transaction is not self._transaction:
            raise POSException.StorageTransactionError(self, transaction)
542

543 544 545 546 547 548 549 550 551 552 553
        self._lock_acquire()
        try:
            old = self._index_get(oid, 0)
            if not old:
                raise POSException.POSKeyError(oid)
            h = self._read_data_header(old, oid)
            committed_tid = h.tid

            if oldserial != committed_tid:
                raise POSException.ConflictError(
                    oid=oid, serials=(committed_tid, oldserial))
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568
            pos = self._pos
            here = pos + self._tfile.tell() + self._thl
            self._tindex[oid] = here
            new = DataHeader(oid, self._tid, old, pos, 0, 0)
            self._tfile.write(new.asString())
            self._tfile.write(z64)

            # Check quota
            if self._quota is not None and here > self._quota:
                raise FileStorageQuotaError(
                    "The storage quota has been exceeded.")

        finally:
            self._lock_release()
569 570

    def _data_find(self, tpos, oid, data):
571 572 573 574 575 576 577 578 579
        # Return backpointer for oid.  Must call with the lock held.
        # This is a file offset to oid's data record if found, else 0.
        # The data records in the transaction at tpos are searched for oid.
        # If a data record for oid isn't found, returns 0.
        # Else if oid's data record contains a backpointer, that
        # backpointer is returned.
        # Else oid's data record contains the data, and the file offset of
        # oid's data record is returned.  This data record should contain
        # a pickle identical to the 'data' argument.
580 581 582 583

        # Unclear:  If the length of the stored data doesn't match len(data),
        # an exception is raised.  If the lengths match but the data isn't
        # the same, 0 is returned.  Why the discrepancy?
584 585
        self._file.seek(tpos)
        h = self._file.read(TRANS_HDR_LEN)
Dmitry Vasiliev's avatar
Dmitry Vasiliev committed
586
        tid, tl, status, ul, dl, el = unpack(TRANS_HDR, h)
587 588 589 590 591 592 593 594 595 596 597 598 599
        self._file.read(ul + dl + el)
        tend = tpos + tl + 8
        pos = self._file.tell()
        while pos < tend:
            h = self._read_data_header(pos)
            if h.oid == oid:
                # Make sure this looks like the right data record
                if h.plen == 0:
                    # This is also a backpointer.  Gotta trust it.
                    return pos
                if h.plen != len(data):
                    # The expected data doesn't match what's in the
                    # backpointer.  Something is wrong.
600 601
                    logger.error("Mismatch between data and"
                                 " backpointer at %d", pos)
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
                    return 0
                _data = self._file.read(h.plen)
                if data != _data:
                    return 0
                return pos
            pos += h.recordlen()
            self._file.seek(pos)
        return 0

    def restore(self, oid, serial, data, version, prev_txn, transaction):
        # A lot like store() but without all the consistency checks.  This
        # should only be used when we /know/ the data is good, hence the
        # method name.  While the signature looks like store() there are some
        # differences:
        #
        # - serial is the serial number of /this/ revision, not of the
        #   previous revision.  It is used instead of self._tid, which is
        #   ignored.
        #
        # - Nothing is returned
        #
        # - data can be None, which indicates a George Bailey object
        #   (i.e. one who's creation has been transactionally undone).
        #
        # prev_txn is a backpointer.  In the original database, it's possible
        # that the data was actually living in a previous transaction.  This
        # can happen for transactional undo and other operations, and is used
        # as a space saving optimization.  Under some circumstances the
        # prev_txn may not actually exist in the target database (i.e. self)
        # for example, if it's been packed away.  In that case, the prev_txn
        # should be considered just a hint, and is ignored if the transaction
        # doesn't exist.
        if self._is_read_only:
            raise POSException.ReadOnlyError()
        if transaction is not self._transaction:
            raise POSException.StorageTransactionError(self, transaction)
638 639
        if version:
            raise TypeError("Versions are no-longer supported")
640 641 642

        self._lock_acquire()
        try:
643 644
            if oid > self._oid:
                self.set_max_oid(oid)
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
            prev_pos = 0
            if prev_txn is not None:
                prev_txn_pos = self._txn_find(prev_txn, 0)
                if prev_txn_pos:
                    prev_pos = self._data_find(prev_txn_pos, oid, data)
            old = self._index_get(oid, 0)
            # Calculate the file position in the temporary file
            here = self._pos + self._tfile.tell() + self._thl
            # And update the temp file index
            self._tindex[oid] = here
            if prev_pos:
                # If there is a valid prev_pos, don't write data.
                data = None
            if data is None:
                dlen = 0
            else:
                dlen = len(data)

            # Write the recovery data record
664
            new = DataHeader(oid, serial, old, self._pos, 0, dlen)
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

            self._tfile.write(new.asString())

            # Finally, write the data or a backpointer.
            if data is None:
                if prev_pos:
                    self._tfile.write(p64(prev_pos))
                else:
                    # Write a zero backpointer, which indicates an
                    # un-creation transaction.
                    self._tfile.write(z64)
            else:
                self._tfile.write(data)
        finally:
            self._lock_release()

    def supportsUndo(self):
        return 1

    def _clear_temp(self):
        self._tindex.clear()
        if self._tfile is not None:
            self._tfile.seek(0)

    def _begin(self, tid, u, d, e):
        self._nextpos = 0
        self._thl = TRANS_HDR_LEN + len(u) + len(d) + len(e)
        if self._thl > 65535:
            # one of u, d, or e may be > 65535
            # We have to check lengths here because struct.pack
            # doesn't raise an exception on overflow!
            if len(u) > 65535:
                raise FileStorageError('user name too long')
            if len(d) > 65535:
                raise FileStorageError('description too long')
            if len(e) > 65535:
                raise FileStorageError('too much extension data')


    def tpc_vote(self, transaction):
        self._lock_acquire()
        try:
            if transaction is not self._transaction:
                return
            dlen = self._tfile.tell()
            if not dlen:
                return # No data in this trans
            self._tfile.seek(0)
            user, descr, ext = self._ude

            self._file.seek(self._pos)
            tl = self._thl + dlen

            try:
                h = TxnHeader(self._tid, tl, "c", len(user),
                              len(descr), len(ext))
                h.user = user
                h.descr = descr
                h.ext = ext
                self._file.write(h.asString())
725
                ZODB.utils.cp(self._tfile, self._file, dlen)
726 727 728
                self._file.write(p64(tl))
                self._file.flush()
            except:
729
                # Hm, an error occurred writing out the data. Maybe the
730 731 732 733 734 735 736 737
                # disk is full. We don't want any turd at the end.
                self._file.truncate(self._pos)
                raise
            self._nextpos = self._pos + (tl + 8)
        finally:
            self._lock_release()

    def _finish(self, tid, u, d, e):
738 739 740
        # If self._nextpos is 0, then the transaction didn't write any
        # data, so we don't bother writing anything to the file.
        if self._nextpos:
741
            # Clear the checkpoint flag
742 743 744 745 746 747 748 749 750 751 752 753
            self._file.seek(self._pos+16)
            self._file.write(self._tstatus)
            try:
                # At this point, we may have committed the data to disk.
                # If we fail from here, we're in bad shape.
                self._finish_finish(tid)
            except:
                # Ouch.  This is bad.  Let's try to get back to where we were
                # and then roll over and die
                logger.critical("Failure in _finish. Closing.", exc_info=True)
                self.close()
                raise
754

755 756 757
    def _finish_finish(self, tid):
        # This is a separate method to allow tests to replace it with
        # something broken. :)
758

759 760 761
        self._file.flush()
        if fsync is not None:
            fsync(self._file.fileno())
762

763 764
        self._pos = self._nextpos
        self._index.update(self._tindex)
765
        self._ltid = tid
766
        self._blob_tpc_finish()
767 768 769 770 771

    def _abort(self):
        if self._nextpos:
            self._file.truncate(self._pos)
            self._nextpos=0
772
            self._blob_tpc_abort()
773 774

    def _undoDataInfo(self, oid, pos, tpos):
775 776
        """Return the tid, data pointer, and data for the oid record at pos
        """
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
        if tpos:
            pos = tpos - self._pos - self._thl
            tpos = self._tfile.tell()
            h = self._tfmt._read_data_header(pos, oid)
            afile = self._tfile
        else:
            h = self._read_data_header(pos, oid)
            afile = self._file
        if h.oid != oid:
            raise UndoError("Invalid undo transaction id", oid)

        if h.plen:
            data = afile.read(h.plen)
        else:
            data = ''
            pos = h.back

        if tpos:
            self._tfile.seek(tpos) # Restore temp file to end

797
        return h.tid, pos, data
798 799 800 801

    def getTid(self, oid):
        self._lock_acquire()
        try:
802 803 804 805 806 807
            pos = self._lookup_pos(oid)
            h = self._read_data_header(pos, oid)
            if h.plen == 0 and h.back == 0:
                # Undone creation
                raise POSKeyError(oid)
            return h.tid
808 809 810
        finally:
            self._lock_release()

811
    def _transactionalUndoRecord(self, oid, pos, tid, pre):
812 813 814 815 816
        """Get the undo information for a data record

        'pos' points to the data header for 'oid' in the transaction
        being undone.  'tid' refers to the transaction being undone.
        'pre' is the 'prev' field of the same data header.
817

818 819 820 821
        Return a 3-tuple consisting of a pickle, data pointer, and
        current position.  If the pickle is true, then the data
        pointer must be 0, but the pickle can be empty *and* the
        pointer 0.
822 823 824 825 826 827 828 829 830 831 832 833
        """

        copy = 1 # Can we just copy a data pointer

        # First check if it is possible to undo this record.
        tpos = self._tindex.get(oid, 0)
        ipos = self._index.get(oid, 0)
        tipos = tpos or ipos

        if tipos != pos:
            # Eek, a later transaction modified the data, but,
            # maybe it is pointing at the same data we are.
834
            ctid, cdataptr, cdata = self._undoDataInfo(oid, ipos, tpos)
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
            if cdataptr != pos:
                # We aren't sure if we are talking about the same data
                try:
                    if (
                        # The current record wrote a new pickle
                        cdataptr == tipos
                        or
                        # Backpointers are different
                        self._loadBackPOS(oid, pos) !=
                        self._loadBackPOS(oid, cdataptr)
                        ):
                        if pre and not tpos:
                            copy = 0 # we'll try to do conflict resolution
                        else:
                            # We bail if:
                            # - We don't have a previous record, which should
                            #   be impossible.
                            raise UndoError("no previous record", oid)
                except KeyError:
                    # LoadBack gave us a key error. Bail.
                    raise UndoError("_loadBack() failed", oid)

        # Return the data that should be written in the undo record.
        if not pre:
            # There is no previous revision, because the object creation
            # is being undone.
862
            return "", 0, ipos
863 864 865

        if copy:
            # we can just copy our previous-record pointer forward
866
            return "", pre, ipos
867 868 869 870 871 872 873 874 875

        try:
            bdata = self._loadBack_impl(oid, pre)[0]
        except KeyError:
            # couldn't find oid; what's the real explanation for this?
            raise UndoError("_loadBack() failed for %s", oid)
        data = self.tryToResolveConflict(oid, ctid, tid, bdata, cdata)

        if data:
876
            return data, 0, ipos
877 878 879 880 881 882 883 884 885 886

        raise UndoError("Some data were modified by a later transaction", oid)

    # undoLog() returns a description dict that includes an id entry.
    # The id is opaque to the client, but contains the transaction id.
    # The transactionalUndo() implementation does a simple linear
    # search through the file (from the end) to find the transaction.

    def undoLog(self, first=0, last=-20, filter=None):
        if last < 0:
887
            # -last is supposed to be the max # of transactions.  Convert to
888 889
            # a positive index.  Should have x - first = -last, which
            # means x = first - last.  This is spelled out here because
890
            # the normalization code was incorrect for years (used +1
891 892
            # instead -- off by 1), until ZODB 3.4.
            last = first - last
893 894
        self._lock_acquire()
        try:
895
            if self._pack_is_in_progress:
896 897
                raise UndoError(
                    'Undo is currently disabled for database maintenance.<p>')
898
            us = UndoSearch(self._file, self._pos, first, last, filter)
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
            while not us.finished():
                # Hold lock for batches of 20 searches, so default search
                # parameters will finish without letting another thread run.
                for i in range(20):
                    if us.finished():
                        break
                    us.search()
                # Give another thread a chance, so that a long undoLog()
                # operation doesn't block all other activity.
                self._lock_release()
                self._lock_acquire()
            return us.results
        finally:
            self._lock_release()

914
    def undo(self, transaction_id, transaction):
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
        """Undo a transaction, given by transaction_id.

        Do so by writing new data that reverses the action taken by
        the transaction.

        Usually, we can get by with just copying a data pointer, by
        writing a file position rather than a pickle. Sometimes, we
        may do conflict resolution, in which case we actually copy
        new data that results from resolution.
        """

        if self._is_read_only:
            raise POSException.ReadOnlyError()
        if transaction is not self._transaction:
            raise POSException.StorageTransactionError(self, transaction)

        self._lock_acquire()
        try:
            return self._txn_undo(transaction_id)
        finally:
            self._lock_release()

    def _txn_undo(self, transaction_id):
        # Find the right transaction to undo and call _txn_undo_write().
        tid = base64.decodestring(transaction_id + '\n')
        assert len(tid) == 8
        tpos = self._txn_find(tid, 1)
        tindex = self._txn_undo_write(tpos)
        self._tindex.update(tindex)
        return self._tid, tindex.keys()

    def _txn_find(self, tid, stop_at_pack):
        pos = self._pos
        while pos > 39:
            self._file.seek(pos - 8)
            pos = pos - u64(self._file.read(8)) - 8
            self._file.seek(pos)
            h = self._file.read(TRANS_HDR_LEN)
            _tid = h[:8]
            if _tid == tid:
                return pos
            if stop_at_pack:
                # check the status field of the transaction header
958
                if h[16] == 'p':
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
                    break
        raise UndoError("Invalid transaction id")

    def _txn_undo_write(self, tpos):
        # a helper function to write the data records for transactional undo

        otloc = self._pos
        here = self._pos + self._tfile.tell() + self._thl
        base = here - self._tfile.tell()
        # Let's move the file pointer back to the start of the txn record.
        th = self._read_txn_header(tpos)
        if th.status != " ":
            raise UndoError('non-undoable transaction')
        tend = tpos + th.tlen
        pos = tpos + th.headerlen()
        tindex = {}

        # keep track of failures, cause we may succeed later
        failures = {}
        # Read the data records for this transaction
        while pos < tend:
            h = self._read_data_header(pos)
            if h.oid in failures:
                del failures[h.oid] # second chance!

            assert base + self._tfile.tell() == here, (here, base,
                                                       self._tfile.tell())
            try:
987 988
                p, prev, ipos = self._transactionalUndoRecord(
                    h.oid, pos, h.tid, h.prev)
989 990 991 992
            except UndoError, v:
                # Don't fail right away. We may be redeemed later!
                failures[h.oid] = v
            else:
993 994

                if self.blob_dir and not p and prev:
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
                    try:
                        up, userial = self._loadBackTxn(h.oid, prev)
                    except ZODB.POSException.POSKeyError:
                        pass # It was removed, so no need to copy data
                    else:
                        if ZODB.blob.is_blob_record(up):
                            # We're undoing a blob modification operation.
                            # We have to copy the blob data
                            tmp = ZODB.utils.mktemp(dir=self.fshelper.temp_dir)
                            ZODB.utils.cp(
                                self.openCommittedBlobFile(h.oid, userial),
                                open(tmp, 'wb'))
                            self._blob_storeblob(h.oid, self._tid, tmp)
1008

1009
                new = DataHeader(h.oid, self._tid, ipos, otloc, 0, len(p))
1010

1011 1012
                # TODO:  This seek shouldn't be necessary, but some other
                # bit of code is messing with the file pointer.
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                assert self._tfile.tell() == here - base, (here, base,
                                                           self._tfile.tell())
                self._tfile.write(new.asString())
                if p:
                    self._tfile.write(p)
                else:
                    self._tfile.write(p64(prev))
                tindex[h.oid] = here
                here += new.recordlen()

            pos += h.recordlen()
            if pos > tend:
                raise UndoError("non-undoable transaction")

        if failures:
            raise MultipleUndoErrors(failures.items())

        return tindex

1032
    def history(self, oid, size=1, filter=None):
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        self._lock_acquire()
        try:
            r = []
            pos = self._lookup_pos(oid)

            while 1:
                if len(r) >= size: return r
                h = self._read_data_header(pos)

                th = self._read_txn_header(h.tloc)
1043 1044
                if th.ext:
                    d = loads(th.ext)
1045 1046 1047 1048
                else:
                    d = {}

                d.update({"time": TimeStamp(h.tid).timeTime(),
1049 1050
                          "user_name": th.user,
                          "description": th.descr,
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                          "tid": h.tid,
                          "size": h.plen,
                          })

                if filter is None or filter(d):
                    r.append(d)

                if h.prev:
                    pos = h.prev
                else:
                    return r
        finally:
            self._lock_release()

    def _redundant_pack(self, file, pos):
        assert pos > 8, pos
        file.seek(pos - 8)
        p = u64(file.read(8))
        file.seek(pos - p + 8)
        return file.read(1) not in ' u'

1072 1073 1074 1075 1076
    @staticmethod
    def packer(storage, referencesf, stop, gc):
        # Our default packer is built around the original packer.  We
        # simply adapt the old interface to the new.  We don't really
        # want to invest much in the old packer, at least for now.
1077
        assert referencesf is not None
1078
        p = FileStoragePacker(storage, referencesf, stop, gc)
1079 1080 1081 1082 1083 1084
        opos = p.pack()
        if opos is None:
            return None
        return opos, p.index

    def pack(self, t, referencesf, gc=None):
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        """Copy data from the current database file to a packed file

        Non-current records from transactions with time-stamp strings less
        than packtss are ommitted. As are all undone records.

        Also, data back pointers that point before packtss are resolved and
        the associated data are copied, since the old records are not copied.
        """
        if self._is_read_only:
            raise POSException.ReadOnlyError()

        stop=`TimeStamp(*time.gmtime(t)[:5]+(t%60,))`
1097
        if stop==z64: raise FileStorageError('Invalid pack time')
1098 1099 1100 1101 1102 1103 1104

        # If the storage is empty, there's nothing to do.
        if not self._index:
            return

        self._lock_acquire()
        try:
1105
            if self._pack_is_in_progress:
1106
                raise FileStorageError('Already packing')
1107
            self._pack_is_in_progress = True
1108 1109 1110
        finally:
            self._lock_release()

1111 1112 1113
        if gc is None:
            gc = self._pack_gc

1114 1115 1116 1117 1118 1119
        oldpath = self._file_name + ".old"
        if os.path.exists(oldpath):
            os.remove(oldpath)
        if self.blob_dir and os.path.exists(self.blob_dir + ".old"):
            ZODB.blob.remove_committed_dir(self.blob_dir + ".old")

1120 1121
        cleanup = []

1122
        have_commit_lock = False
1123
        try:
1124
            pack_result = None
1125
            try:
1126
                pack_result = self.packer(self, referencesf, stop, gc)
1127
            except RedundantPackWarning, detail:
1128
                logger.info(str(detail))
1129
            if pack_result is None:
1130
                return
1131 1132
            have_commit_lock = True
            opos, index = pack_result
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
            self._lock_acquire()
            try:
                self._file.close()
                try:
                    os.rename(self._file_name, oldpath)
                except Exception:
                    self._file = open(self._file_name, 'r+b')
                    raise

                # OK, we're beyond the point of no return
                os.rename(self._file_name + '.pack', self._file_name)
                self._file = open(self._file_name, 'r+b')
1145
                self._initIndex(index, self._tindex)
1146 1147 1148
                self._pos = opos
            finally:
                self._lock_release()
1149 1150 1151 1152 1153 1154 1155 1156 1157

            # We're basically done.  Now we need to deal with removed
            # blobs and removing the .old file (see further down).

            if self.blob_dir:
                self._commit_lock_release()
                have_commit_lock = False
                self._remove_blob_files_tagged_for_removal_during_pack()

1158
        finally:
1159
            if have_commit_lock:
1160 1161
                self._commit_lock_release()
            self._lock_acquire()
1162
            self._pack_is_in_progress = False
1163 1164
            self._lock_release()

1165 1166 1167 1168 1169 1170 1171 1172
        if not self.pack_keep_old:
            os.remove(oldpath)

        self._lock_acquire()
        try:
            self._save_index()
        finally:
            self._lock_release()
1173 1174

    def _remove_blob_files_tagged_for_removal_during_pack(self):
1175 1176 1177
        lblob_dir = len(self.blob_dir)
        fshelper = self.fshelper
        old = self.blob_dir+'.old'
1178
        link_or_copy = ZODB.blob.link_or_copy
1179 1180

        # Helper to clean up dirs left empty after moving things to old
1181
        def maybe_remove_empty_dir_containing(path, level=0):
1182
            path = os.path.dirname(path)
1183
            if len(path) <= lblob_dir or os.listdir(path):
1184
                return
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

            # Path points to an empty dir.  There may be a race.  We
            # might have just removed the dir for an oid (or a parent
            # dir) and while we're cleaning up it's parent, another
            # thread is adding a new entry to it.

            # We don't have to worry about level 0, as this is just a
            # directory containing an object's revisions. If it is
            # enmpty, the object must have been garbage.

            # If the level is 1 or higher, we need to be more
            # careful.  We'll get the storage lock and double check
            # that the dir is still empty before removing it.

            removed = False
            if level:
                self._lock_acquire()
            try:
                if not os.listdir(path):
                    os.rmdir(path)
                    removed = True
            finally:
                if level:
                    self._lock_release()

            if removed:
                maybe_remove_empty_dir_containing(path, level+1)

1213

1214 1215 1216 1217 1218 1219
        if self.pack_keep_old:
            # Helpers that move oid dir or revision file to the old dir.
            os.mkdir(old, 0777)
            link_or_copy(os.path.join(self.blob_dir, '.layout'),
                         os.path.join(old, '.layout'))
            def handle_file(path):
1220 1221
                newpath = old+path[lblob_dir:]
                dest = os.path.dirname(newpath)
1222 1223
                if not os.path.exists(dest):
                    os.makedirs(dest, 0700)
1224
                os.rename(path, newpath)
1225 1226 1227 1228 1229
            handle_dir = handle_file
        else:
            # Helpers that remove an oid dir or revision file.
            handle_file = ZODB.blob.remove_committed
            handle_dir = ZODB.blob.remove_committed_dir
1230

1231
        # Fist step: move or remove oids or revisions
1232 1233 1234 1235 1236 1237 1238 1239 1240
        for line in open(os.path.join(self.blob_dir, '.removed')):
            line = line.strip().decode('hex')

            if len(line) == 8:
                # oid is garbage, re/move dir
                path = fshelper.getPathForOID(line)
                if not os.path.exists(path):
                    # Hm, already gone. Odd.
                    continue
1241
                handle_dir(path)
1242
                maybe_remove_empty_dir_containing(path, 1)
1243
                continue
1244

1245 1246
            if len(line) != 16:
                raise ValueError("Bad record in ", self.blob_dir, '.removed')
1247

1248 1249 1250 1251 1252
            oid, tid = line[:8], line[8:]
            path = fshelper.getBlobFilename(oid, tid)
            if not os.path.exists(path):
                # Hm, already gone. Odd.
                continue
1253 1254 1255 1256 1257 1258 1259 1260
            handle_file(path)
            assert not os.path.exists(path)
            maybe_remove_empty_dir_containing(path)

        os.remove(os.path.join(self.blob_dir, '.removed'))

        if not self.pack_keep_old:
            return
1261

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
        # Second step, copy remaining files.
        for path, dir_names, file_names in os.walk(self.blob_dir):
            for file_name in file_names:
                if not file_name.endswith('.blob'):
                    continue
                file_path = os.path.join(path, file_name)
                dest = os.path.dirname(old+file_path[lblob_dir:])
                if not os.path.exists(dest):
                    os.makedirs(dest, 0700)
                link_or_copy(file_path, old+file_path[lblob_dir:])
1272

1273 1274 1275 1276 1277 1278 1279
    def iterator(self, start=None, stop=None):
        return FileIterator(self._file_name, start, stop)

    def lastTransaction(self):
        """Return transaction id for last committed transaction"""
        return self._ltid

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    def lastInvalidations(self, count):
        file = self._file
        seek = file.seek
        read = file.read
        self._lock_acquire()
        try:
            pos = self._pos
            while count > 0 and pos > 4:
                count -= 1
                seek(pos-8)
                pos = pos - 8 - u64(read(8))

            seek(0)
1293
            return [(trans.tid, [r.oid for r in trans])
1294
                    for trans in FileIterator(self._file_name, pos=pos)]
1295 1296
        finally:
            self._lock_release()
1297

1298

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    def lastTid(self, oid):
        """Return last serialno committed for object oid.

        If there is no serialno for this oid -- which can only occur
        if it is a new object -- return None.
        """
        try:
            return self.getTid(oid)
        except KeyError:
            return None

    def cleanup(self):
        """Remove all files created by this storage."""
        for ext in '', '.old', '.tmp', '.lock', '.index', '.pack':
            try:
                os.remove(self._file_name + ext)
            except OSError, e:
                if e.errno != errno.ENOENT:
                    raise

1319 1320 1321
    def record_iternext(self, next=None):
        index = self._index
        oid = index.minKey(next)
Tim Peters's avatar
Tim Peters committed
1322

1323 1324
        oid_as_long, = unpack(">Q", oid)
        next_oid = pack(">Q", oid_as_long + 1)
1325
        try:
1326
            next_oid = index.minKey(next_oid)
1327 1328 1329
        except ValueError: # "empty tree" error
            next_oid = None

Jim Fulton's avatar
Jim Fulton committed
1330 1331
        data, tid = self.load(oid, "")

1332
        return oid, tid, data, next_oid
Tim Peters's avatar
Tim Peters committed
1333

1334

1335

1336
def shift_transactions_forward(index, tindex, file, pos, opos):
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    """Copy transactions forward in the data file

    This might be done as part of a recovery effort
    """

    # Cache a bunch of methods
    seek=file.seek
    read=file.read
    write=file.write

    index_get=index.get

    # Initialize,
    pv=z64
    p1=opos
    p2=pos
    offset=p2-p1

    # Copy the data in two stages.  In the packing stage,
    # we skip records that are non-current or that are for
    # unreferenced objects. We also skip undone transactions.
    #
    # After the packing stage, we copy everything but undone
    # transactions, however, we have to update various back pointers.
    # We have to have the storage lock in the second phase to keep
    # data from being changed while we're copying.
    pnv=None
    while 1:

        # Read the transaction record
        seek(pos)
        h=read(TRANS_HDR_LEN)
        if len(h) < TRANS_HDR_LEN: break
        tid, stl, status, ul, dl, el = unpack(TRANS_HDR,h)
        if status=='c': break # Oops. we found a checkpoint flag.
        tl=u64(stl)
        tpos=pos
        tend=tpos+tl

        otpos=opos # start pos of output trans

        thl=ul+dl+el
        h2=read(thl)
        if len(h2) != thl:
            raise PackError(opos)

        # write out the transaction record
        seek(opos)
        write(h)
        write(h2)

        thl=TRANS_HDR_LEN+thl
        pos=tpos+thl
        opos=otpos+thl

        while pos < tend:
            # Read the data records for this transaction
            seek(pos)
            h=read(DATA_HDR_LEN)
            oid,serial,sprev,stloc,vlen,splen = unpack(DATA_HDR, h)
1397
            assert not vlen
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
            plen=u64(splen)
            dlen=DATA_HDR_LEN+(plen or 8)

            tindex[oid]=opos

            if plen: p=read(plen)
            else:
                p=read(8)
                p=u64(p)
                if p >= p2: p=p-offset
                elif p >= p1:
                    # Ick, we're in trouble. Let's bail
                    # to the index and hope for the best
                    p=index_get(oid, 0)
                p=p64(p)

            # WRITE
            seek(opos)
            sprev=p64(index_get(oid, 0))
            write(pack(DATA_HDR,
1418
                       oid, serial, sprev, p64(otpos), 0, splen))
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

            write(p)

            opos=opos+dlen
            pos=pos+dlen

        # skip the (intentionally redundant) transaction length
        pos=pos+8

        if status != 'u':
            index.update(tindex) # Record the position

        tindex.clear()

        write(stl)
        opos=opos+8

    return opos

def search_back(file, pos):
    seek=file.seek
    read=file.read
    seek(0,2)
    s=p=file.tell()
    while p > pos:
        seek(p-8)
        l=u64(read(8))
        if l <= 0: break
        p=p-l-8

    return p, s

def recover(file_name):
    file=open(file_name, 'r+b')
    index={}
    tindex={}

1456
    pos, oid, tid = read_index(file, file_name, index, tindex, recover=1)
1457 1458 1459 1460 1461 1462 1463
    if oid is not None:
        print "Nothing to recover"
        return

    opos=pos
    pos, sz = search_back(file, pos)
    if pos < sz:
1464
        npos = shift_transactions_forward(index, tindex, file, pos, opos)
1465 1466 1467 1468 1469 1470 1471 1472

    file.truncate(npos)

    print "Recovered file, lost %s, ended up with %s bytes" % (
        pos-opos, npos)



1473
def read_index(file, name, index, tindex, stop='\377'*8,
1474
               ltid=z64, start=4L, maxoid=z64, recover=0, read_only=0):
1475
    """Scan the file storage and update the index.
1476 1477 1478 1479 1480 1481 1482

    Returns file position, max oid, and last transaction id.  It also
    stores index information in the three dictionary arguments.

    Arguments:
    file -- a file object (the Data.fs)
    name -- the name of the file (presumably file.name)
1483 1484 1485
    index -- fsIndex, oid -> data record file offset
    tindex -- dictionary, oid -> data record offset
              tindex is cleared before return
1486 1487

    There are several default arguments that affect the scan or the
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    return values.  TODO:  document them.

    start -- the file position at which to start scanning for oids added
             beyond the ones the passed-in indices know about.  The .index
             file caches the highest ._pos FileStorage knew about when the
             the .index file was last saved, and that's the intended value
             to pass in for start; accept the default (and pass empty
             indices) to recreate the index from scratch
    maxoid -- ignored (it meant something prior to ZODB 3.2.6; the argument
              still exists just so the signature of read_index() stayed the
              same)
1499 1500 1501

    The file position returned is the position just after the last
    valid transaction record.  The oid returned is the maximum object
1502 1503
    id in `index`, or z64 if the index is empty.  The transaction id is the
    tid of the last transaction, or ltid if the index is empty.
1504 1505 1506 1507 1508
    """

    read = file.read
    seek = file.seek
    seek(0, 2)
1509
    file_size = file.tell()
1510 1511 1512
    fmt = TempFormatter(file)

    if file_size:
1513
        if file_size < start:
1514
            raise FileStorageFormatError(file.name)
1515 1516
        seek(0)
        if read(4) != packed_version:
1517
            raise FileStorageFormatError(name)
1518 1519 1520
    else:
        if not read_only:
            file.write(packed_version)
1521
        return 4L, z64, ltid
1522

1523
    index_get = index.get
1524

1525
    pos = start
1526
    seek(start)
1527
    tid = '\0' * 7 + '\1'
1528 1529 1530

    while 1:
        # Read the transaction record
1531 1532 1533
        h = read(TRANS_HDR_LEN)
        if not h:
            break
1534 1535
        if len(h) != TRANS_HDR_LEN:
            if not read_only:
1536
                logger.warning('%s truncated at %s', name, pos)
1537 1538 1539 1540
                seek(pos)
                file.truncate()
            break

1541
        tid, tl, status, ul, dl, el = unpack(TRANS_HDR, h)
1542 1543

        if tid <= ltid:
1544
            logger.warning("%s time-stamp reduction at %s", name, pos)
1545 1546 1547 1548 1549 1550 1551
        ltid = tid

        if pos+(tl+8) > file_size or status=='c':
            # Hm, the data were truncated or the checkpoint flag wasn't
            # cleared.  They may also be corrupted,
            # in which case, we don't want to totally lose the data.
            if not read_only:
1552 1553
                logger.warning("%s truncated, possibly due to damaged"
                               " records at %s", name, pos)
1554 1555 1556 1557
                _truncate(file, name, pos)
            break

        if status not in ' up':
1558 1559
            logger.warning('%s has invalid status, %s, at %s',
                           name, status, pos)
1560

1561
        if tl < TRANS_HDR_LEN + ul + dl + el:
1562 1563 1564 1565 1566 1567
            # We're in trouble. Find out if this is bad data in the
            # middle of the file, or just a turd that Win 9x dropped
            # at the end when the system crashed.
            # Skip to the end and read what should be the transaction length
            # of the last transaction.
            seek(-8, 2)
1568
            rtl = u64(read(8))
1569 1570 1571
            # Now check to see if the redundant transaction length is
            # reasonable:
            if file_size - rtl < pos or rtl < TRANS_HDR_LEN:
1572 1573
                logger.critical('%s has invalid transaction header at %s',
                                name, pos)
1574
                if not read_only:
1575 1576
                    logger.warning(
                         "It appears that there is invalid data at the end of "
1577
                         "the file, possibly due to a system crash.  %s "
1578
                         "truncated to recover from bad data at end." % name)
1579 1580 1581
                    _truncate(file, name, pos)
                break
            else:
1582 1583
                if recover:
                    return pos, None, None
1584 1585 1586 1587 1588
                panic('%s has invalid transaction header at %s', name, pos)

        if tid >= stop:
            break

1589 1590
        tpos = pos
        tend = tpos + tl
1591

1592
        if status == 'u':
1593 1594
            # Undone transaction, skip it
            seek(tend)
1595
            h = u64(read(8))
1596
            if h != tl:
1597 1598
                if recover:
                    return tpos, None, None
1599 1600
                panic('%s has inconsistent transaction length at %s',
                      name, pos)
1601
            pos = tend + 8
1602 1603
            continue

1604
        pos = tpos + TRANS_HDR_LEN + ul + dl + el
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
        while pos < tend:
            # Read the data records for this transaction
            h = fmt._read_data_header(pos)
            dlen = h.recordlen()
            tindex[h.oid] = pos

            if pos + dlen > tend or h.tloc != tpos:
                if recover:
                    return tpos, None, None
                panic("%s data record exceeds transaction record at %s",
                      name, pos)

            if index_get(h.oid, 0) != h.prev:
1618
                if h.prev:
1619 1620
                    if recover:
                        return tpos, None, None
1621 1622
                    logger.error("%s incorrect previous pointer at %s",
                                 name, pos)
1623
                else:
1624 1625
                    logger.warning("%s incorrect previous pointer at %s",
                                   name, pos)
1626

1627
            pos += dlen
1628 1629

        if pos != tend:
1630 1631
            if recover:
                return tpos, None, None
1632 1633 1634 1635 1636 1637
            panic("%s data records don't add up at %s",name,tpos)

        # Read the (intentionally redundant) transaction length
        seek(pos)
        h = u64(read(8))
        if h != tl:
1638 1639
            if recover:
                return tpos, None, None
1640 1641
            panic("%s redundant transaction length check failed at %s",
                  name, pos)
1642 1643 1644 1645
        pos += 8

        index.update(tindex)
        tindex.clear()
1646

1647 1648 1649 1650 1651 1652 1653
    # Caution:  fsIndex doesn't have an efficient __nonzero__ or __len__.
    # That's why we do try/except instead.  fsIndex.maxKey() is fast.
    try:
        maxoid = index.maxKey()
    except ValueError:
        # The index is empty.
        maxoid == z64
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667

    return pos, maxoid, ltid


def _truncate(file, name, pos):
    file.seek(0, 2)
    file_size = file.tell()
    try:
        i = 0
        while 1:
            oname='%s.tr%s' % (name, i)
            if os.path.exists(oname):
                i += 1
            else:
1668 1669
                logger.warning("Writing truncated data from %s to %s",
                               name, oname)
1670 1671
                o = open(oname,'wb')
                file.seek(pos)
1672
                ZODB.utils.cp(file, o, file_size-pos)
1673 1674 1675
                o.close()
                break
    except:
1676 1677
        logger.error("couldn\'t write truncated data for %s", name,
              exc_info=True)
1678
        raise POSException.StorageSystemError("Couldn't save truncated data")
1679 1680 1681 1682 1683

    file.seek(pos)
    file.truncate()


1684
class FileIterator(FileStorageFormatter):
1685 1686 1687 1688 1689
    """Iterate over the transactions in a FileStorage file.
    """
    _ltid = z64
    _file = None

1690 1691 1692
    def __init__(self, filename, start=None, stop=None, pos=4L):
        assert isinstance(filename, str)
        file = open(filename, 'rb')
1693
        self._file = file
1694
        self._file_name = filename
1695
        if file.read(4) != packed_version:
1696
            raise FileStorageFormatError(file.name)
1697 1698
        file.seek(0,2)
        self._file_size = file.tell()
1699 1700 1701
        if (pos < 4) or pos > self._file_size:
            raise ValueError("Given position is greater than the file size",
                             pos, self._file_size)
1702
        self._pos = pos
1703 1704
        assert start is None or isinstance(start, str)
        assert stop is None or isinstance(stop, str)
1705 1706
        self._start = start
        self._stop = stop
1707
        if start:
1708 1709
            if self._file_size <= 4:
                return
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
            self._skip_to_start(start)

    def __len__(self):
        # Define a bogus __len__() to make the iterator work
        # with code like builtin list() and tuple() in Python 2.1.
        # There's a lot of C code that expects a sequence to have
        # an __len__() but can cope with any sort of mistake in its
        # implementation.  So just return 0.
        return 0

    # This allows us to pass an iterator as the `other' argument to
    # copyTransactionsFrom() in BaseStorage.  The advantage here is that we
    # can create the iterator manually, e.g. setting start and stop, and then
    # just let copyTransactionsFrom() do its thing.
    def iterator(self):
        return self

    def close(self):
        file = self._file
        if file is not None:
            self._file = None
            file.close()

    def _skip_to_start(self, start):
Dmitry Vasiliev's avatar
Dmitry Vasiliev committed
1734
        file = self._file
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
        pos1 = self._pos
        file.seek(pos1)
        tid1 = file.read(8)
        if len(tid1) < 8:
            raise CorruptedError("Couldn't read tid.")
        if start < tid1:
            pos2 = pos1
            tid2 = tid1
            file.seek(4)
            tid1 = file.read(8)
            if start <= tid1:
                self._pos = 4
                return
            pos1 = 4
        else:
            if start == tid1:
                return

            # Try to read the last transaction. We could be unlucky and
            # opened the file while committing a transaction.  In that
            # case, we'll just scan from the beginning if the file is
            # small enough, otherwise we'll fail.
            file.seek(self._file_size-8)
            l = u64(file.read(8))
            if not (l + 12 <= self._file_size and
                    self._read_num(self._file_size-l) == l):
                if self._file_size < (1<<20):
                    return self._scan_foreward(start)
                raise ValueError("Can't find last transaction in large file")
            pos2 = self._file_size-l-8
            file.seek(pos2)
            tid2 = file.read(8)
            if tid2 < tid1:
                raise CorruptedError("Tids out of order.")
            if tid2 <= start:
                if tid2 == start:
                    self._pos = pos2
                else:
                    self._pos = self._file_size
                return

        t1 = ZODB.TimeStamp.TimeStamp(tid1).timeTime()
        t2 = ZODB.TimeStamp.TimeStamp(tid2).timeTime()
        ts = ZODB.TimeStamp.TimeStamp(start).timeTime()
        if (ts - t1) < (t2 - ts):
            return self._scan_forward(pos1, start)
        else:
            return self._scan_backward(pos2, start)

    def _scan_forward(self, pos, start):
        logger.debug("Scan forward %s:%s looking for %r",
                     self._file_name, pos, start)
        file = self._file
1788
        while 1:
1789 1790 1791 1792
            # Read the transaction record
            h = self._read_txn_header(pos)
            if h.tid >= start:
                self._pos = pos
1793
                return
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813

            pos += h.tlen + 8

    def _scan_backward(self, pos, start):
        logger.debug("Scan backward %s:%s looking for %r",
                     self._file_name, pos, start)
        file = self._file
        seek = file.seek
        read = file.read
        while 1:
            pos -= 8
            seek(pos)
            tlen = ZODB.utils.u64(read(8))
            pos -= tlen
            h = self._read_txn_header(pos)
            if h.tid <= start:
                if h.tid == start:
                    self._pos = pos
                else:
                    self._pos = pos + tlen + 8
1814 1815
                return

1816 1817 1818 1819 1820
    # Iterator protocol
    def __iter__(self):
        return self

    def next(self):
1821
        if self._file is None:
1822
            raise ZODB.interfaces.StorageStopIteration()
1823 1824

        pos = self._pos
1825 1826
        while True:

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
            # Read the transaction record
            try:
                h = self._read_txn_header(pos)
            except CorruptedDataError, err:
                # If buf is empty, we've reached EOF.
                if not err.buf:
                    break
                raise

            if h.tid <= self._ltid:
1837 1838
                logger.warning("%s time-stamp reduction at %s",
                               self._file.name, pos)
1839 1840 1841
            self._ltid = h.tid

            if self._stop is not None and h.tid > self._stop:
1842
                break
1843 1844 1845

            if h.status == "c":
                # Assume we've hit the last, in-progress transaction
1846
                break
1847 1848 1849 1850 1851

            if pos + h.tlen + 8 > self._file_size:
                # Hm, the data were truncated or the checkpoint flag wasn't
                # cleared.  They may also be corrupted,
                # in which case, we don't want to totally lose the data.
1852 1853
                logger.warning("%s truncated, possibly due to"
                               " damaged records at %s", self._file.name, pos)
1854 1855 1856
                break

            if h.status not in " up":
1857 1858
                logger.warning('%s has invalid status,'
                               ' %s, at %s', self._file.name, h.status, pos)
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

            if h.tlen < h.headerlen():
                # We're in trouble. Find out if this is bad data in
                # the middle of the file, or just a turd that Win 9x
                # dropped at the end when the system crashed.  Skip to
                # the end and read what should be the transaction
                # length of the last transaction.
                self._file.seek(-8, 2)
                rtl = u64(self._file.read(8))
                # Now check to see if the redundant transaction length is
                # reasonable:
                if self._file_size - rtl < pos or rtl < TRANS_HDR_LEN:
1871 1872 1873 1874
                    logger.critical("%s has invalid transaction header at %s",
                                    self._file.name, pos)
                    logger.warning(
                         "It appears that there is invalid data at the end of "
1875 1876 1877 1878 1879
                         "the file, possibly due to a system crash.  %s "
                         "truncated to recover from bad data at end."
                         % self._file.name)
                    break
                else:
1880 1881
                    logger.warning("%s has invalid transaction header at %s",
                                   self._file.name, pos)
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
                    break

            tpos = pos
            tend = tpos + h.tlen

            if h.status != "u":
                pos = tpos + h.headerlen()
                e = {}
                if h.elen:
                    try:
1892
                        e = loads(h.ext)
1893 1894 1895
                    except:
                        pass

1896 1897
                result = TransactionRecord(h.tid, h.status, h.user, h.descr,
                                           e, pos, tend, self._file, tpos)
1898 1899 1900 1901 1902

            # Read the (intentionally redundant) transaction length
            self._file.seek(tend)
            rtl = u64(self._file.read(8))
            if rtl != h.tlen:
1903 1904
                logger.warning("%s redundant transaction length check"
                               " failed at %s", self._file.name, tend)
1905 1906 1907 1908 1909
                break
            self._pos = tend + 8

            return result

1910 1911 1912
        self.close()
        raise ZODB.interfaces.StorageStopIteration()

1913

1914
class TransactionRecord(BaseStorage.TransactionRecord):
1915

1916
    def __init__(self, tid, status, user, desc, ext, pos, tend, file, tpos):
1917 1918
        BaseStorage.TransactionRecord.__init__(
            self, tid, status, user, desc, ext)
1919 1920 1921 1922 1923
        self._pos = pos
        self._tend = tend
        self._file = file
        self._tpos = tpos

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
    def __iter__(self):
        return TransactionRecordIterator(self)

class TransactionRecordIterator(FileStorageFormatter):
    """Iterate over the transactions in a FileStorage file."""

    def __init__(self, record):
        self._file = record._file
        self._pos = record._pos
        self._tpos = record._tpos
        self._tend = record._tend

1936 1937 1938 1939
    def __iter__(self):
        return self

    def next(self):
1940 1941 1942 1943 1944 1945 1946
        pos = self._pos
        while pos < self._tend:
            # Read the data records for this transaction
            h = self._read_data_header(pos)
            dlen = h.recordlen()

            if pos + dlen > self._tend or h.tloc != self._tpos:
1947 1948
                logger.warning("%s data record exceeds transaction"
                               " record at %s", file.name, pos)
1949 1950 1951 1952 1953 1954 1955 1956 1957
                break

            self._pos = pos + dlen
            prev_txn = None
            if h.plen:
                data = self._file.read(h.plen)
            else:
                if h.back == 0:
                    # If the backpointer is 0, then this transaction
1958
                    # undoes the object creation.  It undid the
1959 1960 1961 1962 1963
                    # transaction that created it.  Return None
                    # instead of a pickle to indicate this.
                    data = None
                else:
                    data, tid = self._loadBackTxn(h.oid, h.back, False)
1964 1965
                    # Caution:  :ooks like this only goes one link back.
                    # Should it go to the original data like BDBFullStorage?
1966 1967
                    prev_txn = self.getTxnFromData(h.oid, h.back)

1968 1969 1970
            return Record(h.oid, h.tid, data, prev_txn, pos)

        raise ZODB.interfaces.StorageStopIteration()
1971 1972 1973


class Record(BaseStorage.DataRecord):
1974

1975
    def __init__(self, oid, tid, data, prev, pos):
1976
        super(Record, self).__init__(oid, tid, data, prev)
1977
        self.pos = pos
1978

1979

1980 1981
class UndoSearch:

1982
    def __init__(self, file, pos, first, last, filter=None):
1983 1984 1985 1986 1987
        self.file = file
        self.pos = pos
        self.first = first
        self.last = last
        self.filter = filter
1988 1989
        # self.i is the index of the transaction we're _going_ to find
        # next.  When it reaches self.first, we should start appending
1990
        # to self.results.  When it reaches self.last, we're done
1991
        # (although we may finish earlier).
1992 1993
        self.i = 0
        self.results = []
1994
        self.stop = False
1995 1996 1997 1998

    def finished(self):
        """Return True if UndoSearch has found enough records."""
        # BAW: Why 39 please?  This makes no sense (see also below).
1999
        return self.i >= self.last or self.pos < 39 or self.stop
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

    def search(self):
        """Search for another record."""
        dict = self._readnext()
        if dict is not None and (self.filter is None or self.filter(dict)):
            if self.i >= self.first:
                self.results.append(dict)
            self.i += 1

    def _readnext(self):
        """Read the next record from the storage."""
        self.file.seek(self.pos - 8)
        self.pos -= u64(self.file.read(8)) + 8
        self.file.seek(self.pos)
        h = self.file.read(TRANS_HDR_LEN)
Dmitry Vasiliev's avatar
Dmitry Vasiliev committed
2015
        tid, tl, status, ul, dl, el = unpack(TRANS_HDR, h)
2016
        if status == 'p':
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
            self.stop = 1
            return None
        if status != ' ':
            return None
        d = u = ''
        if ul:
            u = self.file.read(ul)
        if dl:
            d = self.file.read(dl)
        e = {}
        if el:
            try:
                e = loads(self.file.read(el))
            except:
                pass
        d = {'id': base64.encodestring(tid).rstrip(),
             'time': TimeStamp(tid).timeTime(),
             'user_name': u,
2035
             'size': tl,
2036 2037 2038
             'description': d}
        d.update(e)
        return d