Source

whoosh / src / whoosh / filedb / filestore.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
# Copyright 2009 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    1. Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#
#    2. Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of Matt Chaput.

from __future__ import with_statement
import errno, os, sys, tempfile
from threading import Lock

from whoosh.compat import BytesIO, memoryview_
from whoosh.filedb.structfile import BufferFile, StructFile
from whoosh.index import _DEF_INDEX_NAME, EmptyIndexError
from whoosh.util import random_name
from whoosh.util.filelock import FileLock


# Exceptions

class ReadOnlyError(Exception):
    pass


# Base class

class Storage(object):
    """Abstract base class for storage objects.

    A storage object is a virtual flat filesystem, allowing the creation and
    retrieval of file-like objects
    (:class:`~whoosh.filedb.structfile.StructFile` objects). The default
    implementation (:class:`FileStorage`) uses actual files in a directory.

    All access to files in Whoosh goes through this object. This allows more
    different forms of storage (for example, in RAM, in a database, in a single
    file) to be used transparently.

    For example, to create a :class:`FileStorage` object::

        # Create a storage object
        st = FileStorage("indexdir")
        # Create the directory if it doesn't already exist
        st.create()

    The :meth:`Storage.create` method makes it slightly easier to swap storage
    implementations. The ``create()`` method handles set-up of the storage
    object. For example, ``FileStorage.create()`` creates the directory. A
    database implementation might create tables. This is designed to let you
    avoid putting implementation-specific setup code in your application.
    """

    readonly = False
    supports_mmap = False

    def __iter__(self):
        return iter(self.list())

    def __enter__(self):
        self.create()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def create(self):
        """Creates any required implementation-specific resources. For example,
        a filesystem-based implementation might create a directory, while a
        database implementation might create tables. For example::

            from whoosh.filedb.filestore import FileStorage
            # Create a storage object
            st = FileStorage("indexdir")
            # Create any necessary resources
            st.create()

        This method returns ``self`` so you can also say::

            st = FileStorage("indexdir").create()

        Storage implementations should be written so that calling create() a
        second time on the same storage

        :return: a :class:`Storage` instance.
        """

        return self

    def destroy(self, *args, **kwargs):
        """Removes any implementation-specific resources related to this storage
        object. For example, a filesystem-based implementation might delete a
        directory, and a database implementation might drop tables.

        The arguments are implementation-specific.
        """

        pass

    def create_index(self, schema, indexname=_DEF_INDEX_NAME, indexclass=None):
        """Creates a new index in this storage.

        >>> from whoosh import fields
        >>> from whoosh.filedb.filestore import FileStorage
        >>> schema = fields.Schema(content=fields.TEXT)
        >>> # Create the storage directory
        >>> st = FileStorage.create("indexdir")
        >>> # Create an index in the storage
        >>> ix = st.create_index(schema)

        :param schema: the :class:`whoosh.fields.Schema` object to use for the
            new index.
        :param indexname: the name of the index within the storage object. You
            can use this option to store multiple indexes in the same storage.
        :param indexclass: an optional custom ``Index`` sub-class to use to
            create the index files. The default is
            :class:`whoosh.index.FileIndex`. This method will call the
            ``create`` class method on the given class to create the index.
        :return: a :class:`whoosh.index.Index` instance.
        """

        if self.readonly:
            raise ReadOnlyError
        if indexclass is None:
            import whoosh.index
            indexclass = whoosh.index.FileIndex
        return indexclass.create(self, schema, indexname)

    def open_index(self, indexname=_DEF_INDEX_NAME, schema=None, indexclass=None):
        """Opens an existing index (created using :meth:`create_index`) in this
        storage.

        >>> from whoosh.filedb.filestore import FileStorage
        >>> st = FileStorage("indexdir")
        >>> # Open an index in the storage
        >>> ix = st.open_index()

        :param indexname: the name of the index within the storage object. You
            can use this option to store multiple indexes in the same storage.
        :param schema: if you pass in a :class:`whoosh.fields.Schema` object
            using this argument, it will override the schema that was stored
            with the index.
        :param indexclass: an optional custom ``Index`` sub-class to use to
            open the index files. The default is
            :class:`whoosh.index.FileIndex`. This method will instantiate the
            class with this storage object.
        :return: a :class:`whoosh.index.Index` instance.
        """

        if indexclass is None:
            import whoosh.index
            indexclass = whoosh.index.FileIndex
        return indexclass(self, schema=schema, indexname=indexname)

    def index_exists(self, indexname=None):
        """Returns True if a non-empty index exists in this storage.

        :param indexname: the name of the index within the storage object. You
            can use this option to store multiple indexes in the same storage.
        :rtype: bool
        """

        if indexname is None:
            indexname = _DEF_INDEX_NAME
        try:
            ix = self.open_index(indexname)
            gen = ix.latest_generation()
            ix.close()
            return gen > -1
        except EmptyIndexError:
            pass
        return False

    def create_file(self, name):
        """Creates a file with the given name in this storage.

        :param name: the name for the new file.
        :return: a :class:`whoosh.filedb.structfile.StructFile` instance.
        """

        raise NotImplementedError

    def open_file(self, name, *args, **kwargs):
        """Opens a file with the given name in this storage.

        :param name: the name for the new file.
        :return: a :class:`whoosh.filedb.structfile.StructFile` instance.
        """

        raise NotImplementedError

    def list(self):
        """Returns a list of file names in this storage.

        :return: a list of strings
        """
        raise NotImplementedError

    def file_exists(self, name):
        """Returns True if the given file exists in this storage.

        :param name: the name to check.
        :rtype: bool
        """

        raise NotImplementedError

    def file_modified(self, name):
        """Returns the last-modified time of the given file in this storage (as
        a "ctime" UNIX timestamp).

        :param name: the name to check.
        :return: a "ctime" number.
        """

        raise NotImplementedError

    def file_length(self, name):
        """Returns the size (in bytes) of the given file in this storage.

        :param name: the name to check.
        :rtype: int
        """

        raise NotImplementedError

    def delete_file(self, name):
        """Removes the given file from this storage.

        :param name: the name to delete.
        """

        raise NotImplementedError

    def rename_file(self, frm, to, safe=False):
        """Renames a file in this storage.

        :param frm: The current name of the file.
        :param to: The new name for the file.
        :param safe: if True, raise an exception if a file with the new name
            already exists.
        """

        raise NotImplementedError

    def lock(self, name):
        """Return a named lock object (implementing ``.acquire()`` and
        ``.release()`` methods). Different storage implementations may use
        different lock types with different guarantees. For example, the
        RamStorage object uses Python thread locks, while the FileStorage
        object uses filesystem-based locks that are valid across different
        processes.

        :param name: a name for the lock.
        :return: a lock-like object.
        """

        raise NotImplementedError

    def close(self):
        """Closes any resources opened by this storage object. For some storage
        implementations this will be a no-op, but for others it is necessary
        to release locks and/or prevent leaks, so it's a good idea to call it
        when you're done with a storage object.
        """

        pass

    def optimize(self):
        """Optimizes the storage object. The meaning and cost of "optimizing"
        will vary by implementation. For example, a database implementation
        might run a garbage collection procedure on the underlying database.
        """

        pass

    def temp_storage(self, name=None):
        """Creates a new storage object for temporary files. You can call
        :meth:`Storage.destroy` on the new storage when you're finished with
        it.

        :param name: a name for the new storage. This may be optional or
            required depending on the storage implementation.
        :rtype: :class:`Storage`
        """

        raise NotImplementedError


