Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/carquinyol/datastore.py
blob: 5bc841673edf0b95c4ebb740c17d61f5377611d0 (plain)
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
# Copyright (C) 2008, One Laptop Per Child
# Based on code Copyright (C) 2007, ObjectRealms, LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import logging
import uuid
import time
import os
import sys
import traceback

from decorator import decorator
import dbus
import dbus.service
import gobject

from sugar import mime

from carquinyol import layoutmanager
from carquinyol import migration
from carquinyol.layoutmanager import MAX_QUERY_LIMIT
from carquinyol.metadatastore import MetadataStore
from carquinyol.indexstore import IndexStore
from carquinyol.filestore import FileStore
from carquinyol.optimizer import Optimizer

# the name used by the logger
DS_LOG_CHANNEL = 'org.laptop.sugar.DataStore'

DS_SERVICE = "org.laptop.sugar.DataStore"
DS_DBUS_INTERFACE = "org.laptop.sugar.DataStore"
DS_OBJECT_PATH = "/org/laptop/sugar/DataStore"

logger = logging.getLogger(DS_LOG_CHANNEL)


@decorator
def queue_if_frozen(method, self, *args, **kwargs):
    """Decorator to add method invocations to self.queue if self.frozen is set.

    Should only be used to wrap methods that have no return value.
    """
    if self.frozen:
        self.queue.append(lambda: method(self, *args, **kwargs))
    else:
        return method(self, *args, **kwargs)


