/
OAbstractPaginatedStorage.java
4595 lines (3671 loc) · 158 KB
/
OAbstractPaginatedStorage.java
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
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * 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.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.storage.impl.local;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import com.orientechnologies.common.concur.lock.OLockManager;
import com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException;
import com.orientechnologies.common.directmemory.ODirectMemoryPointer;
import com.orientechnologies.common.exception.OErrorCode;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.io.OIOUtils;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.common.serialization.types.OByteSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.common.types.OModifiableBoolean;
import com.orientechnologies.common.util.OCallable;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.common.util.OPair;
import com.orientechnologies.orient.core.OOrientShutdownListener;
import com.orientechnologies.orient.core.OOrientStartupListener;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.command.OCommandExecutor;
import com.orientechnologies.orient.core.command.OCommandManager;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.config.OStorageClusterConfiguration;
import com.orientechnologies.orient.core.config.OStorageConfiguration;
import com.orientechnologies.orient.core.config.OStoragePaginatedClusterConfiguration;
import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseListener;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManagerShared;
import com.orientechnologies.orient.core.exception.OBackupInProgressException;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.exception.OFastConcurrentModificationException;
import com.orientechnologies.orient.core.exception.OLowDiskSpaceException;
import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.OIndexCursor;
import com.orientechnologies.orient.core.index.OIndexDefinition;
import com.orientechnologies.orient.core.index.OIndexEngine;
import com.orientechnologies.orient.core.index.OIndexException;
import com.orientechnologies.orient.core.index.OIndexKeyCursor;
import com.orientechnologies.orient.core.index.OIndexes;
import com.orientechnologies.orient.core.index.ORuntimeKeyIndexDefinition;
import com.orientechnologies.orient.core.metadata.OMetadataDefault;
import com.orientechnologies.orient.core.metadata.OMetadataInternal;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.metadata.security.OToken;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordVersionHelper;
import com.orientechnologies.orient.core.record.impl.ODirtyManager;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.record.impl.ODocumentInternal;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OCompositeKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OSimpleKeySerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OIdentifiableStorage;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.ORecordMetadata;
import com.orientechnologies.orient.core.storage.OStorageAbstract;
import com.orientechnologies.orient.core.storage.OStorageOperationResult;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OCachePointer;
import com.orientechnologies.orient.core.storage.cache.OPageDataVerificationError;
import com.orientechnologies.orient.core.storage.cache.OReadCache;
import com.orientechnologies.orient.core.storage.cache.OWriteCache;
import com.orientechnologies.orient.core.storage.cache.local.OWOWCache;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OOfflineCluster;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OOfflineClusterException;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OPaginatedCluster;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordOperationMetadata;
import com.orientechnologies.orient.core.storage.impl.local.paginated.ORecordSerializationContext;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OStorageTransaction;
import com.orientechnologies.orient.core.storage.impl.local.paginated.atomicoperations.OAtomicOperationsManager;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.*;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OSessionStoragePerformanceStatistic;
import com.orientechnologies.orient.core.storage.impl.local.statistic.OStoragePerformanceStatistic;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransactionAbstract;
import com.orientechnologies.orient.core.tx.OTxListener;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @author Andrey Lomakin
* @since 28.03.13
*/
public abstract class OAbstractPaginatedStorage extends OStorageAbstract implements OLowDiskSpaceListener,
OFullCheckpointRequestListener, OIdentifiableStorage, OOrientStartupListener, OOrientShutdownListener {
public static final String IBU_EXTENSION = ".ibu";
public static final String CONF_ENTRY_NAME = "database.ocf";
public static final String INCREMENTAL_BACKUP_DATEFORMAT = "yyyy-MM-dd-HH-mm-ss";
private static final int RECORD_LOCK_TIMEOUT = OGlobalConfiguration.STORAGE_RECORD_LOCK_TIMEOUT.getValueAsInteger();
private final OLockManager<ORID> lockManager;
private final String PROFILER_CREATE_RECORD;
private final String PROFILER_READ_RECORD;
private final String PROFILER_UPDATE_RECORD;
private final String PROFILER_DELETE_RECORD;
private final Map<String, OCluster> clusterMap = new HashMap<String, OCluster>();
private List<OCluster> clusters = new ArrayList<OCluster>();
private volatile ThreadLocal<OStorageTransaction> transaction = new ThreadLocal<OStorageTransaction>();
private final AtomicBoolean checkpointInProgress = new AtomicBoolean();
private final OSBTreeCollectionManagerShared sbTreeCollectionManager;
protected volatile OWriteAheadLog writeAheadLog;
private OStorageRecoverListener recoverListener;
protected volatile OReadCache readCache;
protected volatile OWriteCache writeCache;
private volatile ORecordConflictStrategy recordConflictStrategy = Orient.instance().getRecordConflictStrategy()
.newInstanceOfDefaultClass();
private volatile int defaultClusterId = -1;
private volatile OAtomicOperationsManager atomicOperationsManager;
private volatile boolean wereNonTxOperationsPerformedInPreviousOpen = false;
private volatile OLowDiskSpaceInformation lowDiskSpace = null;
private volatile boolean checkpointRequest = false;
private final int id;
private final AtomicBoolean backupInProgress = new AtomicBoolean(false);
private Map<String, OIndexEngine> indexEngineNameMap = new HashMap<String, OIndexEngine>();
private List<OIndexEngine> indexEngines = new ArrayList<OIndexEngine>();
private boolean wereDataRestoredAfterOpen = false;
private volatile OStoragePerformanceStatistic storagePerformanceStatistic;
public OAbstractPaginatedStorage(String name, String filePath, String mode, int id) {
super(name, filePath, mode, OGlobalConfiguration.STORAGE_LOCK_TIMEOUT.getValueAsInteger());
this.id = id;
lockManager = new ORIDOLockManager();
PROFILER_CREATE_RECORD = "db." + this.name + ".createRecord";
PROFILER_READ_RECORD = "db." + this.name + ".readRecord";
PROFILER_UPDATE_RECORD = "db." + this.name + ".updateRecord";
PROFILER_DELETE_RECORD = "db." + this.name + ".deleteRecord";
sbTreeCollectionManager = new OSBTreeCollectionManagerShared(this);
}
public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iProperties) {
stateLock.acquireReadLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
return;
} finally {
stateLock.releaseReadLock();
}
stateLock.acquireWriteLock();
try {
if (status == STATUS.OPEN)
// ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS
// REUSED
return;
if (!exists())
throw new OStorageException("Cannot open the storage '" + name + "' because it does not exist in path: " + url);
configuration.load(iProperties);
componentsFactory = new OCurrentStorageComponentsFactory(configuration);
preOpenSteps();
storagePerformanceStatistic = new OStoragePerformanceStatistic(
OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, name, id);
initWalAndDiskCache();
atomicOperationsManager = new OAtomicOperationsManager(this);
try {
atomicOperationsManager.registerMBean();
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for atomic operations manager cannot be registered", e);
}
recoverIfNeeded();
openClusters();
openIndexes();
if (OGlobalConfiguration.STORAGE_MAKE_FULL_CHECKPOINT_AFTER_OPEN.getValueAsBoolean())
makeFullCheckpoint();
writeCache.startFuzzyCheckpoints();
try {
storagePerformanceStatistic.registerMBean();
} catch (Exception e) {
OLogManager.instance().error(this, "Error during of registering of MBean for storage performance statistic", e);
}
status = STATUS.OPEN;
} catch (Exception e) {
for (OCluster c : clusters) {
try {
c.close(false);
} catch (IOException e1) {
OLogManager.instance().error(this, "Cannot close cluster after exception on open");
}
}
try {
status = STATUS.OPEN;
doClose(true, false);
} catch (RuntimeException re) {
OLogManager.instance().error(this, "Error during storage close", e);
}
status = STATUS.CLOSED;
throw OException.wrapException(new OStorageException("Cannot open local storage '" + url + "' with mode=" + mode), e);
} finally {
stateLock.releaseWriteLock();
}
}
protected void openIndexes() {
OCurrentStorageComponentsFactory cf = componentsFactory;
if (cf == null)
throw new OStorageException("Stroage " + name + " is not properly initialized");
final Set<String> indexNames = configuration.indexEngines();
for (String indexName : indexNames) {
final OStorageConfiguration.IndexEngineData engineData = configuration.getIndexEngine(indexName);
final OIndexEngine engine = OIndexes.createIndexEngine(engineData.getName(), engineData.getAlgorithm(),
engineData.getIndexType(), engineData.getDurableInNonTxMode(), this, engineData.getVersion(),
engineData.getEngineProperties());
try {
engine.load(engineData.getName(), cf.binarySerializerFactory.getObjectSerializer(engineData.getValueSerializerId()),
engineData.isAutomatic(), cf.binarySerializerFactory.getObjectSerializer(engineData.getKeySerializedId()),
engineData.getKeyTypes(), engineData.isNullValuesSupport(), engineData.getKeySize());
indexEngineNameMap.put(engineData.getName().toLowerCase(configuration.getLocaleInstance()), engine);
indexEngines.add(engine);
} catch (RuntimeException e) {
OLogManager.instance().error(this,
"Index " + engineData.getName() + " can not be created and will be removed from configuration");
engine.deleteWithoutLoad(engineData.getName());
}
}
}
protected void openClusters() throws IOException {
// OPEN BASIC SEGMENTS
int pos;
addDefaultClusters();
// REGISTER CLUSTER
for (int i = 0; i < configuration.clusters.size(); ++i) {
final OStorageClusterConfiguration clusterConfig = configuration.clusters.get(i);
if (clusterConfig != null) {
pos = createClusterFromConfig(clusterConfig);
try {
if (pos == -1) {
clusters.get(i).open();
} else {
if (clusterConfig.getName().equals(CLUSTER_DEFAULT_NAME))
defaultClusterId = pos;
clusters.get(pos).open();
}
} catch (FileNotFoundException e) {
OLogManager.instance().warn(this, "Error on loading cluster '" + clusters.get(i).getName() + "' (" + i
+ "): file not found. It will be excluded from current database '" + getName() + "'.");
clusterMap.remove(clusters.get(i).getName().toLowerCase(configuration.getLocaleInstance()));
setCluster(i, null);
}
} else {
setCluster(i, null);
}
}
}
public void open(final OToken iToken, final Map<String, Object> iProperties) {
open(iToken.getUserName(), "", iProperties);
}
public void create(final Map<String, Object> iProperties) {
stateLock.acquireWriteLock();
try {
if (status != STATUS.CLOSED)
throw new OStorageException("Cannot create new storage '" + getURL() + "' because it is not closed");
if (exists())
throw new OStorageException("Cannot create new storage '" + getURL() + "' because it already exists");
if (!configuration.getContextConfiguration().getContextKeys()
.contains(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getKey())) {
final String compression = iProperties != null
? (String) iProperties
.get(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getKey().toLowerCase(configuration.getLocaleInstance()))
: null;
if (compression != null)
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD, compression);
else
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD,
OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getValue());
}
if (!configuration.getContextConfiguration().getContextKeys()
.contains(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.getKey())) {
final String encryption = iProperties != null ? (String) iProperties
.get(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.getKey().toLowerCase(configuration.getLocaleInstance())) : null;
if (encryption != null)
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD, encryption);
else
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD,
OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.getValue());
}
// SAVE COMPRESSION OPTIONS IF ANY. THIS IS USED FOR ENCRYPTION AT REST WHERE IN THE 'STORAGE_ENCRYPTION_KEY' IS STORED
// THE KEY
final String encryptionKey = iProperties != null ? (String) iProperties
.get(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.getKey().toLowerCase(configuration.getLocaleInstance())) : null;
if (encryptionKey != null)
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY, encryptionKey);
else
configuration.getContextConfiguration().setValue(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY,
OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.getValue());
componentsFactory = new OCurrentStorageComponentsFactory(configuration);
storagePerformanceStatistic = new OStoragePerformanceStatistic(
OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024, name, id);
initWalAndDiskCache();
atomicOperationsManager = new OAtomicOperationsManager(this);
try {
atomicOperationsManager.registerMBean();
} catch (Exception e) {
OLogManager.instance().error(this, "MBean for atomic operations manager cannot be registered", e);
}
preCreateSteps();
status = STATUS.OPEN;
// ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF
doAddCluster(OMetadataDefault.CLUSTER_INTERNAL_NAME, null);
configuration.create();
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_INDEX_NAME, null);
// ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF
// INDEXING
doAddCluster(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME, null);
// ADD THE DEFAULT CLUSTER
defaultClusterId = doAddCluster(CLUSTER_DEFAULT_NAME, null);
clearStorageDirty();
if (OGlobalConfiguration.STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE.getValueAsBoolean())
makeFullCheckpoint();
writeCache.startFuzzyCheckpoints();
postCreateSteps();
} catch (OStorageException e) {
close();
throw e;
} catch (IOException e) {
close();
throw OException.wrapException(new OStorageException("Error on creation of storage '" + name + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public void onShutdown() {
transaction = null;
}
@Override
public void onStartup() {
if (transaction == null)
transaction = new ThreadLocal<OStorageTransaction>();
}
@Override
public void close(final boolean force, boolean onDelete) {
doClose(force, onDelete);
}
public void delete() {
final long timer = Orient.instance().getProfiler().startChrono();
stateLock.acquireWriteLock();
try {
dataLock.acquireExclusiveLock();
try {
// CLOSE THE DATABASE BY REMOVING THE CURRENT USER
doClose(true, true);
try {
Orient.instance().unregisterStorage(this);
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot unregister storage", e);
}
if (writeAheadLog != null)
writeAheadLog.delete();
if (writeCache != null) {
if (readCache != null)
readCache.deleteStorage(writeCache);
else
writeCache.delete();
}
postDeleteSteps();
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Cannot delete database '" + name + "'"), e);
} finally {
dataLock.releaseExclusiveLock();
Orient.instance().getProfiler().stopChrono("db." + name + ".drop", "Drop a database", timer, "db.*.drop");
}
} finally {
stateLock.releaseWriteLock();
}
}
public boolean check(final boolean verbose, final OCommandOutputListener listener) {
checkOpeness();
stateLock.acquireReadLock();
try {
dataLock.acquireExclusiveLock();
try {
checkOpeness();
final long start = System.currentTimeMillis();
OPageDataVerificationError[] pageErrors = writeCache.checkStoredPages(verbose ? listener : null);
listener.onMessage("Check of storage completed in " + (System.currentTimeMillis() - start) + "ms. "
+ (pageErrors.length > 0 ? pageErrors.length + " with errors." : " without errors."));
return pageErrors.length == 0;
} finally {
dataLock.releaseExclusiveLock();
}
} finally {
stateLock.releaseReadLock();
}
}
public int addCluster(String clusterName, boolean forceListBased, final Object... parameters) {
checkOpeness();
checkLowDiskSpaceAndFullCheckpointRequests();
stateLock.acquireWriteLock();
try {
checkOpeness();
makeStorageDirty();
return doAddCluster(clusterName, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName), e);
} finally {
stateLock.releaseWriteLock();
}
}
public int addCluster(String clusterName, int requestedId, boolean forceListBased, Object... parameters) {
checkOpeness();
checkLowDiskSpaceAndFullCheckpointRequests();
stateLock.acquireWriteLock();
try {
checkOpeness();
if (requestedId < 0) {
throw new OConfigurationException("Cluster id must be positive!");
}
if (requestedId < clusters.size() && clusters.get(requestedId) != null) {
throw new OConfigurationException("Requested cluster ID [" + requestedId + "] is occupied by cluster with name ["
+ clusters.get(requestedId).getName() + "]");
}
makeStorageDirty();
return addClusterInternal(clusterName, requestedId, parameters);
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error in creation of new cluster '" + clusterName + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
}
public boolean dropCluster(final int clusterId, final boolean iTruncate) {
checkOpeness();
checkLowDiskSpaceAndFullCheckpointRequests();
stateLock.acquireWriteLock();
try {
checkOpeness();
if (clusterId < 0 || clusterId >= clusters.size())
throw new IllegalArgumentException("Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-"
+ (clusters.size() - 1) + ") in database '" + name + "'");
final OCluster cluster = clusters.get(clusterId);
if (cluster == null)
return false;
if (iTruncate)
cluster.truncate();
cluster.delete();
makeStorageDirty();
clusterMap.remove(cluster.getName().toLowerCase(configuration.getLocaleInstance()));
clusters.set(clusterId, null);
// UPDATE CONFIGURATION
configuration.dropCluster(clusterId);
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public int getId() {
return id;
}
public boolean setClusterStatus(final int clusterId, final OStorageClusterConfiguration.STATUS iStatus) {
checkOpeness();
stateLock.acquireWriteLock();
try {
checkOpeness();
if (clusterId < 0 || clusterId >= clusters.size())
throw new IllegalArgumentException("Cluster id '" + clusterId + "' is outside the of range of configured clusters (0-"
+ (clusters.size() - 1) + ") in database '" + name + "'");
final OCluster cluster = clusters.get(clusterId);
if (cluster == null)
return false;
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE && cluster instanceof OOfflineCluster
|| iStatus == OStorageClusterConfiguration.STATUS.ONLINE && !(cluster instanceof OOfflineCluster))
return false;
final OCluster newCluster;
if (iStatus == OStorageClusterConfiguration.STATUS.OFFLINE) {
cluster.close(true);
newCluster = new OOfflineCluster(this, clusterId, cluster.getName());
} else {
newCluster = OPaginatedClusterFactory.INSTANCE.createCluster(cluster.getName(), configuration.version, this);
newCluster.configure(this, clusterId, cluster.getName());
newCluster.open();
}
clusterMap.put(cluster.getName().toLowerCase(configuration.getLocaleInstance()), newCluster);
clusters.set(clusterId, newCluster);
// UPDATE CONFIGURATION
makeStorageDirty();
configuration.setClusterStatus(clusterId, iStatus);
makeFullCheckpoint();
return true;
} catch (Exception e) {
throw OException.wrapException(new OStorageException("Error while removing cluster '" + clusterId + "'"), e);
} finally {
stateLock.releaseWriteLock();
}
}
@Override
public OSBTreeCollectionManager getSBtreeCollectionManager() {
return sbTreeCollectionManager;
}
public OReadCache getReadCache() {
return readCache;
}
public OWriteCache getWriteCache() {
return writeCache;
}
public long count(final int iClusterId) {
return count(iClusterId, false);
}
@Override
public long count(int clusterId, boolean countTombstones) {
if (clusterId == -1)
throw new OStorageException("Cluster Id " + clusterId + " is invalid in database '" + name + "'");
// COUNT PHYSICAL CLUSTER IF ANY
checkOpeness();
stateLock.acquireReadLock();
try {
dataLock.acquireSharedLock();
try {
checkOpeness();
final OCluster cluster = clusters.get(clusterId);
if (cluster == null)
return 0;
if (countTombstones)
return cluster.getEntries();
return cluster.getEntries() - cluster.getTombstonesCount();
} finally {
dataLock.releaseSharedLock();
}
} finally {
stateLock.releaseReadLock();
}
}
public long[] getClusterDataRange(final int iClusterId) {
if (iClusterId == -1)
return new long[] { ORID.CLUSTER_POS_INVALID, ORID.CLUSTER_POS_INVALID };
checkOpeness();
stateLock.acquireReadLock();
try {
checkOpeness();
return clusters.get(iClusterId) != null
? new long[] { clusters.get(iClusterId).getFirstPosition(), clusters.get(iClusterId).getLastPosition() }
: OCommonConst.EMPTY_LONG_ARRAY;
} catch (IOException ioe) {
throw OException.wrapException(new OStorageException("Cannot retrieve information about data range"), ioe);
} finally {
stateLock.releaseReadLock();
}
}
public OLogSequenceNumber getLSN() {
if (writeAheadLog == null)
return null;
return writeAheadLog.end();
}
public long count(final int[] iClusterIds) {
return count(iClusterIds, false);
}
/**
* This method finds all the records which were updated starting from current LSN and write result in provided output stream. In
* output stream will be included all records which were updated/deleted/created since passed in LSN till the current moment.
* <p>
* Deleted records are written in output stream first, then created/updated records. All records are sorted by record id.
* <p>
* <ol>
* <li>Record's cluster id - 4 bytes</li>
* <li>Record's cluster position - 8 bytes</li>
* <li>Delete flag, 1 if record is deleted - 1 byte</li>
* <li>Record version , only if record is not deleted - 4 bytes</li>
* <li>Record type, only if record is not deleted - 1 byte</li>
* <li>Length of binary presentation of record, only if record is not deleted - 4 bytes</li>
* <li>Binary presentation of the record, only if record is not deleted - length of content is provided in above entity</li>
* </ol>
*
* @param lsn
* LSN from which we should find changed records
* @param stream
* Stream which will contain found records
* @return Last LSN processed during examination of changed records, or <code>null</code> if it was impossible to find changed
* records: write ahead log is absent, record with start LSN was not found in WAL, etc.
* @see OGlobalConfiguration#STORAGE_TRACK_CHANGED_RECORDS_IN_WAL
*/
public OLogSequenceNumber recordsChangedAfterLSN(final OLogSequenceNumber lsn, final OutputStream stream) {
if (!OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getValueAsBoolean())
throw new IllegalStateException(
"Can not find records which were changed starting from provided LSN because tracking of rids of changed records in WAL is switched off, "
+ "to switch it on please set property " + OGlobalConfiguration.STORAGE_TRACK_CHANGED_RECORDS_IN_WAL.getValue()
+ " to the true value, please note that only records"
+ " which are stored after this property was set will be retrieved");
stateLock.acquireReadLock();
try {
if (writeAheadLog == null) {
return null;
}
// we iterate till the last record is contained in wal at the moment when we call this method
final OLogSequenceNumber endLsn = writeAheadLog.end();
if (endLsn == null) {
return null;
}
// container of rids of changed records
final SortedSet<ORID> sortedRids = new TreeSet<ORID>();
final OLogSequenceNumber startLsn = lsn;
writeAheadLog.preventCutTill(startLsn);
try {
// start record is absent there is nothing that we can do
OWALRecord walRecord = writeAheadLog.read(startLsn);
if (walRecord == null) {
return null;
}
OLogSequenceNumber currentLsn = startLsn;
// all information about changed records is contained in atomic operation metadata
while (currentLsn != null && endLsn.compareTo(currentLsn) > 0) {
walRecord = writeAheadLog.read(currentLsn);
if (walRecord instanceof OAtomicUnitEndRecord) {
final OAtomicUnitEndRecord atomicUnitEndRecord = (OAtomicUnitEndRecord) walRecord;
if (atomicUnitEndRecord.getAtomicOperationMetadata().containsKey(ORecordOperationMetadata.RID_METADATA_KEY)) {
final ORecordOperationMetadata recordOperationMetadata = (ORecordOperationMetadata) atomicUnitEndRecord
.getAtomicOperationMetadata().get(ORecordOperationMetadata.RID_METADATA_KEY);
sortedRids.addAll(recordOperationMetadata.getValue());
}
}
currentLsn = writeAheadLog.next(currentLsn);
}
} finally {
writeAheadLog.preventCutTill(null);
}
OLogManager.instance().debug(this, "Exporting records after LSN=%s. Found %d records", lsn, sortedRids.size());
// records may be deleted after we flag them as existing and as result rule of sorting of records
// (deleted records go first will be broken), so we prohibit any modifications till we do not complete method execution
final long lockId = atomicOperationsManager.freezeAtomicOperations(null, null);
try {
final DataOutputStream dataOutputStream = new DataOutputStream(stream);
try {
dataOutputStream.writeLong(sortedRids.size());
Iterator<ORID> ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
// we do not need to load record only check it's presence
if (cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition())) == null) {
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
dataOutputStream.write(1);
OLogManager.instance().debug(this, "Exporting deleted record %s", rid);
// delete to avoid duplication
ridIterator.remove();
}
}
ridIterator = sortedRids.iterator();
while (ridIterator.hasNext()) {
final ORID rid = ridIterator.next();
final OCluster cluster = clusters.get(rid.getClusterId());
dataOutputStream.writeInt(rid.getClusterId());
dataOutputStream.writeLong(rid.getClusterPosition());
final ORawBuffer rawBuffer = cluster.readRecord(rid.getClusterPosition());
assert rawBuffer != null;
dataOutputStream.write(0);
dataOutputStream.writeInt(rawBuffer.version);
dataOutputStream.write(rawBuffer.recordType);
dataOutputStream.writeInt(rawBuffer.buffer.length);
dataOutputStream.write(rawBuffer.buffer);
OLogManager.instance().debug(this, "Exporting modified record rid=%s type=%d size=%d v=%d", rid, rawBuffer.recordType,
rawBuffer.buffer.length, rawBuffer.version);
}
} finally {
dataOutputStream.close();
}
} finally {
atomicOperationsManager.releaseAtomicOperations(lockId);
}
return endLsn;
} catch (IOException e) {
throw OException.wrapException(new OStorageException("Error of reading of records changed after LSN " + lsn), e);
} finally {
stateLock.releaseReadLock();
}
}
@Override
public long count(int[] iClusterIds, boolean countTombstones) {
checkOpeness();
long tot = 0;
stateLock.acquireReadLock();
try {
dataLock.acquireSharedLock();
try {
checkOpeness();
for (int iClusterId : iClusterIds) {
if (iClusterId >= clusters.size())
throw new OConfigurationException("Cluster id " + iClusterId + " was not found in database '" + name + "'");
if (iClusterId > -1) {
final OCluster c = clusters.get(iClusterId);
if (c != null)
tot += c.getEntries() - (countTombstones ? 0L : c.getTombstonesCount());
}
}
return tot;
} finally {
dataLock.releaseSharedLock();
}
} finally {
stateLock.releaseReadLock();
}
}
public OStorageOperationResult<OPhysicalPosition> createRecord(final ORecordId rid, final byte[] content, final int recordVersion,
final byte recordType, final int mode, final ORecordCallback<Long> callback) {
checkOpeness();
checkLowDiskSpaceAndFullCheckpointRequests();
final OPhysicalPosition ppos = new OPhysicalPosition(recordType);
final OCluster cluster = getClusterById(rid.clusterId);
if (transaction.get() != null) {
final long timer = Orient.instance().getProfiler().startChrono();
try {
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, ppos);
} finally {
Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, "Create a record in database", timer,
"db.*.createRecord");
}
}
final long timer = Orient.instance().getProfiler().startChrono();
stateLock.acquireReadLock();
try {
dataLock.acquireSharedLock();
try {
checkOpeness();
return doCreateRecord(rid, content, recordVersion, recordType, callback, cluster, ppos);
} finally {
dataLock.releaseSharedLock();
}
} finally {
stateLock.releaseReadLock();
Orient.instance().getProfiler().stopChrono(PROFILER_CREATE_RECORD, "Create a record in database", timer, "db.*.createRecord");
}
}
@Override
public ORecordMetadata getRecordMetadata(ORID rid) {
if (rid.isNew())
throw new OStorageException("Passed record with id " + rid + " is new and cannot be stored.");
checkOpeness();
stateLock.acquireReadLock();
try {
final OCluster cluster = getClusterById(rid.getClusterId());
lockManager.acquireLock(rid, OLockManager.LOCK.SHARED);
try {
dataLock.acquireSharedLock();
try {
checkOpeness();
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null)
return null;
return new ORecordMetadata(rid, ppos.recordVersion);
} finally {
dataLock.releaseSharedLock();
}
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
lockManager.releaseLock(this, rid, OLockManager.LOCK.SHARED);
}
} finally {
stateLock.releaseReadLock();
}
return null;
}
public void scanCluster(final String iClusterName, final boolean iAscendingOrder, long iFrom, long iTo,
final OCallable<Boolean, ORecord> iCallback) throws IOException {
checkOpeness();
final OCluster cluster = getClusterByName(iClusterName);
if (cluster instanceof OOfflineCluster)
return;
if (!(cluster instanceof OPaginatedCluster))
throw new IllegalArgumentException("Cluster '" + iClusterName + "' (type=" + cluster.getClass() + ") does not support scan");
if (transaction.get() != null) {
final long timer = Orient.instance().getProfiler().startChrono();
try {
((OPaginatedCluster) cluster).scan(iAscendingOrder, iFrom, iTo, 0, iCallback);
} finally {
Orient.instance().getProfiler().stopChrono(PROFILER_READ_RECORD, "Read a record from database", timer, "db.*.readRecord");
}
}
final long scanBatchSize = OGlobalConfiguration.QUERY_SCAN_BATCH_SIZE.getValueAsLong();
if (scanBatchSize > 0) {
long lastPos = -1;
if (iAscendingOrder) {
do {
lastPos = scanClusterInLock(iAscendingOrder, (OPaginatedCluster) cluster, iFrom, iTo, scanBatchSize, iCallback);
iFrom = lastPos;