testblob.py 19.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
##############################################################################
#
# Copyright (c) 2004 Zope Corporation 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.
#
##############################################################################

15 16
from pickle import Pickler
from pickle import Unpickler
17 18
from StringIO import StringIO
from ZConfig import ConfigurationSyntaxError
19
from ZODB.blob import Blob, BlobStorage
20
from ZODB.DB import DB
21 22
from ZODB.FileStorage import FileStorage
from ZODB import utils
23
from ZODB.tests.testConfig import ConfigTestBase
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
from zope.testing import doctest

import base64
import os
import random
import re
import shutil
import stat
import struct
import sys
import sys
import tempfile
import time
import transaction
import unittest
import ZConfig
import ZODB.blob
import ZODB.interfaces
import ZODB.tests.IteratorStorage
import ZODB.tests.util
import zope.testing.renormalizing
import zope.testing.setupstack
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

def new_time():
    """Create a _new_ time stamp.

    This method also makes sure that after retrieving a timestamp that was
    *before* a transaction was committed, that at least one second passes so
    the packing time actually is before the commit time.

    """
    now = new_time = time.time()
    while new_time <= now:
        new_time = time.time()
    time.sleep(1)
    return new_time


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
class BlobConfigTestBase(ConfigTestBase):

    def setUp(self):
        super(BlobConfigTestBase, self).setUp()

        self.blob_dir = tempfile.mkdtemp()

    def tearDown(self):
        super(BlobConfigTestBase, self).tearDown()

        shutil.rmtree(self.blob_dir)


class ZODBBlobConfigTest(BlobConfigTestBase):

    def test_map_config1(self):
        self._test(
            """
            <zodb>
              <blobstorage>
                blob-dir %s
                <mappingstorage/>
              </blobstorage>
            </zodb>
            """ % self.blob_dir)

    def test_file_config1(self):
        path = tempfile.mktemp()
        self._test(
            """
            <zodb>
              <blobstorage>
                blob-dir %s
                <filestorage>
                  path %s
                </filestorage>
              </blobstorage>
            </zodb>
            """ %(self.blob_dir, path))
        os.unlink(path)
        os.unlink(path+".index")
        os.unlink(path+".tmp")

    def test_blob_dir_needed(self):
107
        self.assertRaises(ZConfig.ConfigurationSyntaxError,
108 109 110 111 112 113 114 115 116
                          self._test,
                          """
                          <zodb>
                            <blobstorage>
                              <mappingstorage/>
                            </blobstorage>
                          </zodb>
                          """)

117

118
class BlobTests(unittest.TestCase):
119 120

    def setUp(self):
121 122 123 124 125
        self.test_dir = tempfile.mkdtemp()
        self.here = os.getcwd()
        os.chdir(self.test_dir)
        self.storagefile = 'Data.fs'
        self.blob_dir = 'blobs'
126 127

    def tearDown(self):
128
        os.chdir(self.here)
129
        ZODB.blob.remove_committed_dir(self.test_dir)
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
class BlobCloneTests(BlobTests):

    def testDeepCopyCanInvalidate(self):
        """
        Tests regression for invalidation problems related to missing
        readers and writers values in cloned objects (see
        http://mail.zope.org/pipermail/zodb-dev/2008-August/012054.html)
        """
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        transaction.begin()
        root['blob'] = Blob()
        transaction.commit()

        stream = StringIO()
        p = Pickler(stream, 1)
        p.dump(root['blob'])
        u = Unpickler(stream)
        stream.seek(0)
        clone = u.load()
        clone._p_invalidate()

Andreas Zeidler's avatar
Andreas Zeidler committed
156 157 158 159
        # it should also be possible to open the cloned blob
        # (even though it won't contain the original data)
        clone.open()

160 161 162
        # tearDown
        database.close()

163 164 165

class BlobUndoTests(BlobTests):

166 167 168 169 170 171 172 173 174 175
    def testUndoWithoutPreviousVersion(self):
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        transaction.begin()
        root['blob'] = Blob()
        transaction.commit()

176
        database.undo(database.undoLog(0, 1)[0]['id'])
177 178 179 180
        transaction.commit()

        # the blob footprint object should exist no longer
        self.assertRaises(KeyError, root.__getitem__, 'blob')