class OverlayStorage(Storage):
    """Overlays two storage objects. Reads are processed from the first if it
    has the named file, otherwise the second. Writes always go to the second.
    """

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def create_index(self, *args, **kwargs):
        self.b.create_index(*args, **kwargs)

    def open_index(self, *args, **kwargs):
        self.a.open_index(*args, **kwargs)

    def create_file(self, *args, **kwargs):
        return self.b.create_file(*args, **kwargs)

    def open_file(self, name, *args, **kwargs):
        if self.a.file_exists(name):
            return self.a.open_file(name, *args, **kwargs)
        else:
            return self.b.open_file(name, *args, **kwargs)

    def list(self):
        return list(set(self.a.list()) | set(self.b.list()))

    def file_exists(self, name):
        return self.a.file_exists(name) or self.b.file_exists(name)

    def file_modified(self, name):
        if self.a.file_exists(name):
            return self.a.file_modified(name)
        else:
            return self.b.file_modified(name)

    def file_length(self, name):
        if self.a.file_exists(name):
            return self.a.file_length(name)
        else:
            return self.b.file_length(name)

    def delete_file(self, name):
        return self.b.delete_file(name)

    def rename_file(self, *args, **kwargs):
        raise NotImplementedError

    def lock(self, name):
        return self.b.lock(name)

    def close(self):
        self.a.close()
        self.b.close()

    def optimize(self):
        self.a.optimize()
        self.b.optimize()

    def temp_storage(self, name=None):
        return self.b.temp_storage(name=name)


