-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
BackupServiceIT.java
1075 lines (921 loc) · 40 KB
/
BackupServiceIT.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 (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.backup;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.ConnectException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.neo4j.com.storecopy.StoreCopyClient;
import org.neo4j.com.storecopy.StoreCopyServer;
import org.neo4j.cursor.IOCursor;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.graphdb.index.Index;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.io.fs.FileUtils;
import org.neo4j.io.pagecache.IOLimiter;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.factory.DatabaseInfo;
import org.neo4j.kernel.impl.logging.LogService;
import org.neo4j.kernel.impl.spi.SimpleKernelContext;
import org.neo4j.kernel.impl.store.MetaDataStore;
import org.neo4j.kernel.impl.store.MetaDataStore.Position;
import org.neo4j.kernel.impl.store.MismatchingStoreIdException;
import org.neo4j.kernel.impl.store.StoreFactory;
import org.neo4j.kernel.impl.storemigration.LogFiles;
import org.neo4j.kernel.impl.storemigration.StoreFile;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.log.LogFile;
import org.neo4j.kernel.impl.transaction.log.LogicalTransactionStore;
import org.neo4j.kernel.impl.transaction.log.PhysicalLogFiles;
import org.neo4j.kernel.impl.transaction.log.ReadOnlyTransactionStore;
import org.neo4j.kernel.impl.transaction.log.TransactionIdStore;
import org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointer;
import org.neo4j.kernel.impl.transaction.log.checkpoint.SimpleTriggerInfo;
import org.neo4j.kernel.impl.transaction.log.entry.LogHeader;
import org.neo4j.kernel.impl.transaction.log.entry.LogHeaderReader;
import org.neo4j.kernel.impl.transaction.log.rotation.LogRotation;
import org.neo4j.kernel.impl.util.Dependencies;
import org.neo4j.kernel.impl.util.DependenciesProxy;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.monitoring.Monitors;
import org.neo4j.logging.FormattedLogProvider;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import org.neo4j.logging.Logger;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.storageengine.api.StorageEngine;
import org.neo4j.test.Barrier;
import org.neo4j.test.DbRepresentation;
import org.neo4j.test.rule.EmbeddedDatabaseRule;
import org.neo4j.test.rule.PageCacheRule;
import org.neo4j.test.rule.SuppressOutput;
import org.neo4j.test.rule.TestDirectory;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.neo4j.function.Suppliers.untilTimeExpired;
import static org.neo4j.kernel.impl.storemigration.StoreFile.COUNTS_STORE_LEFT;
import static org.neo4j.kernel.impl.storemigration.StoreFile.COUNTS_STORE_RIGHT;
public class BackupServiceIT
{
private static final class StoreSnoopingMonitor extends StoreCopyServer.Monitor.Adapter
{
private final Barrier barrier;
private StoreSnoopingMonitor( Barrier barrier )
{
this.barrier = barrier;
}
@Override
public void finishStreamingStoreFile( File storefile )
{
if ( storefile.getAbsolutePath().contains( NODE_STORE ) ||
storefile.getAbsolutePath().contains( RELATIONSHIP_STORE ) )
{
barrier.reached(); // multiple calls to this barrier will not block
}
}
}
@Rule
public final TestDirectory target = TestDirectory.testDirectory();
private static final String NODE_STORE = StoreFactory.NODE_STORE_NAME;
private static final String RELATIONSHIP_STORE = StoreFactory.RELATIONSHIP_STORE_NAME;
private static final String BACKUP_HOST = "localhost";
private final FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
private final Monitors monitors = new Monitors();
private final IOLimiter limiter = IOLimiter.unlimited();
private File storeDir;
private File backupDir;
public int backupPort = 8200;
@Rule
public EmbeddedDatabaseRule dbRule = new EmbeddedDatabaseRule( getClass() ).startLazily();
@Rule
public SuppressOutput suppressOutput = SuppressOutput.suppressAll();
@Rule
public final PageCacheRule pageCacheRule = new PageCacheRule();
@Before
public void setup()
{
backupPort = backupPort + 1;
storeDir = dbRule.getStoreDirFile();
backupDir = target.directory( "backup_dir" );
}
private BackupService backupService()
{
return new BackupService( fileSystem, FormattedLogProvider.toOutputStream( System.out ), new Monitors() );
}
private BackupService backupService( LogProvider logProvider )
{
return new BackupService( fileSystem, logProvider, new Monitors() );
}
@Test
public void shouldPrintThatFullBackupIsPerformed() throws Exception
{
defaultBackupPortHostParams();
GraphDatabaseService db = dbRule.getGraphDatabaseAPI();
final Log log = mock( Log.class );
LogProvider logProvider = new LogProvider()
{
@Override
public Log getLog( Class loggingClass )
{
return log;
}
@Override
public Log getLog( String name )
{
return log;
}
};
backupService( logProvider ).doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort,
backupDir, ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
verify( log ).info( "Previous backup not found, a new full backup will be performed." );
}
@Test
public void shouldPrintThatIncrementalBackupIsPerformedAndFallingBackToFull() throws Exception
{
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// A full backup
backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir, ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
// And the log the backup uses is rotated out
createAndIndexNode( db, 2 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 3 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 4 );
rotateAndCheckPoint( db );
final Log log = mock( Log.class );
LogProvider logProvider = new LogProvider()
{
@Override
public Log getLog( Class loggingClass )
{
return log;
}
@Override
public Log getLog( String name )
{
return log;
}
};
backupService( logProvider ).doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort,
backupDir, ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
verify( log ).info( "Previous backup found, trying incremental backup." );
verify( log ).info( "Existing backup is too far out of date, a new full backup will be performed." );
}
@Test
public void shouldThrowUsefulMessageWhenCannotConnectDuringFullBackup() throws Exception
{
try
{
backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, 56789, backupDir, ConsistencyCheck.NONE,
dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
fail( "No exception thrown" );
}
catch ( RuntimeException e )
{
assertThat( e.getMessage(), containsString( "BackupClient could not connect" ) );
assertThat( e.getCause(), instanceOf( ConnectException.class ) );
}
}
@Test
public void shouldThrowUsefulMessageWhenCannotConnectDuringIncrementalBackup() throws Exception
{
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
BackupService backupService = backupService();
createAndIndexNode( db, 1 );
// A full backup
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir,
ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
try
{
backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, 56789, backupDir, ConsistencyCheck.NONE,
dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
fail( "No exception thrown" );
}
catch ( RuntimeException e )
{
assertThat( e.getMessage(), containsString( "BackupClient could not connect" ) );
assertThat( e.getCause(), instanceOf( ConnectException.class ) );
}
}
@Test
public void shouldThrowExceptionWhenDoingFullBackupWhenDirectoryHasSomeFiles() throws Exception
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// Touch a random file
assertTrue( new File( backupDir, ".jibberishfile" ).createNewFile() );
try
{
// when
backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.FULL, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
fail( "Should have thrown an exception" );
}
catch ( RuntimeException ex )
{
// then
assertThat( ex.getMessage(), containsString( "is not empty" ) );
}
finally
{
db.shutdown();
}
}
@Test
public void shouldThrowExceptionWhenDoingFullBackupWhenDirectoryHasSomeDirs() throws Exception
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// Touch a random directory
assertTrue( new File( backupDir, "jibberishfolder" ).mkdir() );
try
{
// when
backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.FULL, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
fail( "Should have thrown an exception" );
}
catch ( RuntimeException ex )
{
// then
assertThat( ex.getMessage(), containsString( "is not empty" ) );
}
finally
{
db.shutdown();
}
}
@Test
public void shouldRemoveTempDirectory() throws Throwable
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE,
dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
assertFalse( "Temp directory was not removed as expected",
fileSystem.fileExists( new File( backupDir, StoreCopyClient.TEMP_COPY_DIRECTORY_NAME ) ) );
}
@Test
public void shouldCopyStoreFiles() throws Throwable
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE,
dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
File[] files = fileSystem.listFiles( backupDir );
assertTrue( files.length > 0 );
for ( final StoreFile storeFile : StoreFile.values() )
{
if ( storeFile == COUNTS_STORE_LEFT ||
storeFile == COUNTS_STORE_RIGHT )
{
assertThat( files, anyOf( hasFile( COUNTS_STORE_LEFT.storeFileName() ),
hasFile( COUNTS_STORE_RIGHT.storeFileName() ) ) );
}
else
{
assertThat( files, hasFile( storeFile.storeFileName() ) );
}
}
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
}
/*
* During incremental backup destination db should not track free ids independently from source db
* for now we will always cleanup id files generated after incremental backup and will regenerate them afterwards
* This should prevent situation when destination db free id following master, but never allocates it from
* generator till some db will be started on top of it.
* That will cause all sorts of problems with several entities in a store with same id.
*
* As soon as backup will be able to align ids between participants please remove description and adapt test.
*/
@Test
public void incrementallyBackupDatabaseShouldNotKeepGeneratedIdFiles()
{
defaultBackupPortHostParams();
GraphDatabaseAPI graphDatabase = dbRule.getGraphDatabaseAPI();
Label markerLabel = Label.label( "marker" );
try ( Transaction transaction = graphDatabase.beginTx() )
{
Node node = graphDatabase.createNode();
node.addLabel( markerLabel );
transaction.success();
}
try ( Transaction transaction = graphDatabase.beginTx() )
{
Node node = findNodeByLabel( graphDatabase, markerLabel );
for ( int i = 0; i < 10; i++ )
{
node.setProperty( "property" + i, "testValue" + i );
}
transaction.success();
}
// propagate to backup node and properties
doIncrementalBackupOrFallbackToFull();
// removing properties will free couple of ids that will be reused during next properties creation
try ( Transaction transaction = graphDatabase.beginTx() )
{
Node node = findNodeByLabel( graphDatabase, markerLabel );
for ( int i = 0; i < 6; i++ )
{
node.removeProperty( "property" + i );
}
transaction.success();
}
// propagate removed properties
doIncrementalBackupOrFallbackToFull();
try ( Transaction transaction = graphDatabase.beginTx() )
{
Node node = findNodeByLabel( graphDatabase, markerLabel );
for ( int i = 10; i < 16; i++ )
{
node.setProperty( "property" + i, "updatedValue" + i );
}
transaction.success();
}
// propagate to backup new properties with reclaimed ids
doIncrementalBackupOrFallbackToFull();
// it should be possible to at this point to start db based on our backup and create couple of properties
// their ids should not clash with already existing
GraphDatabaseService backupBasedDatabase = new GraphDatabaseFactory()
.newEmbeddedDatabase( backupDir.getAbsoluteFile() );
try
{
try ( Transaction transaction = backupBasedDatabase.beginTx() )
{
Node node = findNodeByLabel( (GraphDatabaseAPI) backupBasedDatabase, markerLabel );
Iterable<String> propertyKeys = node.getPropertyKeys();
for ( String propertyKey : propertyKeys )
{
node.setProperty( propertyKey, "updatedClientValue" + propertyKey );
}
node.setProperty( "newProperty", "updatedClientValue" );
transaction.success();
}
try ( Transaction transaction = backupBasedDatabase.beginTx() )
{
Node node = findNodeByLabel( (GraphDatabaseAPI) backupBasedDatabase, markerLabel );
// newProperty + 10 defined properties.
assertEquals( "We should be able to see all previously defined properties.",
11, Iterables.asList( node.getPropertyKeys() ).size() );
}
}
finally
{
backupBasedDatabase.shutdown();
}
}
@Test
public void shouldBeAbleToBackupEvenIfTransactionLogsAreIncomplete() throws Throwable
{
/*
* This test deletes the old persisted log file and expects backup to still be functional. It
* should not be assumed that the log files have any particular length of history. They could
* for example have been mangled during backups or removed during pruning.
*/
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
for ( int i = 0; i < 100; i++ )
{
createAndIndexNode( db, i );
}
final File oldLog = db.getDependencyResolver().resolveDependency( LogFile.class ).currentLogFile();
rotateAndCheckPoint( db );
for ( int i = 0; i < 1; i++ )
{
createAndIndexNode( db, i );
}
rotateAndCheckPoint( db );
long lastCommittedTxBefore = db.getDependencyResolver().resolveDependency( TransactionIdStore.class )
.getLastCommittedTransactionId();
db = dbRule.restartDatabase( ( fs, storeDirectory ) -> FileUtils.deleteFile( oldLog ) );
long lastCommittedTxAfter = db.getDependencyResolver().resolveDependency( TransactionIdStore.class )
.getLastCommittedTransactionId();
// when
BackupService backupService = backupService();
BackupService.BackupOutcome outcome = backupService.doFullBackup( BACKUP_HOST, backupPort,
backupDir.getAbsoluteFile(), ConsistencyCheck.FULL, dbRule.getConfigCopy(),
BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
assertEquals( lastCommittedTxBefore, lastCommittedTxAfter );
assertTrue( outcome.isConsistent() );
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
}
@Test
public void shouldFindTransactionLogContainingLastNeoStoreTransactionInAnEmptyStore() throws IOException
{
// This test highlights a special case where an empty store can return transaction metadata for transaction 0.
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
assertEquals( 0, getLastTxChecksum( pageCacheRule.getPageCache( fileSystem ) ) );
}
@Test
public void shouldFindTransactionLogContainingLastNeoStoreTransaction() throws Throwable
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
assertNotEquals( 0, getLastTxChecksum( pageCacheRule.getPageCache( fileSystem ) ) );
}
@Test
public void shouldFindValidPreviousCommittedTxIdInFirstNeoStoreLog() throws Throwable
{
// given
defaultBackupPortHostParams();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
createAndIndexNode( db, 2 );
createAndIndexNode( db, 3 );
createAndIndexNode( db, 4 );
db.getDependencyResolver().resolveDependency( StorageEngine.class ).flushAndForce( limiter );
long txId = db.getDependencyResolver().resolveDependency( TransactionIdStore.class )
.getLastCommittedTransactionId();
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, dbRule.getConfigCopy(), BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
checkPreviousCommittedTxIdFromLog( 0, TransactionIdStore.BASE_TX_ID );
}
@Test
public void shouldFindTransactionLogContainingLastLuceneTransaction() throws Throwable
{
// given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 );
// when
BackupService backupService = backupService();
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );
db.shutdown();
// then
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
assertNotEquals( 0, getLastTxChecksum( pageCacheRule.getPageCache( fileSystem ) ) );
}
@Test
public void shouldGiveHelpfulErrorMessageIfLogsPrunedPastThePointOfNoReturn() throws Exception
{
// Given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
BackupService backupService = backupService();
createAndIndexNode( db, 1 );
rotateAndCheckPoint( db );
// A full backup
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );
// And the log the backup uses is rotated out
createAndIndexNode( db, 2 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 3 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 4 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 5 );
rotateAndCheckPoint( db );
// when
try
{
backupService.doIncrementalBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
BackupClient.BIG_READ_TIMEOUT, defaultConfig );
fail( "Should have thrown exception." );
}
// Then
catch ( IncrementalBackupNotPossibleException e )
{
assertThat( e.getMessage(), equalTo( BackupService.TOO_OLD_BACKUP ) );
}
}
@Test
public void shouldFallbackToFullBackupIfIncrementalFailsAndExplicitlyAskedToDoThis() throws Exception
{
// Given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" );
// have logs rotated on every transaction
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
BackupService backupService = backupService();
createAndIndexNode( db, 1 );
// A full backup
backupService.doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(),
ConsistencyCheck.NONE, defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );
// And the log the backup uses is rotated out
createAndIndexNode( db, 2 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 3 );
rotateAndCheckPoint( db );
createAndIndexNode( db, 4 );
rotateAndCheckPoint( db );
// when
backupService.doIncrementalBackupOrFallbackToFull(
BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
// Then
db.shutdown();
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
}
private void rotateAndCheckPoint( GraphDatabaseAPI db ) throws IOException
{
db.getDependencyResolver().resolveDependency( LogRotation.class ).rotateLogFile();
db.getDependencyResolver().resolveDependency( CheckPointer.class ).forceCheckPoint(
new SimpleTriggerInfo( "test" )
);
}
@Test
public void shouldHandleBackupWhenLogFilesHaveBeenDeleted() throws Exception
{
// Given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" );
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
BackupService backupService = backupService();
createAndIndexNode( db, 1 );
// A full backup
backupService.doIncrementalBackupOrFallbackToFull(
BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
// And the log the backup uses is rotated out
createAndIndexNode( db, 2 );
db = deleteLogFilesAndRestart();
createAndIndexNode( db, 3 );
db = deleteLogFilesAndRestart();
// when
backupService.doIncrementalBackupOrFallbackToFull(
BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
// Then
db.shutdown();
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
}
private GraphDatabaseAPI deleteLogFilesAndRestart()
throws IOException
{
final FileFilter logFileFilter = pathname -> pathname.getName().contains( "logical" );
return dbRule.restartDatabase( ( fs, storeDirectory ) -> {
for ( File logFile : storeDir.listFiles( logFileFilter ) )
{
logFile.delete();
}
} );
}
@Test
public void shouldDoFullBackupOnIncrementalFallbackToFullIfNoBackupFolderExists() throws Exception
{
// Given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( GraphDatabaseSettings.keep_logical_logs, "false" );
GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
BackupService backupService = backupService();
createAndIndexNode( db, 1 );
// when
backupService.doIncrementalBackupOrFallbackToFull(
BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
// then
db.shutdown();
assertEquals( getDbRepresentation(), getBackupDbRepresentation() );
}
@Test
public void shouldContainTransactionsThatHappenDuringBackupProcess() throws Throwable
{
// given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" );
Config withOnlineBackupDisabled = dbRule.getConfigCopy();
final Barrier.Control barrier = new Barrier.Control();
final GraphDatabaseAPI db = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db, 1 ); // create some data
final DependencyResolver resolver = db.getDependencyResolver();
long expectedLastTxId = resolver.resolveDependency( TransactionIdStore.class ).getLastClosedTransactionId();
// This monitor is added server-side...
monitors.addMonitorListener( new StoreSnoopingMonitor( barrier ) );
Dependencies dependencies = new Dependencies( resolver );
dependencies.satisfyDependencies( defaultConfig, monitors, NullLogProvider.getInstance() );
OnlineBackupKernelExtension backup = (OnlineBackupKernelExtension)
new OnlineBackupExtensionFactory().newInstance(
new SimpleKernelContext( fileSystem, storeDir, DatabaseInfo.UNKNOWN, dependencies ),
DependenciesProxy.dependencies( dependencies, OnlineBackupExtensionFactory.Dependencies.class )
);
backup.start();
// when
BackupService backupService = backupService();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute( () -> {
barrier.awaitUninterruptibly();
createAndIndexNode( db, 1 );
resolver.resolveDependency( StorageEngine.class ).flushAndForce( limiter );
barrier.release();
} );
BackupService.BackupOutcome backupOutcome = backupService.doFullBackup( BACKUP_HOST, backupPort,
backupDir.getAbsoluteFile(), ConsistencyCheck.FULL, withOnlineBackupDisabled,
BackupClient.BIG_READ_TIMEOUT, false );
backup.stop();
executor.shutdown();
executor.awaitTermination( 30, TimeUnit.SECONDS );
// then
checkPreviousCommittedTxIdFromLog( 0, expectedLastTxId );
File neoStore = new File( storeDir, MetaDataStore.DEFAULT_NAME );
long txIdFromOrigin = MetaDataStore
.getRecord( resolver.resolveDependency( PageCache.class ), neoStore, Position.LAST_TRANSACTION_ID );
checkLastCommittedTxIdInLogAndNeoStore( expectedLastTxId+1, txIdFromOrigin );
assertEquals( DbRepresentation.of( db ), getBackupDbRepresentation() );
assertTrue( backupOutcome.isConsistent() );
}
@Test
public void backupsShouldBeMentionedInServerConsoleLog() throws Throwable
{
// given
defaultBackupPortHostParams();
Config config = dbRule.getConfigCopy();
dbRule.setConfig( OnlineBackupSettings.online_backup_enabled, "false" );
Config withOnlineBackupDisabled = dbRule.getConfigCopy();
createAndIndexNode( dbRule, 1 );
final Log log = mock( Log.class );
LogProvider logProvider = new LogProvider()
{
@Override
public Log getLog( Class loggingClass )
{
return log;
}
@Override
public Log getLog( String name )
{
return log;
}
};
Logger logger = mock( Logger.class );
when( log.infoLogger() ).thenReturn( logger );
LogService logService = mock( LogService.class );
when( logService.getInternalLogProvider() ).thenReturn( logProvider );
Dependencies dependencies = new Dependencies( dbRule.getDependencyResolver() );
dependencies.satisfyDependencies( config, monitors, logService );
OnlineBackupKernelExtension backup = (OnlineBackupKernelExtension)
new OnlineBackupExtensionFactory().newInstance(
new SimpleKernelContext( fileSystem, storeDir, DatabaseInfo.UNKNOWN, dependencies ),
DependenciesProxy.dependencies( dependencies, OnlineBackupExtensionFactory.Dependencies.class )
);
backup.start();
// when
backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir, ConsistencyCheck.NONE,
withOnlineBackupDisabled, BackupClient.BIG_READ_TIMEOUT, false );
// then
verify( logger ).log( "Full backup started..." );
verify( logger ).log( "Full backup finished." );
// when
createAndIndexNode( dbRule, 2 );
backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort, backupDir,
ConsistencyCheck.NONE, withOnlineBackupDisabled, BackupClient.BIG_READ_TIMEOUT, false );
backup.stop();
// then
verify( logger ).log( "Incremental backup started..." );
verify( logger ).log( "Incremental backup finished." );
}
@Test
public void incrementalBackupShouldFailWhenTargetDirContainsDifferentStore() throws IOException
{
// Given
defaultBackupPortHostParams();
Config defaultConfig = dbRule.getConfigCopy();
GraphDatabaseAPI db1 = dbRule.getGraphDatabaseAPI();
createAndIndexNode( db1, 1 );
backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE,
defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );
// When
GraphDatabaseAPI db2 = dbRule.restartDatabase( ( fs, storeDirectory ) -> {
deleteAllBackedUpTransactionLogs();
fileSystem.deleteRecursively( storeDir );
fileSystem.mkdir( storeDir );
} );
createAndIndexNode( db2, 2 );
try
{
backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort,
backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
BackupClient.BIG_READ_TIMEOUT, false );
fail( "Should have thrown exception about mismatching store ids" );
}
catch ( RuntimeException e )
{
// Then
assertThat( e.getMessage(), equalTo( BackupService.DIFFERENT_STORE ) );
assertThat( e.getCause(), instanceOf( MismatchingStoreIdException.class ) );
}
}
@Test
public void theBackupServiceShouldBeHappyUnderStress() throws Exception
{
Callable<Integer> callable = new BackupServiceStressTestingBuilder()
.until( untilTimeExpired( 10, SECONDS ) )
.withStore( storeDir )
.withBackupDirectory( backupDir )
.withBackupAddress( BACKUP_HOST, backupPort )
.build();
int brokenStores = callable.call();
assertEquals( 0, brokenStores );
}
private void defaultBackupPortHostParams()
{
dbRule.setConfig( OnlineBackupSettings.online_backup_server, BACKUP_HOST + ":" + backupPort );
}
private void createAndIndexNode( GraphDatabaseService db, int i )
{
try ( Transaction tx = db.beginTx() )
{
Index<Node> index = db.index().forNodes( "delete_me" );
Node node = db.createNode();
node.setProperty( "id", System.currentTimeMillis() + i );
index.add( node, "delete", "me" );
tx.success();
}
}
private BaseMatcher<File[]> hasFile( final String fileName )
{
return new BaseMatcher<File[]>()
{
@Override
public boolean matches( Object o )
{
File[] files = (File[]) o;
if ( files == null )
{
return false;
}
for ( File file : files )
{
if ( file.getAbsolutePath().contains( fileName ) )
{
return true;
}
}
return false;
}
@Override
public void describeTo( Description description )
{
description.appendText( String.format( "[%s] in list of copied files", fileName ) );
}