181 182
        database.close()
        
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    def testUndo(self):
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        transaction.begin()
        blob = Blob()
        blob.open('w').write('this is state 1')
        root['blob'] = blob
        transaction.commit()

        transaction.begin()
        blob = root['blob']
        blob.open('w').write('this is state 2')
        transaction.commit()


201
        database.undo(database.undoLog(0, 1)[0]['id'])
202 203
        transaction.commit()
        self.assertEqual(blob.open('r').read(), 'this is state 1')
204

205
        database.close()
206

207 208 209 210 211 212 213
    def testUndoAfterConsumption(self):
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        transaction.begin()
214
        open('consume1', 'w').write('this is state 1')
215
        blob = Blob()
216
        blob.consumeFile('consume1')
217 218
        root['blob'] = blob
        transaction.commit()
219
        
220 221
        transaction.begin()
        blob = root['blob']
222 223
        open('consume2', 'w').write('this is state 2')
        blob.consumeFile('consume2')
224 225
        transaction.commit()

226
        database.undo(database.undoLog(0, 1)[0]['id'])
227 228 229 230
        transaction.commit()

        self.assertEqual(blob.open('r').read(), 'this is state 1')

231 232
        database.close()

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    def testRedo(self):
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        blob = Blob()

        transaction.begin()
        blob.open('w').write('this is state 1')
        root['blob'] = blob
        transaction.commit()

        transaction.begin()
        blob = root['blob']
        blob.open('w').write('this is state 2')
        transaction.commit()

251
        database.undo(database.undoLog(0, 1)[0]['id'])
252 253 254 255 256 257
        transaction.commit()

        self.assertEqual(blob.open('r').read(), 'this is state 1')

        serial = base64.encodestring(blob_storage._tid)

258
        database.undo(database.undoLog(0, 1)[0]['id'])
259 260 261
        transaction.commit()

        self.assertEqual(blob.open('r').read(), 'this is state 2')
262 263 264

        database.close()

265 266 267 268 269 270 271 272 273 274 275 276 277
    def testRedoOfCreation(self):
        base_storage = FileStorage(self.storagefile)
        blob_storage = BlobStorage(self.blob_dir, base_storage)
        database = DB(blob_storage)
        connection = database.open()
        root = connection.root()
        blob = Blob()

        transaction.begin()
        blob.open('w').write('this is state 1')
        root['blob'] = blob
        transaction.commit()

278
        database.undo(database.undoLog(0, 1)[0]['id'])
279 280 281 282
        transaction.commit()

        self.assertRaises(KeyError, root.__getitem__, 'blob')

283
        database.undo(database.undoLog(0, 1)[0]['id'])
284 285 286 287
        transaction.commit()

        self.assertEqual(blob.open('r').read(), 'this is state 1')

288
        database.close()
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

class RecoveryBlobStorage(unittest.TestCase,
                          ZODB.tests.IteratorStorage.IteratorDeepCompare):

    def setUp(self):
        self.globs = {}
        zope.testing.setupstack.setUpDirectory(self)
        self._storage = BlobStorage(
            'src_blobs', ZODB.FileStorage.FileStorage("Source.fs", create=True))
        self._dst = BlobStorage(
            'dest_blobs', ZODB.FileStorage.FileStorage("Dest.fs", create=True))

    def tearDown(self):
        self._storage.close()
        self._dst.close()
        zope.testing.setupstack.tearDown(self)

    # Requires a setUp() that creates a self._dst destination storage
    def testSimpleBlobRecovery(self):
        self.assert_(
            ZODB.interfaces.IBlobStorageRestoreable.providedBy(self._storage)
            )
        db = DB(self._storage)
        conn = db.open()
        conn.root()[1] = ZODB.blob.Blob()
        transaction.commit()
        conn.root()[2] = ZODB.blob.Blob()
        conn.root()[2].open('w').write('some data')
        transaction.commit()
        conn.root()[3] = ZODB.blob.Blob()
        conn.root()[3].open('w').write(
            (''.join(struct.pack(">I", random.randint(0, (1<<32)-1))
                     for i in range(random.randint(10000,20000)))
             )[:-random.randint(1,4)]
            )
        transaction.commit()
        conn.root()[2] = ZODB.blob.Blob()
        conn.root()[2].open('w').write('some other data')
        transaction.commit()
        self._dst.copyTransactionsFrom(self._storage)
        self.compare(self._storage, self._dst)
    