class FileStorage(Storage):
    """Storage object that stores the index as files in a directory on disk.

    Prior to version 3, the initializer would raise an IOError if the directory
    did not exist. As of version 3, the object does not check if the
    directory exists at initialization. This change is to support using the
    :meth:`FileStorage.create` method.
    """

    supports_mmap = True

    def __init__(self, path, supports_mmap=True, readonly=False, debug=False):
        """
        :param path: a path to a directory.
        :param supports_mmap: if True (the default), use the ``mmap`` module to
            open memory mapped files. You can open the storage object with
            ``supports_mmap=False`` to force Whoosh to open files normally
            instead of with ``mmap``.
        :param readonly: If ``True``, the object will raise an exception if you
            attempt to create or rename a file.
        """

        self.folder = path
        self.supports_mmap = supports_mmap
        self.readonly = readonly
        self._debug = debug
        self.locks = {}

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self.folder)

    def create(self):
        """Creates this storage object's directory path using ``os.makedirs`` if
        it doesn't already exist.

        >>> from whoosh.filedb.filestore import FileStorage
        >>> st = FileStorage("indexdir")
        >>> st.create()

        This method returns ``self``, you can say::

            st = FileStorage("indexdir").create()

        Note that you can simply create handle the creation of the directory
        yourself and open the storage object using the initializer::

            dirname = "indexdir"
            os.mkdir(dirname)
            st = FileStorage(dirname)

        However, using the ``create()`` method allows you to potentially swap in
        other storage implementations more easily.

        :return: a :class:`Storage` instance.
        """

        dirpath = os.path.abspath(self.folder)
        # If the given directory does not already exist, try to create it
        try:
            os.makedirs(dirpath)
        except OSError:
            # This is necessary for compatibility between Py2 and Py3
            e = sys.exc_info()[1]
            # If we get an error because the path already exists, ignore it
            if e.errno != errno.EEXIST:
                raise

        # Raise an exception if the given path is not a directory
        if not os.path.isdir(dirpath):
            e = IOError("%r is not a directory" % dirpath)
            e.errno = errno.ENOTDIR
            raise e

        return self

    def destroy(self):
        """Removes any files in this storage object and then removes the
        storage object's directory. What happens if any of the files or the
        directory are in use depends on the underlying platform.
        """

        # Remove all files
        self.clean()
        # Try to remove the directory
        os.rmdir(self.folder)

    def create_file(self, name, excl=False, mode="wb", **kwargs):
        """Creates a file with the given name in this storage.

        :param name: the name for the new file.
        :param excl: if True, try to open the file in "exclusive" mode.
        :param mode: the mode flags with which to open the file. The default is
            ``"wb"``.
        :return: a :class:`whoosh.filedb.structfile.StructFile` instance.
        """

        if self.readonly:
            raise ReadOnlyError

        path = self._fpath(name)
        if excl:
            flags = os.O_CREAT | os.O_EXCL | os.O_RDWR
            if hasattr(os, "O_BINARY"):
                flags |= os.O_BINARY
            fd = os.open(path, flags)
            fileobj = os.fdopen(fd, mode)
        else:
            fileobj = open(path, mode)

        f = StructFile(fileobj, name=name, **kwargs)
        return f

    def open_file(self, name, **kwargs):
        """Opens an existing file in this storage.

        :param name: the name of the file to open.
        :param kwargs: additional keyword arguments are passed through to the
            :class:`~whoosh.filedb.structfile.StructFile` initializer.
        :return: a :class:`whoosh.filedb.structfile.StructFile` instance.
        """

        f = StructFile(open(self._fpath(name), "rb"), name=name, **kwargs)
        return f

    def _fpath(self, fname):
        return os.path.abspath(os.path.join(self.folder, fname))

    def clean(self, ignore=False):
        if self.readonly:
            raise ReadOnlyError

        path = self.folder
        files = self.list()
        for fname in files:
            try:
                os.remove(os.path.join(path, fname))
            except OSError:
                if not ignore:
                    raise

    def list(self):
        try:
            files = os.listdir(self.folder)
        except IOError:
            files = []

        return files

    def file_exists(self, name):
        return os.path.exists(self._fpath(name))

    def file_modified(self, name):
        return os.path.getmtime(self._fpath(name))

    def file_length(self, name):
        return os.path.getsize(self._fpath(name))

    def delete_file(self, name):
        if self.readonly:
            raise ReadOnlyError

        os.remove(self._fpath(name))

    def rename_file(self, oldname, newname, safe=False):
        if self.readonly:
            raise ReadOnlyError

        if os.path.exists(self._fpath(newname)):
            if safe:
                raise NameError("File %r exists" % newname)
            else:
                os.remove(self._fpath(newname))
        os.rename(self._fpath(oldname), self._fpath(newname))

    def lock(self, name):
        return FileLock(self._fpath(name))

    def temp_storage(self, name=None):
        name = name or "%s.tmp" % random_name()
        path = os.path.join(self.folder, name)
        tempstore = FileStorage(path)
        return tempstore.create()


