summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/repo/indexed/IndexedStorage.java
blob: ea131f1a7cf5bd0598eee015a86f500ba8accb1f (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
487
488
489
490
491
492
/*
 * Copyright 2006-2012 Amazon Technologies, Inc. or its affiliates.
 * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
 * of Amazon Technologies, Inc. or its affiliates.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.amazon.carbonado.repo.indexed;

import java.util.Collection;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amazon.carbonado.Cursor;
import com.amazon.carbonado.FetchDeadlockException;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.FetchTimeoutException;
import com.amazon.carbonado.IsolationLevel;
import com.amazon.carbonado.PersistDeadlockException;
import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.PersistTimeoutException;
import com.amazon.carbonado.Query;
import com.amazon.carbonado.RepositoryException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.Storage;
import com.amazon.carbonado.Transaction;
import com.amazon.carbonado.Trigger;
import com.amazon.carbonado.capability.IndexInfo;

import com.amazon.carbonado.cursor.MergeSortBuffer;

import com.amazon.carbonado.filter.Filter;

import com.amazon.carbonado.info.ChainedProperty;
import com.amazon.carbonado.info.StorableIndex;

import com.amazon.carbonado.cursor.SortBuffer;

import com.amazon.carbonado.qe.BoundaryType;
import com.amazon.carbonado.qe.QueryEngine;
import com.amazon.carbonado.qe.QueryExecutorFactory;
import com.amazon.carbonado.qe.StorableIndexSet;
import com.amazon.carbonado.qe.StorageAccess;

import com.amazon.carbonado.util.Throttle;

import static com.amazon.carbonado.repo.indexed.ManagedIndex.*;

/**
 *
 *
 * @author Brian S O'Neill
 */
class IndexedStorage<S extends Storable> implements Storage<S>, StorageAccess<S> {
    final IndexedRepository mRepository;
    final Storage<S> mMasterStorage;

    // Maps managed and queryable indexes to IndexInfo objects.
    private final Map<StorableIndex<S>, IndexInfo> mAllIndexInfoMap;

    // Set of indexes available for queries to use.
    private final StorableIndexSet<S> mQueryableIndexSet;

    private final QueryEngine<S> mQueryEngine;
    
    IndexedStorage(IndexAnalysis<S> analysis) throws RepositoryException {
        mRepository = analysis.repository;
        mMasterStorage = analysis.masterStorage;
        mAllIndexInfoMap = analysis.allIndexInfoMap;
        mQueryableIndexSet = analysis.queryableIndexSet;

        if (analysis.indexesTrigger != null) {
            if (!addTrigger(analysis.indexesTrigger)) {
                // This might be caused by this storage being created again recursively.
                throw new RepositoryException("Unable to add trigger for managing indexes");
            }
        }

        try {
            // Okay, now start doing some damage. First, remove unnecessary indexes.
            for (StorableIndex<S> index : analysis.removeIndexSet) {
                removeIndex(index);
            }

            // Now add new indexes.
            for (StorableIndex<S> index : analysis.addIndexSet) {
                registerIndex((ManagedIndex) mAllIndexInfoMap.get(index));
            }
        } catch (RepositoryException e) {
            // Something went wrong. Cleanup the trigger to avoid an exception if we try again.
            if (analysis.indexesTrigger != null) {
                removeTrigger(analysis.indexesTrigger);
            }
            throw e;
        }

        mQueryEngine = new QueryEngine<S>(mMasterStorage.getStorableType(), mRepository);

        // Install triggers to manage derived properties in external Storables.
        if (analysis.derivedToDependencies != null) {
            for (ChainedProperty<?> derivedTo : analysis.derivedToDependencies) {
                Trigger<? super S> trigger;
                if (mRepository.isStrictTriggers()) {
                    trigger = new DerivedIndexesTrigger.Strict
                        (mRepository, getStorableType(), derivedTo);
                } else {
                    trigger = new DerivedIndexesTrigger
                        (mRepository, getStorableType(), derivedTo);
                }
                addTrigger(trigger);
            }
        }
    }

    public Class<S> getStorableType() {
        return mMasterStorage.getStorableType();
    }

    public S prepare() {
        return mMasterStorage.prepare();
    }

    public Query<S> query() throws FetchException {
        return mQueryEngine.query();
    }

    public Query<S> query(String filter) throws FetchException {
        return mQueryEngine.query(filter);
    }

    public Query<S> query(Filter<S> filter) throws FetchException {
        return mQueryEngine.query(filter);
    }

    public void truncate() throws PersistException {
        hasManagedIndexes: {
            for (IndexInfo info : mAllIndexInfoMap.values()) {
                if (info instanceof ManagedIndex) {
                    break hasManagedIndexes;
                }
            }

            // No managed indexes, so nothing special to do.
            mMasterStorage.truncate();
            return;
        }

        Transaction txn = mRepository.enterTransaction();
        try {
            mMasterStorage.truncate();

            // Now truncate the indexes.
            for (IndexInfo info : mAllIndexInfoMap.values()) {
                if (info instanceof ManagedIndex) {
                    ((ManagedIndex) info).getIndexEntryStorage().truncate();
                }
            }

            txn.commit();
        } finally {
            txn.exit();
        }
    }

    public boolean addTrigger(Trigger<? super S> trigger) {
        return mMasterStorage.addTrigger(trigger);
    }

    public boolean removeTrigger(Trigger<? super S> trigger) {
        return mMasterStorage.removeTrigger(trigger);
    }

    // Required by StorageAccess.
    public QueryExecutorFactory<S> getQueryExecutorFactory() {
        return mQueryEngine;
    }

    // Required by StorageAccess.
    public Collection<StorableIndex<S>> getAllIndexes() {
        return mQueryableIndexSet;
    }

    // Required by StorageAccess.
    public Storage<S> storageDelegate(StorableIndex<S> index) {
        if (mAllIndexInfoMap.get(index) instanceof ManagedIndex) {
            // Index is managed by this storage, which is typical.
            return null;
        }
        // Index is managed by master storage, most likely a primary key index.
        return mMasterStorage;
    }

    public SortBuffer<S> createSortBuffer() {
        return new MergeSortBuffer<S>();
    }

    public SortBuffer<S> createSortBuffer(Query.Controller controller) {
        return new MergeSortBuffer<S>(controller);
    }

    public long countAll() throws FetchException {
        return mMasterStorage.query().count();
    }

    public long countAll(Query.Controller controller) throws FetchException {
        return mMasterStorage.query().count(controller);
    }

    public Cursor<S> fetchAll() throws FetchException {
        return mMasterStorage.query().fetch();
    }

    public Cursor<S> fetchAll(Query.Controller controller) throws FetchException {
        return mMasterStorage.query().fetch(controller);
    }

    public Cursor<S> fetchOne(StorableIndex<S> index,
                              Object[] identityValues)
        throws FetchException
    {
        ManagedIndex<S> indexInfo = (ManagedIndex<S>) mAllIndexInfoMap.get(index);
        return indexInfo.fetchOne(this, identityValues);
    }

    public Cursor<S> fetchOne(StorableIndex<S> index,
                              Object[] identityValues,
                              Query.Controller controller)
        throws FetchException
    {
        ManagedIndex<S> indexInfo = (ManagedIndex<S>) mAllIndexInfoMap.get(index);
        return indexInfo.fetchOne(this, identityValues, controller);
    }

    public Query<?> indexEntryQuery(StorableIndex<S> index)
        throws FetchException
    {
        ManagedIndex<S> indexInfo = (ManagedIndex<S>) mAllIndexInfoMap.get(index);
        return indexInfo.getIndexEntryStorage().query();
    }

    public Cursor<S> fetchFromIndexEntryQuery(StorableIndex<S> index, Query<?> indexEntryQuery)
        throws FetchException
    {
        ManagedIndex<S> indexInfo = (ManagedIndex<S>) mAllIndexInfoMap.get(index);
        return indexInfo.fetchFromIndexEntryQuery(this, indexEntryQuery);
    }

    public Cursor<S> fetchFromIndexEntryQuery(StorableIndex<S> index, Query<?> indexEntryQuery,
                                              Query.Controller controller)
        throws FetchException
    {
        ManagedIndex<S> indexInfo = (ManagedIndex<S>) mAllIndexInfoMap.get(index);
        return indexInfo.fetchFromIndexEntryQuery(this, indexEntryQuery, controller);
    }

    public Cursor<S> fetchSubset(StorableIndex<S> index,
                                 Object[] identityValues,
                                 BoundaryType rangeStartBoundary,
                                 Object rangeStartValue,
                                 BoundaryType rangeEndBoundary,
                                 Object rangeEndValue,
                                 boolean reverseRange,
                                 boolean reverseOrder)
        throws FetchException
    {
        // This method should never be called since a query was returned by indexEntryQuery.
        throw new UnsupportedOperationException();
    }

    public Cursor<S> fetchSubset(StorableIndex<S> index,
                                 Object[] identityValues,
                                 BoundaryType rangeStartBoundary,
                                 Object rangeStartValue,
                                 BoundaryType rangeEndBoundary,
                                 Object rangeEndValue,
                                 boolean reverseRange,
                                 boolean reverseOrder,
                                 Query.Controller controller)
        throws FetchException
    {
        // This method should never be called since a query was returned by indexEntryQuery.
        throw new UnsupportedOperationException();
    }

    private void registerIndex(ManagedIndex<S> managedIndex)
        throws RepositoryException
    {
        StorableIndex index = managedIndex.getIndex();

        if (StoredIndexInfo.class.isAssignableFrom(getStorableType())) {
            throw new IllegalStateException("StoredIndexInfo cannot have indexes");
        }
        StoredIndexInfo info = mRepository.getWrappedRepository()
            .storageFor(StoredIndexInfo.class).prepare();
        info.setIndexName(index.getNameDescriptor());

        try {
            Transaction txn = mRepository.getWrappedRepository()
                .enterTopTransaction(IsolationLevel.READ_COMMITTED);
            try {
                if (info.tryLoad()) {
                    // Index already exists and is registered.
                    return;
                }
            } finally {
                txn.exit();
            }
        } catch (FetchException e) {
            if (e instanceof FetchDeadlockException || e instanceof FetchTimeoutException) {
                // Might be caused by coarse locks. Switch to nested
                // transaction to share the locks.
                Transaction txn = mRepository.getWrappedRepository()
                    .enterTransaction(IsolationLevel.READ_COMMITTED);
                try {
                    if (info.tryLoad()) {
                        // Index already exists and is registered.
                        return;
                    }
                } finally {
                    txn.exit();
                }
            } else {
                throw e;
            }
        }

        // New index, so build it.

        managedIndex.buildIndex(mRepository.getIndexRepairThrottle(),
                                mRepository.getIndexDiscardDuplicates(),
                                false); // verifyOnly = false

        boolean top = true;
        while (true) {
            try {
                Transaction txn;
                if (top) {
                    txn = mRepository.getWrappedRepository()
                        .enterTopTransaction(IsolationLevel.READ_COMMITTED);
                } else {
                    txn = mRepository.getWrappedRepository()
                        .enterTransaction(IsolationLevel.READ_COMMITTED);
                }

                txn.setForUpdate(true);
                try {
                    if (!info.tryLoad()) {
                        info.setIndexTypeDescriptor(index.getTypeDescriptor());
                        info.setCreationTimestamp(System.currentTimeMillis());
                        info.setVersionNumber(0);
                        info.insert();
                        txn.commit();
                    }
                } finally {
                    txn.exit();
                }

                break;
            } catch (RepositoryException e) {
                if (e instanceof FetchDeadlockException ||
                    e instanceof FetchTimeoutException ||
                    e instanceof PersistDeadlockException ||
                    e instanceof PersistTimeoutException)
                {
                    // Might be caused by coarse locks. Switch to nested
                    // transaction to share the locks.
                    if (top) {
                        top = false;
                        continue;
                    }
                }
                throw e;
            }
        }
    }

    private void unregisterIndex(StorableIndex index) throws RepositoryException {
        if (StoredIndexInfo.class.isAssignableFrom(getStorableType())) {
            // Can't unregister when register wasn't allowed.
            return;
        }
        unregisterIndex(index.getNameDescriptor());
    }

    private void unregisterIndex(String indexName) throws RepositoryException {
        StoredIndexInfo info = mRepository.getWrappedRepository()
            .storageFor(StoredIndexInfo.class).prepare();
        info.setIndexName(indexName);
        info.tryDelete();
    }

    @SuppressWarnings("unchecked")
    private void removeIndex(StorableIndex index) throws RepositoryException {
        Log log = LogFactory.getLog(IndexedStorage.class);
        if (log.isInfoEnabled()) {
            StringBuilder b = new StringBuilder();
            b.append("Removing index on ");
            b.append(getStorableType().getName());
            b.append(": ");
            try {
                index.appendTo(b);
            } catch (java.io.IOException e) {
                // Not gonna happen.
            }
            log.info(b.toString());
        }

        Class<? extends Storable> indexEntryClass =
            IndexEntryGenerator.getIndexAccess(index).getReferenceClass();

        Storage<?> indexEntryStorage;
        try {
            indexEntryStorage = mRepository.getIndexEntryStorageFor(indexEntryClass);
        } catch (Exception e) {
            // Assume it doesn't exist.
            unregisterIndex(index);
            return;
        }

        {
            // Doesn't completely remove the index, but it should free up space.

            double desiredSpeed = mRepository.getIndexRepairThrottle();
            Throttle throttle = desiredSpeed < 1.0 ? new Throttle(BUILD_THROTTLE_WINDOW) : null;

            if (throttle == null) {
                indexEntryStorage.truncate();
            } else {
                long totalDropped = 0;
                while (true) {
                    Transaction txn = mRepository.getWrappedRepository()
                        .enterTopTransaction(IsolationLevel.READ_COMMITTED);
                    txn.setForUpdate(true);
                    try {
                        Cursor<? extends Storable> cursor = indexEntryStorage.query().fetch();
                        if (!cursor.hasNext()) {
                            break;
                        }
                        int count = 0;
                        final long savedTotal = totalDropped;
                        boolean anyFailure = false;
                        try {
                            while (count++ < BUILD_BATCH_SIZE && cursor.hasNext()) {
                                if (cursor.next().tryDelete()) {
                                    totalDropped++;
                                } else {
                                    anyFailure = true;
                                }
                            }
                        } finally {
                            cursor.close();
                        }
                        txn.commit();
                        if (log.isInfoEnabled()) {
                            log.info("Removed " + totalDropped + " index entries");
                        }
                        if (anyFailure && totalDropped <= savedTotal) {
                            log.warn("No indexes removed in last batch. " +
                                     "Aborting index removal cleanup");
                            break;
                        }
                    } catch (FetchException e) {
                        throw e.toPersistException();
                    } finally {
                        txn.exit();
                    }

                    try {
                        throttle.throttle(desiredSpeed, BUILD_THROTTLE_SLEEP_PRECISION);
                    } catch (InterruptedException e) {
                        throw new RepositoryException("Index removal interrupted");
                    }
                }
            }
        }

        unregisterIndex(index);
    }
}