333 334 335 336 337 338 339 340 341 342 343 344 345
def gc_blob_removes_uncommitted_data():
    """
    >>> from ZODB.blob import Blob
    >>> blob = Blob()
    >>> blob.open('w').write('x')
    >>> fname = blob._p_blob_uncommitted
    >>> os.path.exists(fname)
    True
    >>> blob = None
    >>> os.path.exists(fname)
    False
    """

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
def commit_from_wrong_partition():
    """
    It should be possible to commit changes even when a blob is on a
    different partition.

    We can simulare this by temporarily breaking os.rename. :)

    >>> def fail(*args):
    ...     raise OSError

    >>> os_rename = os.rename
    >>> os.rename = fail

    >>> import logging, sys
    >>> logger = logging.getLogger('ZODB.blob.copied')
    >>> handler = logging.StreamHandler(sys.stdout)
    >>> logger.propagate = False
    >>> logger.setLevel(logging.DEBUG)
    >>> logger.addHandler(handler)

    >>> import transaction
    >>> from ZODB.MappingStorage import MappingStorage
    >>> from ZODB.blob import BlobStorage
    >>> from ZODB.DB import DB
    >>> from tempfile import mkdtemp
    >>> base_storage = MappingStorage("test")
    >>> blob_dir = mkdtemp()
    >>> blob_storage = BlobStorage(blob_dir, base_storage)
    >>> database = DB(blob_storage)
    >>> connection = database.open()
    >>> root = connection.root()
    >>> from ZODB.blob import Blob
    >>> root['blob'] = Blob()
    >>> root['blob'].open('w').write('test')
    >>> transaction.commit() # doctest: +ELLIPSIS
    Copied blob file ...

    >>> root['blob'].open().read()
    'test'

Works with savepoints too:

    >>> root['blob2'] = Blob()
    >>> root['blob2'].open('w').write('test2')
    >>> _ = transaction.savepoint() # doctest: +ELLIPSIS
    Copied blob file ...

    >>> transaction.commit() # doctest: +ELLIPSIS
    Copied blob file ...
    
    >>> root['blob2'].open().read()
    'test2'
398

399 400 401 402 403 404 405
    >>> os.rename = os_rename
    >>> logger.propagate = True
    >>> logger.setLevel(0)
    >>> logger.removeHandler(handler)

    """

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

def packing_with_uncommitted_data_non_undoing():
    """
    This covers regression for bug #130459.

    When uncommitted data exists it formerly was written to the root of the
    blob_directory and confused our packing strategy. We now use a separate
    temporary directory that is ignored while packing.

    >>> import transaction
    >>> from ZODB.MappingStorage import MappingStorage
    >>> from ZODB.blob import BlobStorage
    >>> from ZODB.DB import DB
    >>> from ZODB.serialize import referencesf
    >>> from tempfile import mkdtemp

    >>> base_storage = MappingStorage("test")
    >>> blob_dir = mkdtemp()
    >>> blob_storage = BlobStorage(blob_dir, base_storage)
    >>> database = DB(blob_storage)
    >>> connection = database.open()
    >>> root = connection.root()
    >>> from ZODB.blob import Blob
    >>> root['blob'] = Blob()
    >>> connection.add(root['blob'])
    >>> root['blob'].open('w').write('test')

    >>> blob_storage.pack(new_time(), referencesf)

    Clean up:

    >>> database.close()
    >>> import shutil
    >>> shutil.rmtree(blob_dir)

    """