class RamStorage(Storage):
    """Storage object that keeps the index in memory.
    """

    supports_mmap = False

    def __init__(self):
        self.files = {}
        self.locks = {}
        self.folder = ''

    def destroy(self):
        del self.files
        del self.locks

    def list(self):
        return list(self.files.keys())

    def clean(self):
        self.files = {}

    def total_size(self):
        return sum(self.file_length(f) for f in self.list())

    def file_exists(self, name):
        return name in self.files

    def file_length(self, name):
        if name not in self.files:
            raise NameError(name)
        return len(self.files[name])

    def file_modified(self, name):
        return -1

    def delete_file(self, name):
        if name not in self.files:
            raise NameError(name)
        del self.files[name]

    def rename_file(self, name, newname, safe=False):
        if name not in self.files:
            raise NameError(name)
        if safe and newname in self.files:
            raise NameError("File %r exists" % newname)

        content = self.files[name]
        del self.files[name]
        self.files[newname] = content

    def create_file(self, name, **kwargs):
        def onclose_fn(sfile):
            self.files[name] = sfile.file.getvalue()
        f = StructFile(BytesIO(), name=name, onclose=onclose_fn)
        return f

    def open_file(self, name, **kwargs):
        if name not in self.files:
            raise NameError(name)
        buf = memoryview_(self.files[name])
        return BufferFile(buf, name=name, **kwargs)

    def lock(self, name):
        if name not in self.locks:
            self.locks[name] = Lock()
        return self.locks[name]

    def temp_storage(self, name=None):
        tdir = tempfile.gettempdir()
        name = name or "%s.tmp" % random_name()
        path = os.path.join(tdir, name)
        tempstore = FileStorage(path)
        return tempstore.create()


def copy_storage(sourcestore, deststore):
    """Copies the files from the source storage object to the destination
    storage object using ``shutil.copyfileobj``.
    """
    from shutil import copyfileobj

    for name in sourcestore.list():
        with sourcestore.open_file(name) as source:
            with deststore.create_file(name) as dest:
                copyfileobj(source, dest)


def copy_to_ram(storage):
    """Copies the given FileStorage object into a new RamStorage object.

    :rtype: :class:`RamStorage`
    """

    ram = RamStorage()
    copy_storage(storage, ram)
    return ram