class DataStore(dbus.service.Object):
    """D-Bus API and logic for connecting all the other components.
    """

    def __init__(self, **options):
        self.frozen = False
        self.queue = []
        bus_name = dbus.service.BusName(DS_SERVICE,
                                        bus=dbus.SessionBus(),
                                        replace_existing=False,
                                        allow_replacement=False)
        dbus.service.Object.__init__(self, bus_name, DS_OBJECT_PATH)

        migrated = self._migrate()

        self._metadata_store = MetadataStore()
        self._file_store = FileStore()
        self._optimizer = Optimizer(self._file_store, self._metadata_store)
        self._index_store = IndexStore()

        if migrated:
            self._rebuild_index()
            return

        try:
            self._index_store.open_index()
        except Exception:
            logging.exception('Failed to open index, will rebuild')
            self._rebuild_index()
            return

        if not layoutmanager.get_instance().index_updated:
            logging.debug('Index is not up-to-date, will update')
            self._update_index()

    def _migrate(self):
        """Check version of data store on disk and migrate if necessary.

        Returns True if migration was done and an index rebuild is required,
        False otherwise.
        """
        layout_manager = layoutmanager.get_instance()
        old_version = layout_manager.get_version()
        if old_version == layoutmanager.CURRENT_LAYOUT_VERSION:
            return False

        if old_version == 0:
            migration.migrate_from_0()

        layout_manager.set_version(layoutmanager.CURRENT_LAYOUT_VERSION)
        return True

    def _rebuild_index(self):
        """Remove and recreate index."""
        layoutmanager.get_instance().index_updated = False
        self._index_store.close_index()
        self._index_store.remove_index()
        self._index_store.open_index()
        self._update_index()

    def _update_index(self):
        """Find entries that are not yet in the index and add them."""
        uids = layoutmanager.get_instance().find_all()
        logging.debug('Going to update the index with object_ids %r',
            uids)
        gobject.idle_add(lambda: self.__update_index_cb(uids),
                            priority=gobject.PRIORITY_LOW)

    def __update_index_cb(self, uids):
        if uids:
            uid = uids.pop()

            logging.debug('Updating entry %r in index. %d to go.', uid,
                len(uids))

            if not self._index_store.contains(uid):
                try:
                    props = self._metadata_store.retrieve(uid)
                    self._index_store.store(uid, props)
                except Exception:
                    logging.exception('Error processing %r', uid)

        if not uids:
            logging.debug('Finished updating index.')
            layoutmanager.get_instance().index_updated = True
            return False
        else:
            return True

    def _create_completion_cb(self, async_cb, async_err_cb, uid, exc=None):
        logger.debug('_create_completion_cb(%r, %r, %r, %r)', async_cb,
            async_err_cb, uid, exc)
        if exc is not None:
            async_err_cb(exc)
            return

        self.Created(uid)
        self._optimizer.optimize(uid)
        logger.debug('created %s', uid)
        async_cb(uid)

    @dbus.service.method(DS_DBUS_INTERFACE,
                         in_signature='a{sv}sb',
                         out_signature='s',
                         async_callbacks=('async_cb', 'async_err_cb'),
                         byte_arrays=True)
    @queue_if_frozen
    def create(self, props, file_path, transfer_ownership,
               async_cb, async_err_cb):
        uid = str(uuid.uuid4())
        logging.debug('datastore.create %r', uid)

        if not props.get('timestamp', ''):
            props['timestamp'] = int(time.time())

        self._metadata_store.store(uid, props)
        self._index_store.store(uid, props)
        self._file_store.store(uid, file_path, transfer_ownership,
                lambda *args: self._create_completion_cb(async_cb,
                                                         async_err_cb,
                                                         uid,
                                                         *args))

    @dbus.service.signal(DS_DBUS_INTERFACE, signature="s")
    def Created(self, uid):
        pass

    def _update_completion_cb(self, async_cb, async_err_cb, uid, exc=None):
        logger.debug('_update_completion_cb() called with %r / %r, exc %r',
            async_cb, async_err_cb, exc)
        if exc is not None:
            async_err_cb(exc)
            return

        self.Updated(uid)
        self._optimizer.optimize(uid)
        logger.debug('updated %s', uid)
        async_cb()

    @dbus.service.method(DS_DBUS_INTERFACE,
             in_signature='sa{sv}sb',
             out_signature='',
             async_callbacks=('async_cb', 'async_err_cb'),
             byte_arrays=True)
    @queue_if_frozen
    def update(self, uid, props, file_path, transfer_ownership,
               async_cb, async_err_cb):
        logging.debug('datastore.update %r', uid)

        if not props.get('timestamp', ''):
            props['timestamp'] = int(time.time())

        self._metadata_store.store(uid, props)
        self._index_store.store(uid, props)

        if os.path.exists(self._file_store.get_file_path(uid)) and \
                (not file_path or os.path.exists(file_path)):
            self._optimizer.remove(uid)
        self._file_store.store(uid, file_path, transfer_ownership,
                lambda *args: self._update_completion_cb(async_cb,
                                                         async_err_cb,
                                                         uid,
                                                         *args))

    @dbus.service.signal(DS_DBUS_INTERFACE, signature="s")
    def Updated(self, uid):
        pass

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='a{sv}as', out_signature='aa{sv}u',
        async_callbacks=('async_cb', 'async_err_cb'))
    @queue_if_frozen
    def find(self, query, properties, async_cb, async_err_cb):
        self._sync_to_dbus_async(self._find, query, properties,
            async_cb=async_cb, async_err_cb=async_err_cb)

    def _find(self, query, properties):
        logging.debug('datastore.find %r', query)
        t = time.time()

        if layoutmanager.get_instance().index_updated:
            try:
                uids, count = self._index_store.find(query)
            except Exception:
                logging.exception('Failed to query index, will rebuild')
                self._rebuild_index()

        if not layoutmanager.get_instance().index_updated:
            logging.warning('Index updating, returning all entries')
            return self._find_all(query, properties)

        entries = []
        for uid in uids:
            entry_path = layoutmanager.get_instance().get_entry_path(uid)
            if not os.path.exists(entry_path):
                logging.warning(
                    'Inconsistency detected, returning all entries')
                self._rebuild_index()
                return self._find_all(query, properties)

            metadata = self._metadata_store.retrieve(uid, properties)
            entries.append(metadata)

        logger.debug('find(): %r', time.time() - t)

        return entries, count

    def _find_all(self, query, properties):
        uids = layoutmanager.get_instance().find_all()
        count = len(uids)

        offset = query.get('offset', 0)
        limit = query.get('limit', MAX_QUERY_LIMIT)
        uids = uids[offset:offset + limit]

        entries = []
        for uid in uids:
            metadata = self._metadata_store.retrieve(uid, properties)
            entries.append(metadata)

        return entries, count

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='s', out_signature='s',
        sender_keyword='sender',
        async_callbacks=('async_cb', 'async_err_cb'))
    @queue_if_frozen
    def get_filename(self, uid, async_cb, async_err_cb, sender=None):
        self._sync_to_dbus_async(self._get_filename, uid, sender,
            async_cb=async_cb, async_err_cb=async_err_cb)

    def _get_filename(self, uid, sender=None):
        logging.debug('datastore.get_filename %r', uid)
        user_id = dbus.Bus().get_unix_user(sender)
        extension = self._get_extension(uid)
        return self._file_store.retrieve(uid, user_id, extension)

    def _get_extension(self, uid):
        mime_type = self._metadata_store.get_property(uid, 'mime_type')
        if mime_type is None or not mime_type:
            return ''
        return mime.get_primary_extension(mime_type)

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='s', out_signature='a{sv}',
        async_callbacks=('async_cb', 'async_err_cb'))
    @queue_if_frozen
    def get_properties(self, uid, async_cb, async_err_cb):
        self._sync_to_dbus_async(self._get_properties, uid,
            async_cb=async_cb, async_err_cb=async_err_cb)

    def _get_properties(self, uid):
        logging.debug('datastore.get_properties %r', uid)
        metadata = self._metadata_store.retrieve(uid)
        return metadata

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='sa{sv}', out_signature='as',
        async_callbacks=('async_cb', 'async_err_cb'))
    @queue_if_frozen
    def get_uniquevaluesfor(self, propertyname, query, async_cb, async_err_cb):
        self._sync_to_dbus_async(self._get_uniquevaluesfor, propertyname,
            query, async_cb=async_cb, async_err_cb=async_err_cb)

    def _get_uniquevaluesfor(self, propertyname, query):
        if propertyname != 'activity':
            raise ValueError('Only ''activity'' is a supported property name')
        if query:
            raise ValueError('The query parameter is not supported')
        if layoutmanager.get_instance().index_updated:
            return self._index_store.get_activities()
        else:
            logging.warning('Index updating, returning an empty list')
            return []

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='s', out_signature='',
        async_callbacks=('async_cb', 'async_err_cb'))
    @queue_if_frozen
    def delete(self, uid, async_cb, async_err_cb):
        self._sync_to_dbus_async(self._delete, uid,
            async_cb=async_cb, async_err_cb=async_err_cb)

    def _delete(self, uid):
        self._optimizer.remove(uid)

        self._index_store.delete(uid)
        self._file_store.delete(uid)
        self._metadata_store.delete(uid)

        entry_path = layoutmanager.get_instance().get_entry_path(uid)
        os.removedirs(entry_path)

        self.Deleted(uid)
        logger.debug('deleted %s', uid)

    @dbus.service.signal(DS_DBUS_INTERFACE, signature="s")
    def Deleted(self, uid):
        pass

    def stop(self):
        """shutdown the service"""
        self._index_store.close_index()
        self.Stopped()

    @dbus.service.signal(DS_DBUS_INTERFACE)
    def Stopped(self):
        pass

    @dbus.service.method(DS_DBUS_INTERFACE,
                         in_signature="sa{sv}",
                         out_signature='s')
    def mount(self, uri, options=None):
        return ''

    @dbus.service.method(DS_DBUS_INTERFACE,
                         in_signature="",
                         out_signature="aa{sv}")
    def mounts(self):
        return [{'id': 1}]

    @dbus.service.method(DS_DBUS_INTERFACE,
                         in_signature="s",
                         out_signature="")
    def unmount(self, mountpoint_id):
        pass

    @dbus.service.signal(DS_DBUS_INTERFACE, signature="a{sv}")
    def Mounted(self, descriptior):
        pass

    @dbus.service.signal(DS_DBUS_INTERFACE, signature="a{sv}")
    def Unmounted(self, descriptor):
        pass

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='', out_signature='',
        async_callbacks=('async_cb', 'async_err_cb'))
    def freeze(self, async_cb, async_err_cb):
        """Close all open files and stop processing requests until thaw.

        Intended for doing online backups.
        """
        logging.info('Starting to freeze.')
        self.frozen = True
        self._index_store.close_index()
        gobject.idle_add(self._freeze_wait_cb, async_cb, async_err_cb,
            priority=gobject.PRIORITY_LOW+100)

    @dbus.service.method(DS_DBUS_INTERFACE,
        in_signature='', out_signature='',
        async_callbacks=('async_cb', 'async_err_cb'))
    def thaw(self, async_cb, async_err_cb):
        """Resume normal operation after freeze.

        A full restart (including migration if required) will be done.
        """
        if not self.frozen:
            raise ValueError('Trying to thaw while we are not frozen.')

        logging.info('Starting to thaw.')

        layoutmanager.get_instance().recheck_index_updated()

        if self._migrate():
            self._rebuild_index()
        else:
            try:
                self._index_store.open_index()
            except Exception:
                logging.exception('Failed to open index, will rebuild')
                self._rebuild_index()
            else:
                if not layoutmanager.get_instance().index_updated:
                    self._update_index()

        self.frozen = False
        gobject.idle_add(self._thaw_work_cb, async_cb, async_err_cb,
            priority=gobject.PRIORITY_LOW)

    def _freeze_wait_cb(self, async_cb, async_err_cb):
        """Stall the freeze() method while asynchronous operations are in
        progress.
        """
        if self._file_store.async_running() or self._optimizer.async_running():
            return True

        logging.info('Fully frozen.')
        async_cb()
        return False

    def _thaw_work_cb(self, async_cb, async_err_cb):
        """Process requests that were queued during freeze."""
        if not layoutmanager.get_instance().index_updated:
            logging.debug('_thaw_work_cb(): Index is not up-to-date, waiting')
            return True

        if not self.queue:
            logging.info('Fully thawed.')
            async_cb()
            return False

        self.queue.pop(0)()
        return True

    def _sync_to_dbus_async(self, method, *args, **kwargs):
        """Wrap a synchronous method in an asynchronous DBus method.

        The DBus callbacks must be passed as keyword arguments async_cb and
        async_err_cb.
        """
        async_cb = kwargs.pop('async_cb')
        async_err_cb = kwargs.pop('async_err_cb')
        try:
            result = method(*args, **kwargs)
        except Exception, exception:
            async_err_cb(exception)
            return

        if isinstance(result, tuple):
            async_cb(*result)
        elif result is None:
            async_cb()
        else:
            async_cb(result)