def packing_with_uncommitted_data_undoing():
    """
    This covers regression for bug #130459.

    When uncommitted data exists it formerly was written to the root of the
    blob_directory and confused our packing strategy. We now use a separate
    temporary directory that is ignored while packing.

    >>> import transaction
    >>> from ZODB.FileStorage.FileStorage import FileStorage
    >>> from ZODB.blob import BlobStorage
    >>> from ZODB.DB import DB
    >>> from ZODB.serialize import referencesf
    >>> from tempfile import mkdtemp, mktemp

    >>> storagefile = mktemp()
    >>> base_storage = FileStorage(storagefile)
    >>> blob_dir = mkdtemp()
    >>> blob_storage = BlobStorage(blob_dir, base_storage)
    >>> database = DB(blob_storage)
    >>> connection = database.open()
    >>> root = connection.root()
    >>> from ZODB.blob import Blob
    >>> root['blob'] = Blob()
    >>> connection.add(root['blob'])
    >>> root['blob'].open('w').write('test')

    >>> blob_storage.pack(new_time(), referencesf)

    Clean up:

    >>> database.close()
    >>> import shutil
    >>> shutil.rmtree(blob_dir)

    >>> os.unlink(storagefile)
    >>> os.unlink(storagefile+".index")
    >>> os.unlink(storagefile+".tmp")


    """


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
def secure_blob_directory():
    """
    This is a test for secure creation and verification of secure settings of
    blob directories.

    >>> from ZODB.FileStorage.FileStorage import FileStorage
    >>> from ZODB.blob import BlobStorage
    >>> from tempfile import mkdtemp
    >>> import os.path

    >>> working_directory = mkdtemp()
    >>> base_storage = FileStorage(os.path.join(working_directory, 'Data.fs'))
    >>> blob_storage = BlobStorage(os.path.join(working_directory, 'blobs'),
    ...                            base_storage)

    Two directories are created:

    >>> blob_dir = os.path.join(working_directory, 'blobs')
    >>> os.path.isdir(blob_dir)
    True
    >>> tmp_dir = os.path.join(blob_dir, 'tmp')
    >>> os.path.isdir(tmp_dir)
    True

    They are only accessible by the owner:

    >>> oct(os.stat(blob_dir).st_mode)
    '040700'
    >>> oct(os.stat(tmp_dir).st_mode)
    '040700'

    These settings are recognized as secure:

    >>> blob_storage.fshelper.isSecure(blob_dir)
    True
    >>> blob_storage.fshelper.isSecure(tmp_dir)
    True

    After making the permissions of tmp_dir more liberal, the directory is
    recognized as insecure:

    >>> os.chmod(tmp_dir, 040711)
    >>> blob_storage.fshelper.isSecure(tmp_dir)
    False

    Clean up:

    >>> blob_storage.close()
    >>> import shutil
    >>> shutil.rmtree(working_directory)

    """

539 540 541 542 543
# On windows, we can't create secure blob directories, at least not
# with APIs in the standard library, so there's no point in testing
# this.
if sys.platform == 'win32':
    del secure_blob_directory
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
def loadblob_tmpstore():
    """
    This is a test for assuring that the TmpStore's loadBlob implementation
    falls back correctly to loadBlob on the backend.

    First, let's setup a regular database and store a blob:

    >>> import transaction
    >>> from ZODB.FileStorage.FileStorage import FileStorage
    >>> from ZODB.blob import BlobStorage
    >>> from ZODB.DB import DB
    >>> from ZODB.serialize import referencesf
    >>> from tempfile import mkdtemp, mktemp

    >>> storagefile = mktemp()
    >>> base_storage = FileStorage(storagefile)
    >>> blob_dir = mkdtemp()
    >>> blob_storage = BlobStorage(blob_dir, base_storage)
    >>> database = DB(blob_storage)
    >>> connection = database.open()
    >>> root = connection.root()
    >>> from ZODB.blob import Blob
    >>> root['blob'] = Blob()
    >>> connection.add(root['blob'])
    >>> root['blob'].open('w').write('test')
    >>> import transaction
    >>> transaction.commit()
    >>> blob_oid = root['blob']._p_oid
    >>> tid = blob_storage.lastTransaction()

    Now we open a database with a TmpStore in front:

    >>> database.close()

    >>> from ZODB.Connection import TmpStore
    >>> tmpstore = TmpStore(blob_storage)

    We can access the blob correctly:

    >>> tmpstore.loadBlob(blob_oid, tid) # doctest: +ELLIPSIS
585
    '.../0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x01/0x...blob'
586 587 588 589 590

    Clean up:

    >>> database.close()
    >>> import shutil
591
    >>> rmtree(blob_dir)
592 593 594 595

    >>> os.unlink(storagefile)
    >>> os.unlink(storagefile+".index")
    >>> os.unlink(storagefile+".tmp")
596
    """
