summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/repo/sleepycat/BDBRepositoryBuilder.java
blob: 7b2b31d409c1a99cbd3bd39cb82fc550f8039e12 (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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
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
958
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
/*
 * 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.sleepycat;

import java.lang.reflect.Constructor;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

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

import java.util.concurrent.atomic.AtomicReference;

import org.cojen.util.ThrowUnchecked;

import com.amazon.carbonado.Repository;
import com.amazon.carbonado.RepositoryException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.repo.indexed.IndexedRepositoryBuilder;

import com.amazon.carbonado.raw.CompressionType;
import com.amazon.carbonado.raw.CompressedStorableCodecFactory;
import com.amazon.carbonado.raw.StorableCodecFactory;

import com.amazon.carbonado.spi.AbstractRepositoryBuilder;

import com.amazon.carbonado.ConfigurationException;

/**
 * Builder and configuration options for BDBRepository.
 *
 * <pre>
 * BDBRepositoryBuilder builder = new BDBRepositoryBuilder();
 *
 * builder.setProduct("JE");
 * builder.setName("test");
 * builder.setEnvironmentHome("/tmp/testRepo");
 * builder.setTransactionWriteNoSync(true);
 *
 * Repository repo = builder.build();
 * </pre>
 *
 * <p>
 * The following extra capabilities are supported:
 * <ul>
 * <li>{@link com.amazon.carbonado.capability.IndexInfoCapability IndexInfoCapability}
 * <li>{@link com.amazon.carbonado.capability.StorableInfoCapability StorableInfoCapability}
 * <li>{@link com.amazon.carbonado.capability.ShutdownCapability ShutdownCapability}
 * <li>{@link com.amazon.carbonado.layout.LayoutCapability LayoutCapability}
 * <li>{@link com.amazon.carbonado.sequence.SequenceCapability SequenceCapability}
 * <li>{@link CheckpointCapability CheckpointCapability}
 * <li>{@link EnvironmentCapability EnvironmentCapability}
 * </ul>
 *
 * @author Brian S O'Neill
 * @author Vidya Iyer
 * @author Nicole Deflaux
 */
public final class BDBRepositoryBuilder extends AbstractRepositoryBuilder {

    private static final BDBProduct DEFAULT_PRODUCT = BDBProduct.JE;

    private static final int DEFAULT_CHECKPOINT_INTERVAL = 10000;

    private String mName;
    private boolean mIsMaster = true;
    private BDBProduct mProduct = DEFAULT_PRODUCT;
    private File mEnvHome;
    private File mDataHome;
    private String mSingleFileName;
    private Map<String, String> mFileNames;
    private boolean mIndexSupport = true;
    private boolean mIndexRepairEnabled = true;
    private double mIndexThrottle = 1.0;
    private boolean mReadOnly;
    private Long mCacheSize;
    private Integer mCachePercent;
    private Integer mLogRegionSize;
    private double mLockTimeout = 0.5;
    private Integer mMaxLocks;
    private double mTxnTimeout = 300.0;
    private boolean mTxnNoSync;
    private boolean mTxnWriteNoSync;
    private Integer mTxnMaxActive = 1000;
    private Boolean mDatabasesTransactional = null;
    private boolean mReverseSplitOff;
    private Map<Class<?>, Integer> mDatabasePageSizes;
    private boolean mPrivate;
    private boolean mMultiversion;
    private boolean mLogInMemory;
    private Integer mLogFileMaxSize;
    private boolean mInitializeLogging;
    private boolean mRunFullRecovery;
    private boolean mRunCheckpointer = true;
    private int mCheckpointInterval = DEFAULT_CHECKPOINT_INTERVAL;
    private int mCheckpointThresholdKB = 1024;
    private int mCheckpointThresholdMinutes = 1;
    private boolean mKeepOldLogFiles;
    private boolean mRunDeadlockDetector = true;
    private boolean mLockConflictDeadlockDetect = false;
    private Boolean mChecksumEnabled;
    private Object mInitialEnvConfig = null;
    private Object mInitialDBConfig = null;
    private StorableCodecFactory mStorableCodecFactory;
    private Runnable mPreShutdownHook;
    private Runnable mPostShutdownHook;
    private DatabaseHook mDatabaseHook;
    private Map<String, CompressionType> mCompressionMap;

    private BDBPanicHandler mPanicHandler;
    
    public BDBRepositoryBuilder() {
    }

    public Repository build(AtomicReference<Repository> rootRef) throws RepositoryException {
        if (mIndexSupport) {
            // Wrap BDBRepository with IndexedRepository.

            // Temporarily set to false to avoid infinite recursion.
            mIndexSupport = false;
            try {
                IndexedRepositoryBuilder ixBuilder = new IndexedRepositoryBuilder();
                ixBuilder.setWrappedRepository(this);
                ixBuilder.setMaster(isMaster());
                ixBuilder.setIndexRepairEnabled(mIndexRepairEnabled);
                ixBuilder.setIndexRepairThrottle(mIndexThrottle);
                return ixBuilder.build(rootRef);
            } finally {
                mIndexSupport = true;
            }
        }

        if (mStorableCodecFactory == null) {
            mStorableCodecFactory = new CompressedStorableCodecFactory(mCompressionMap);
        }

        assertReady();

        // Make environment directory if it doesn't exist.
        File homeFile = getEnvironmentHomeFile();
        if (!homeFile.exists()) {
            if (!homeFile.mkdirs()) {
                throw new RepositoryException
                    ("Unable to make environment home directory: " + homeFile);
            }
        }

        BDBRepository repo;

        try {
            repo = getRepositoryConstructor().newInstance(rootRef, this);
        } catch (Exception e) {
            ThrowUnchecked.fireFirstDeclaredCause(e, RepositoryException.class);
            // Not reached.
            return null;
        }

        rootRef.set(repo);
        return repo;
    }

    /**
     * Opens the BDB environment, checks if it is corrupt, and then closes it.
     * Only one process should open the environment for verification. Expect it
     * to take a long time.
     *
     * @param out optional stream to capture any verfication errors
     * @return true if environment passes verification
     */
    public boolean verify(PrintStream out) throws RepositoryException {
        final StorableCodecFactory codecFactory = mStorableCodecFactory;
        final String name = mName;
        final boolean readOnly = mReadOnly;
        final boolean runCheckpointer = mRunCheckpointer;
        final boolean runDeadlockDetector = mRunDeadlockDetector;
        final boolean lockConflictDeadlockDetect = mLockConflictDeadlockDetect;
        final boolean isPrivate = mPrivate;

        if (mName == null) {
            // Allow a dummy name for verification.
            mName = "BDB verification";
        }

        if (mStorableCodecFactory == null) {
            mStorableCodecFactory = new CompressedStorableCodecFactory(mCompressionMap);
        }

        mReadOnly = true;
        mRunCheckpointer = false;
        mRunDeadlockDetector = false;
        mLockConflictDeadlockDetect = false;

        try {
            assertReady();

            File homeFile = getEnvironmentHomeFile();
            if (!homeFile.exists()) {
                throw new RepositoryException
                    ("Environment home directory does not exist: " + homeFile);
            }

            AtomicReference<Repository> rootRef = new AtomicReference<Repository>();
            BDBRepository repo;

            try {
                repo = getRepositoryConstructor().newInstance(rootRef, this);
            } catch (Exception e) {
                ThrowUnchecked.fireFirstDeclaredCause(e, RepositoryException.class);
                // Not reached.
                return false;
            }

            rootRef.set(repo);

            try {
                return repo.verify(out);
            } catch (Exception e) {
                throw repo.toRepositoryException(e);
            } finally {
                repo.close();
            }
        } finally {
            mName = name;
            mStorableCodecFactory = codecFactory;
            mReadOnly = readOnly;
            mRunCheckpointer = runCheckpointer;
            mRunDeadlockDetector = runDeadlockDetector;
            mLockConflictDeadlockDetect = lockConflictDeadlockDetect;
        }
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public boolean isMaster() {
        return mIsMaster;
    }

    public void setMaster(boolean b) {
        mIsMaster = b;
    }

    /**
     * Sets the BDB product to use, which defaults to JE. Also supported is DB
     * and DB_HA. If not supported, an IllegalArgumentException is thrown.
     */
    public void setProduct(String product) {
        mProduct = product == null ? DEFAULT_PRODUCT : BDBProduct.forString(product);
    }

    /**
     * Returns the BDB product to use, which is JE by default.
     */
    public String getProduct() {
        return mProduct.toString();
    }

    /**
     * Sets the BDB product to use, which defaults to JE.
     */
    public void setBDBProduct(BDBProduct product) {
        mProduct = product == null ? DEFAULT_PRODUCT : product;
    }

    /**
     * Returns the BDB product to use, which is JE by default.
     */
    public BDBProduct getBDBProduct() {
        return mProduct;
    }

    /**
     * Sets the repository environment home directory, which is required.
     */
    public void setEnvironmentHomeFile(File envHome) {
        try {
            // Switch to canonical for more detailed error messages.
            envHome = envHome.getCanonicalFile();
        } catch (IOException e) {
        }
        mEnvHome = envHome;
    }

    /**
     * Returns the repository environment home directory.
     */
    public File getEnvironmentHomeFile() {
        return mEnvHome;
    }

    /**
     * Sets the repository environment home directory, which is required.
     *
     * @throws RepositoryException if environment home is not valid
     */
    public void setEnvironmentHome(String envHome) {
        setEnvironmentHomeFile(new File(envHome));
    }

    /**
     * Returns the repository environment home directory.
     */
    public String getEnvironmentHome() {
        return mEnvHome.getPath();
    }

    /**
     * By default, data files are stored relative to the environment home. Call
     * this method to override. For BDBRepositories that are log files only,
     * this configuration is ignored.
     */
    public void setDataHomeFile(File dir) {
        if (dir != null) {
            try {
                // Switch to canonical for more detailed error messages.
                dir = dir.getCanonicalFile();
            } catch (IOException e) {
            }
        }
        mDataHome = dir;
    }

    /**
     * Returns the optional directory to store data files. Returns null if data
     * files are expected to be relative to the environment home.
     */
    public File getDataHomeFile() {
        if (mDataHome == null) {
            return getEnvironmentHomeFile();
        }
        return mDataHome;
    }

    /**
     * By default, data files are stored relative to the environment home. Call
     * this method to override. For BDBRepositories that are log files only,
     * this configuration is ignored.
     */
    public void setDataHome(String dir) {
        if (dir == null) {
            mDataHome = null;
        } else {
            setDataHomeFile(new File(dir));
        }
    }

    /**
     * Returns the directory to store data files.
     */
    public String getDataHome() {
        return getDataHomeFile().getPath();
    }

    /**
     * Specify that all BDB databases should reside in one file, except for log
     * files and caches. The filename is relative to the environment home,
     * unless data directories have been specified. For BDBRepositories that
     * are log files only, this configuration is ignored.
     *
     * <p>Note: When setting this option, the storable codec factory must also
     * be changed, since the default storable codec factory is unable to
     * distinguish storable types that reside in a single database file. Call
     * setFileName instead to use built-in BDB feature for supporting multiple
     * databases in one file.
     */
    public void setSingleFileName(String filename) {
        mSingleFileName = filename;
        mFileNames = null;
    }

    /**
     * Returns the single file that all BDB databases should reside in.
     */
    public String getSingleFileName() {
        return mSingleFileName;
    }

    /**
     * Specify the file that a BDB database should reside in, except for log
     * files and caches. The filename is relative to the environment home,
     * unless data directories have been specified. For BDBRepositories that
     * are log files only, this configuration is ignored.
     *
     * @param filename BDB database filename
     * @param typeName type to store in file; if null, the file is used by default
     * for all types
     */
    public void setFileName(String filename, String typeName) {
        mSingleFileName = null;
        if (mFileNames == null) {
            mFileNames = new HashMap<String, String>();
        }
        mFileNames.put(typeName, filename);
    }

    Map<String, String> getFileNameMap() {
        if (mFileNames == null) {
            return null;
        }
        return new HashMap<String, String>(mFileNames);
    }

    /**
     * By default, user specified indexes are supported. Pass false to disable
     * this, and no indexes will be built. Another consequence of this option
     * is that no unique constraint checks will be applied to alternate keys.
     */
    public void setIndexSupport(boolean indexSupport) {
        mIndexSupport = indexSupport;
    }

    /**
     * Returns true if indexes are supported, which is true by default.
     */
    public boolean getIndexSupport() {
        return mIndexSupport;
    }

    /**
     * @see #setIndexRepairEnabled(boolean)
     *
     * @return true by default
     */
    public boolean isIndexRepairEnabled() {
        return mIndexRepairEnabled;
    }

    /**
     * By default, index repair is enabled. In this mode, the first time a
     * Storable type is used, new indexes are populated and old indexes are
     * removed. Until finished, access to the Storable is blocked.
     *
     * <p>When index repair is disabled, the Storable is immediately
     * available. This does have consequences, however. The set of indexes
     * available for queries is defined by the <i>intersection</i> of the old
     * and new index sets. The set of indexes that are kept up-to-date is
     * defined by the <i>union</i> of the old and new index sets.
     *
     * <p>While index repair is disabled, another process can safely repair the
     * indexes in the background. When it is complete, index repair can be
     * enabled for this repository too.
     */
    public void setIndexRepairEnabled(boolean enabled) {
        mIndexRepairEnabled = enabled;
    }

    /**
     * Returns the throttle parameter used when indexes are added, dropped or
     * bulk repaired. By default this value is 1.0, or maximum speed.
     */
    public double getIndexRepairThrottle() {
        return mIndexThrottle;
    }

    /**
     * Sets the throttle parameter used when indexes are added, dropped or bulk
     * repaired. By default this value is 1.0, or maximum speed.
     *
     * @param desiredSpeed 1.0 = perform work at full speed,
     * 0.5 = perform work at half speed, 0.0 = fully suspend work
     */
    public void setIndexRepairThrottle(double desiredSpeed) {
        mIndexThrottle = desiredSpeed;
    }

    /**
     * Sets the repository to read-only mode. By default, repository is opened
     * for reads and writes.
     */
    public void setReadOnly(boolean readOnly) {
        mReadOnly = readOnly;
    }

    /**
     * Returns true if repository should be opened read-only.
     */
    public boolean getReadOnly() {
        return mReadOnly;
    }

    /**
     * Set the repository cache size, in bytes. Actual BDB implementation will
     * select a suitable default if this is not set.
     */
    public void setCacheSize(long cacheSize) {
        mCacheSize = cacheSize;
    }

    /**
     * Set the repository cache size, in bytes. Actual BDB implementation will
     * select a suitable default if this is not set.
     *
     * @param cacheSize cache size to use, or null for default
     */
    public void setCacheSize(Long cacheSize) {
        mCacheSize = cacheSize;
    }

    /**
     * Returns the repository cache size, or null if default should be
     * selected.
     */
    public Long getCacheSize() {
        return mCacheSize;
    }

    /**
     * Set the repository log region size, in bytes.
     */
    public void setLogRegionSize(int logRegionSize) {
        mLogRegionSize = logRegionSize;
    }

    /**
     * Set the repository log region size, in bytes.
     */
    public void setLogRegionSize(Integer logRegionSize) {
        mLogRegionSize = logRegionSize;
    }

    /**
     * Returns the repository log region size, or null if the default
     * should be selected.
     */
    public Integer getLogRegionSize() {
        return mLogRegionSize;
    }

    /**
     * Set the percent of JVM heap used by the repository cache. Actual
     * BDB implementation will select a suitable default if this is not
     * set. This is overridden by setting an explicit cacheSize.
     */
    public void setCachePercent(int cachePercent) {
        mCachePercent = cachePercent;
    }

    /**
     * Set the percent of JVM heap used by the repository cache. Actual
     * BDB implementation will select a suitable default if this is not
     * set. This is overridden by setting an explicit cacheSize.
     *
     * @param cachePercent percent of JVM heap to use, or null for default
     */
    public void setCachePercent(Integer cachePercent) {
        mCachePercent = cachePercent;
    }

    /**
     * Returns the percent of JVM heap used by the repository cache, or
     * null if default should be selected.
     */
    public Integer getCachePercent() {
        return mCachePercent;
    }

    /**
     * Set the lock timeout, in seconds. Default value is 0.5 seconds.
     */
    public void setLockTimeout(double lockTimeout) {
        mLockTimeout = lockTimeout;
    }

    /**
     * Returns the lock timeout, in seconds.
     */
    public double getLockTimeout() {
        return mLockTimeout;
    }

    /**
     * Returns the lock timeout, in microseconds, limited to max long value.
     */
    public long getLockTimeoutInMicroseconds() {
        return inMicros(mLockTimeout);
    }

    public void setMaxLocks(Integer max) {
        mMaxLocks = max;
    }

    public Integer getMaxLocks() {
        return mMaxLocks;
    }

    /**
     * Set the transaction timeout, in seconds. Default value is 300 seconds.
     */
    public void setTransactionTimeout(double txnTimeout) {
        mTxnTimeout = txnTimeout;
    }

    /**
     * Returns the repository transaction timeout, in seconds.
     */
    public double getTransactionTimeout() {
        return mTxnTimeout;
    }

    /**
     * Returns the repository transaction timeout, in microseconds, limited to
     * max long value.
     */
    public long getTransactionTimeoutInMicroseconds() {
        return inMicros(mTxnTimeout);
    }

    /**
     * When true, commits are not immediately written or flushed to disk. This
     * improves performance, but there is a chance of losing the most recent
     * commits if the process is killed or if the machine crashes.
     */
    public void setTransactionNoSync(boolean noSync) {
        mTxnNoSync = noSync;
    }

    /**
     * Returns true if transactions are not written or flushed to disk.
     */
    public boolean getTransactionNoSync() {
        return mTxnNoSync;
    }

    /**
     * When true, commits are written, but they are not flushed to disk. This
     * improves performance, but there is a chance of losing the most recent
     * commits if the machine crashes.
     */
    public void setTransactionWriteNoSync(boolean noSync) {
        mTxnWriteNoSync = noSync;
    }

    /**
     * Returns true if transactions are not flushed to disk.
     */
    public boolean getTransactionWriteNoSync() {
        return mTxnWriteNoSync;
    }

    /**
     * Set the maximum number of concurrent transactions, or pass null to use
     * the default. This setting has no effect for BDB-JE.
     */
    public void setTransactionMaxActive(Integer max) {
        mTxnMaxActive = max;
    }

    /**
     * Returns the maximum number of concurrent transactions, or null if the
     * default is used.
     */
    public Integer getTransactionMaxActive() {
        return mTxnMaxActive;
    }

    /**
     * When true, allows databases to be transactional. This setting affects
     * the databases, not the environment. If this is not explicitly set, the
     * environment getTransactional is used.
     */
    public void setDatabasesTransactional(Boolean transactional) {
        mDatabasesTransactional = transactional;
    }

    /**
     * Returns true if the databases are configured to be transactional,
     * false if configured to not be transactional, null if this override was never set
     */
    public Boolean getDatabasesTransactional() {
        return mDatabasesTransactional;
    }

    /**
     * Pass true to disable reverse split of B-tree nodes to reduce deadlocks.
     * This setting has no effect for BDB-JE.
     */
    public void setReverseSplitOff(boolean off) {
        mReverseSplitOff = off;
    }

    public boolean isReverseSplitOff() {
        return mReverseSplitOff;
    }

    /**
     * Sets the desired page size for a given type. If not specified, the page
     * size applies to all types.
     */
    public void setDatabasePageSize(Integer bytes, Class<? extends Storable> type) {
        if (mDatabasePageSizes == null) {
            mDatabasePageSizes = new HashMap<Class<?>, Integer>();
        }
        mDatabasePageSizes.put(type, bytes);
    }

    Map<Class<?>, Integer> getDatabasePagesMap() {
        if (mDatabasePageSizes == null) {
            return null;
        }
        return new HashMap<Class<?>, Integer>(mDatabasePageSizes);
    }

    /**
     * When true, BDB environment cannot be shared by other processes, and
     * region files are not created. By default, environment is shared, if
     * supported.
     */
    public void setPrivate(boolean b) {
        mPrivate = b;
    }

    /**
     * Returns true if BDB environment is private. By default, environment is
     * shared, if supported.
     */
    public boolean isPrivate() {
        return mPrivate;
    }

    /**
     * Set true to enable multiversion concurrency control (MVCC) on BDB
     * environment. This enables snapshot isolation, and is it is not supported
     * by all BDB products and versions.
     */
    public void setMultiversion(boolean multiversion) {
        mMultiversion = multiversion;
    }

    /**
     * Returns false by default because multiversion concurrency control (MVCC)
     * is not enabled.
     */
    public boolean isMultiversion() {
        return mMultiversion;
    }

    /**
     * Set true to store transaction logs in memory only instead of persistent
     * storage. For BDB products which are entirely log based, no records are
     * ever persisted.
     */
    public void setLogInMemory(boolean logInMemory) {
        mLogInMemory = logInMemory;
    }

    /**
     * Returns false by default, indicating that transaction logs are persisted.
     */
    public boolean getLogInMemory() {
        return mLogInMemory;
    }

    /**
     * Set the maximum transaction log file size for the BDB environment.
     */
    public void setLogFileMaxSize(Integer sizeInBytes) {
        mLogFileMaxSize = sizeInBytes;
    }

    /**
     * Returns null if default size will be used.
     */
    public Integer getLogFileMaxSize() {
        return mLogFileMaxSize;
    }

    /**
     * Ensure the transaction logging sub-system is initialized, which is
     * usually implied.
     */
    public void setInitializeLogging(boolean b) {
        mInitializeLogging = b;
    }

    public boolean getInitializeLogging() {
        return mInitializeLogging;
    }

    /**
     * Pass true to override the default and run a full (catastrophic) recovery
     * when environment is opened. This setting has no effect for BDB-JE.
     */
    public void setRunFullRecovery(boolean runRecovery) {
        mRunFullRecovery = runRecovery;
    }

    /**
     * Returns true if a full (catastrophic) recovery should be performed when
     * environment is opened.
     */
    public boolean getRunFullRecovery() {
        return mRunFullRecovery;
    }

    /**
     * Disable automatic checkpointing of database if another process is
     * responsible for that. The false setting is implied for read-only
     * databases.
     */
    public void setRunCheckpointer(boolean runCheckpointer) {
        mRunCheckpointer = runCheckpointer;
    }

    /**
     * Returns true if checkpointer is run automatically.
     */
    public boolean getRunCheckpointer() {
        return mRunCheckpointer;
    }

    /**
     * Set the interval to run checkpoints. This setting is ignored if the
     * checkpointer is not configured to run.
     *
     * @param intervalMillis interval between checkpoints, in milliseconds
     */
    public void setCheckpointInterval(int intervalMillis) {
        mCheckpointInterval = intervalMillis;
    }

    /**
     * @return interval between checkpoints, in milliseconds
     */
    public int getCheckpointInterval() {
        return mCheckpointInterval;
    }

    /**
     * Set the size threshold to run checkpoints. This setting is ignored if
     * the checkpointer is not configured to run. Default value is 1024 KB.
     *
     * <p>Checkpoint threshold is only used by Carbonado's built-in
     * checkpointer, and is ignored when using BDB-JE.
     *
     * @param thresholdKB run checkpoint if at least this many kilobytes in log
     */
    public void setCheckpointThresholdKB(int thresholdKB) {
        mCheckpointThresholdKB = thresholdKB;
    }

    /**
     * @return run checkpoint if at least this many kilobytes in log
     */
    public int getCheckpointThresholdKB() {
        return mCheckpointThresholdKB;
    }

    /**
     * Set the time threshold to run checkpoints. This setting is ignored if
     * the checkpointer is not configured to run. Default value is 1 minute.
     *
     * <p>Checkpoint threshold is only used by Carbonado's built-in
     * checkpointer, and is ignored when using BDB-JE.
     *
     * @param thresholdMinutes run checkpoint if at least this many minutes
     * passed since last checkpoint
     */
    public void setCheckpointThresholdMinutes(int thresholdMinutes) {
        mCheckpointThresholdMinutes = thresholdMinutes;
    }

    /**
     * @return run checkpoint if at least this many minutes passed since last
     * checkpoint
     */
    public int getCheckpointThresholdMinutes() {
        return mCheckpointThresholdMinutes;
    }

    /**
     * By default, transaction log files are deleted when no longer needed.
     * Keeping log files can be used for incremental backups or for diagnosing
     * problems. If using BDB-JE, old log files are renamed with a ".del"
     * extension. If using BDB-core, the db_archive utility is required for
     * identifying old log files.
     */
    public void setKeepOldLogFiles(boolean keep) {
        mKeepOldLogFiles = keep;
    }

    /**
     * Returns false by default.
     */
    public boolean getKeepOldLogFiles() {
        return mKeepOldLogFiles;
    }

    /**
     * Disable automatic deadlock detection of database if another thread is
     * responsible for that.
     */
    public void setRunDeadlockDetector(boolean runDeadlockDetector) {
        mRunDeadlockDetector = runDeadlockDetector;
    }

    /**
     * Returns true if deadlock detector is configured to run.
     */
    public boolean getRunDeadlockDetector() {
        return mRunDeadlockDetector;
    }

    /**
     * Enable deadlock detection whenever a lock conflict occurs. Default is
     * off, and it has no effect for BDB-JE.
     */
    public void setLockConflictDeadlockDetectMode(boolean b) {
        mLockConflictDeadlockDetect = b;
    }

    /**
     * Returns true if deadlock detection is run whenever a lock conflict occurs.
     */
    public boolean getLockConflictDeadlockDetectMode() {
        return mLockConflictDeadlockDetect;
    }

    /**
     * When true, enable checksum verification of pages read into the cache
     * from the backing filestore. By default checksum is enabled for BDB-JE,
     * and disabled for BDB-C.
     */
    public void setChecksumEnabled(Boolean checksumEnabled) {
        mChecksumEnabled = checksumEnabled;
    }

    /**
     * Returns true if checksum verification is enabled. Returns null if the
     * BDB default is used.
     */
    public Boolean getChecksumEnabled() {
        return mChecksumEnabled;
    }

    /**
     * Optionally set the BDB specific environment configuration to
     * use. The builder will verify that needed configuration values are set.
     */
    public void setInitialEnvironmentConfig(Object envConfig) {
        mInitialEnvConfig = envConfig;
    }

    /**
     * Returns the optional BDB specific environment configuration to use.
     */
    public Object getInitialEnvironmentConfig() {
        return mInitialEnvConfig;
    }

    /**
     * Optionally set the BDB specific database configuration to use
     * for all databases created. The storage will verify that needed
     * configuration values are set.
     */
    public void setInitialDatabaseConfig(Object dbConfig) {
        mInitialDBConfig = dbConfig;
    }

    /**
     * Returns the optional BDB specific database configuration to use
     * for all databases created.
     */
    public Object getInitialDatabaseConfig() {
        return mInitialDBConfig;
    }

    /**
     * Override the default storable codec factory.
     */
    public void setStorableCodecFactory(StorableCodecFactory factory) {
        mStorableCodecFactory = factory;
    }

    /**
     * Returns the storable codec factory used.
     */
    public StorableCodecFactory getStorableCodecFactory() {
        return mStorableCodecFactory;
    }

    /**
     * Sets a callback to be invoked before the repository has finished running
     * its own shutdown hooks. This method is also invoked when repository is
     * manually closed.
     */
    public void setPreShutdownHook(Runnable hook) {
        mPreShutdownHook = hook;
    }

    /**
     * Returns the custom shutdown hook that runs before the repository has
     * finished running its own shutdown hooks, or null if none.
     */
    public Runnable getPreShutdownHook() {
        return mPreShutdownHook;
    }

    /**
     * Sets a callback to be invoked after repository has finished running its
     * own shutdown hooks. This method is also invoked when repository is
     * manually closed.
     */
    public void setShutdownHook(Runnable hook) {
        mPostShutdownHook = hook;
    }

    /**
     * Returns the custom shutdown hook that runs after the repository has
     * finished running its own shutdown hooks, or null if none.
     */
    public Runnable getShutdownHook() {
        return mPostShutdownHook;
    }

    /**
     * Sets a hook to be called whenever a database is opened.
     */
    public void setDatabaseHook(DatabaseHook hook) {
        mDatabaseHook = hook;
    }

    /**
     * Returns the custom open database hook, or null if none.
     */
    public DatabaseHook getDatabaseHook() {
        return mDatabaseHook;
    }

    /**
     * Set the compressor for the given class, overriding a custom StorableCodecFactory.

     * @param type Storable to compress. 
     * @param compressionType String representation of type of
     * compression. Available options are "NONE" for no compression or "GZIP"
     * for gzip compression
     */
    public void setCompressor(String type, String compressionType) {
        mStorableCodecFactory = null;
        compressionType = compressionType.toUpperCase();
        if (mCompressionMap == null) {
            mCompressionMap = new HashMap<String, CompressionType>();
        }
        CompressionType compressionEnum = CompressionType.valueOf(compressionType);
        if (compressionEnum != null) {
            mCompressionMap.put(type, compressionEnum);
        }
    }

    /**
     * Return the compressor used for the given storable.
     * @param type Storable to compress
     * @return String representation of the type of compression used. Available options are "NONE"
     * for no compression and "GZIP" for gzip compression.
     */
    public String getCompressor(String type) {
        if (mCompressionMap == null) {
            return null;
        }

        return mCompressionMap.get(type).toString();
    }
    
    /**
     * Set the handler to call if the database panics.
     * 
     * @param handler
     */
    public void setPanicHandler(BDBPanicHandler handler) {
        mPanicHandler = handler;
    }
    
    /**
     * Return the panic handler to call if the database panics.
     * 
     * @return The BDBPanicHandler or null if unset.
     */
    public BDBPanicHandler getPanicHandler() {
        return mPanicHandler;
    }
    
    private long inMicros(double seconds) {
        if (seconds >= Long.MAX_VALUE) {
            return Long.MAX_VALUE;
        }
        if (seconds <= 0 || Double.isNaN(seconds)) {
            return 0L;
        }
        return (long) (seconds * 1000000);
    }

    @Override
    public void errorCheck(Collection<String> messages) throws ConfigurationException {
        super.errorCheck(messages);

        checkClass: {
            Exception error;
            try {
                getRepositoryConstructor();
                break checkClass;
            } catch (ClassCastException e) {
                error = e;
            } catch (ClassNotFoundException e) {
                error = e;
            } catch (NoSuchMethodException e) {
                error = e;
            }
            messages.add("BDB product \"" + getProduct() + "\" not supported: " + error);
        }

        File envHome = getEnvironmentHomeFile();
        if (envHome == null) {
            messages.add("environmentHome missing");
        } else {
            if (envHome.exists() && !envHome.isDirectory()) {
                messages.add("environment home is not a directory: " + envHome);
            }
        }
    }

    /**
     * Looks up appropriate repository via reflection, whose name is derived
     * from the BDB product string.
     */
    @SuppressWarnings("unchecked")
    private Constructor<BDBRepository> getRepositoryConstructor()
        throws ClassCastException, ClassNotFoundException, NoSuchMethodException
    {
        String packageName;
        {
            String thisClassName = getClass().getName();
            packageName = thisClassName.substring(0, thisClassName.lastIndexOf('.'));
        }
        String className = packageName + '.' + getBDBProduct().name() + "_Repository";
        Class repoClass = Class.forName(className);
        if (BDBRepository.class.isAssignableFrom(repoClass)) {
            return repoClass.getDeclaredConstructor
                (AtomicReference.class, BDBRepositoryBuilder.class);
        }
        throw new ClassCastException("Not an instance of BDBRepository: " + repoClass.getName());
    }

    public static interface DatabaseHook {
        /**
         * Returns an appropriate database name for the given type. Simply
         * return the type name as-is to support default behavior.
         */
        String databaseName(String typeName);

        /**
         * Called right before database is opened.
         *
         * @param db reference to database or config - actual type depends on BDB
         * implementation.
         */
        void prepareForOpening(Object db) throws RepositoryException;
    }
}