597

598
def is_blob_record():
599
    r"""
600 601 602 603 604 605 606 607 608 609 610
    >>> fs = FileStorage('Data.fs')
    >>> bs = ZODB.blob.BlobStorage('blobs', fs)
    >>> db = DB(bs)
    >>> conn = db.open()
    >>> conn.root()['blob'] = ZODB.blob.Blob()
    >>> transaction.commit()
    >>> ZODB.blob.is_blob_record(fs.load(ZODB.utils.p64(0), '')[0])
    False
    >>> ZODB.blob.is_blob_record(fs.load(ZODB.utils.p64(1), '')[0])
    True

611 612 613 614 615 616 617 618 619
    An invalid pickle yields a false value:

    >>> ZODB.blob.is_blob_record("Hello world!")
    False
    >>> ZODB.blob.is_blob_record('c__main__\nC\nq\x01.')
    False
    >>> ZODB.blob.is_blob_record('cWaaaa\nC\nq\x01.')
    False

620 621 622
    >>> db.close()
    """

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
def do_not_depend_on_cwd():
    """
    >>> from ZODB.MappingStorage import MappingStorage
    >>> bs = ZODB.blob.BlobStorage('blobs', MappingStorage())
    >>> here = os.getcwd()
    >>> os.mkdir('evil')
    >>> os.chdir('evil')
    >>> db = DB(bs)
    >>> conn = db.open()
    >>> conn.root()['blob'] = ZODB.blob.Blob()
    >>> conn.root()['blob'].open('w').write('data')
    >>> transaction.commit()
    >>> os.chdir(here)
    >>> conn.root()['blob'].open().read()
    'data'
    
    """

641
def setUp(test):
642 643
    zope.testing.setupstack.setUpDirectory(test)
    test.globs['rmtree'] = zope.testing.setupstack.rmtree
644

645 646
def test_suite():
    suite = unittest.TestSuite()
647 648 649 650
    suite.addTest(unittest.makeSuite(ZODBBlobConfigTest))
    suite.addTest(doctest.DocFileSuite(
        "blob_basic.txt",  "blob_connection.txt", "blob_transaction.txt",
        "blob_packing.txt", "blob_importexport.txt", "blob_consume.txt",
Christian Theune's avatar
Christian Theune committed
651
        "blob_tempdir.txt",
652
        setUp=setUp,
653
        tearDown=zope.testing.setupstack.tearDown,
654 655 656 657 658
        optionflags=doctest.ELLIPSIS,
        ))
    suite.addTest(doctest.DocFileSuite(
        "blob_layout.txt",
        optionflags=doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE,
Jim Fulton's avatar
Jim Fulton committed
659
        setUp=setUp,
660 661
        tearDown=zope.testing.setupstack.tearDown,
        checker = zope.testing.renormalizing.RENormalizing([
Jim Fulton's avatar
Jim Fulton committed
662 663
            (re.compile(r'\%(sep)s\%(sep)s' % dict(sep=os.path.sep)), '/'),
            (re.compile(r'\%(sep)s' % dict(sep=os.path.sep)), '/'),
664 665
            (re.compile(r'\S+/((old|bushy|lawn)/\S+/foo[23456]?)'), r'\1'),
            ]),
Christian Theune's avatar
Christian Theune committed
666
        ))
667
    suite.addTest(doctest.DocTestSuite(
668
        setUp=setUp,
669
        tearDown=zope.testing.setupstack.tearDown,
670
        checker = zope.testing.renormalizing.RENormalizing([
671 672 673
            (re.compile(r'\%(sep)s\%(sep)s' % dict(sep=os.path.sep)), '/'),
            (re.compile(r'\%(sep)s' % dict(sep=os.path.sep)), '/'),
            ]),
674
        ))
Andreas Zeidler's avatar
Andreas Zeidler committed
675
    suite.addTest(unittest.makeSuite(BlobCloneTests))
676
    suite.addTest(unittest.makeSuite(BlobUndoTests))
677
    suite.addTest(unittest.makeSuite(RecoveryBlobStorage))
678 679 680 681 682

    return suite

if __name__ == '__main__':
    unittest.main(defaultTest = 'test_suite')