-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
TestBackup.java
696 lines (633 loc) · 24.4 KB
/
TestBackup.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
/*
* 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.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
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.MapUtil;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.kernel.StoreLockException;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.configuration.Settings;
import org.neo4j.kernel.impl.api.TransactionHeaderInformation;
import org.neo4j.kernel.impl.factory.CommunityEditionModule;
import org.neo4j.kernel.impl.factory.CommunityFacadeFactory;
import org.neo4j.kernel.impl.factory.EditionModule;
import org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory;
import org.neo4j.kernel.impl.factory.PlatformModule;
import org.neo4j.kernel.impl.logging.StoreLogService;
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.format.lowlimit.LowLimitV3_0;
import org.neo4j.kernel.impl.store.id.IdGeneratorImpl;
import org.neo4j.kernel.impl.storemigration.StoreFile;
import org.neo4j.kernel.impl.storemigration.StoreFileType;
import org.neo4j.kernel.impl.transaction.TransactionHeaderInformationFactory;
import org.neo4j.test.DbRepresentation;
import org.neo4j.test.PageCacheRule;
import org.neo4j.test.SuppressOutput;
import org.neo4j.test.TargetDirectory;
import org.neo4j.test.TestGraphDatabaseFactory;
import org.neo4j.test.subprocess.SubProcess;
import static java.lang.Integer.parseInt;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.neo4j.graphdb.factory.GraphDatabaseSettings.dense_node_threshold;
import static org.neo4j.kernel.impl.MyRelTypes.TEST;
public class TestBackup
{
@Rule
public TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( TestBackup.class );
@Rule
public final PageCacheRule pageCacheRule = new PageCacheRule();
@Rule
public SuppressOutput suppressOutput = SuppressOutput.suppressAll();
private File serverPath;
private File otherServerPath;
private File backupPath;
private List<ServerInterface> servers;
@Before
public void before() throws Exception
{
servers = new ArrayList<>();
File base = testDir.directory();
serverPath = new File( base, "server" );
otherServerPath = new File( base, "server2" );
backupPath = new File( base, "backuedup-serverdb" );
}
@After
public void shutDownServers()
{
for ( ServerInterface server : servers )
{
server.shutdown();
}
servers.clear();
}
@Test
public void makeSureFullFailsWhenDbExists() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
createInitialDataSet( backupPath );
try
{
backup.full( backupPath.getPath() );
fail( "Shouldn't be able to do full backup into existing db" );
}
catch ( Exception e )
{
// good
}
shutdownServer( server );
}
@Test
public void makeSureIncrementalFailsWhenNoDb() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
try
{
backup.incremental( backupPath.getPath() );
fail( "Shouldn't be able to do incremental backup into non-existing db" );
}
catch ( Exception e )
{
// Good
}
shutdownServer( server );
}
@Test
public void backedUpDatabaseContainsChecksumOfLastTx() throws Exception
{
ServerInterface server = null;
try
{
createInitialDataSet( serverPath );
server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
shutdownServer( server );
server = null;
PageCache pageCache = pageCacheRule.getPageCache( new DefaultFileSystemAbstraction() );
long firstChecksum = lastTxChecksumOf( serverPath, pageCache );
assertEquals( firstChecksum, lastTxChecksumOf( backupPath, pageCache ) );
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
shutdownServer( server );
server = null;
long secondChecksum = lastTxChecksumOf( serverPath, pageCache );
assertEquals( secondChecksum, lastTxChecksumOf( backupPath, pageCache ) );
assertTrue( firstChecksum != secondChecksum );
}
finally
{
if ( server != null )
{
shutdownServer( server );
}
}
}
@Test
public void fullThenIncremental() throws Exception
{
DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
// START SNIPPET: onlineBackup
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
// END SNIPPET: onlineBackup
assertEquals( initialDataSetRepresentation, getDbRepresentation() );
shutdownServer( server );
DbRepresentation furtherRepresentation = addMoreData( serverPath );
server = startServer( serverPath );
// START SNIPPET: onlineBackup
backup.incremental( backupPath.getPath() );
// END SNIPPET: onlineBackup
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( furtherRepresentation, getDbRepresentation() );
shutdownServer( server );
}
@Test
public void makeSureNoLogFileRemains() throws Exception
{
createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
// First check full
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
// Then check empty incremental
backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
// Then check real incremental
shutdownServer( server );
addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertFalse( checkLogFileExistence( backupPath.getPath() ) );
shutdownServer( server );
}
@Test
public void makeSureStoreIdIsEnforced() throws Exception
{
// Create data set X on server A
DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath );
ServerInterface server = startServer( serverPath );
// Grab initial backup from server A
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath, getFormatConfig() ) );
shutdownServer( server );
// Create data set X+Y on server B
createInitialDataSet( otherServerPath );
addMoreData( otherServerPath );
server = startServer( otherServerPath );
// Try to grab incremental backup from server B.
// Data should be OK, but store id check should prevent that.
try
{
backup.incremental( backupPath.getPath() );
fail( "Shouldn't work" );
}
catch ( RuntimeException e )
{
assertThat(e.getCause(), instanceOf(MismatchingStoreIdException.class));
}
shutdownServer( server );
// Just make sure incremental backup can be received properly from
// server A, even after a failed attempt from server B
DbRepresentation furtherRepresentation = addMoreData( serverPath );
server = startServer( serverPath );
backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( furtherRepresentation, DbRepresentation.of( backupPath, getFormatConfig() ) );
shutdownServer( server );
}
@Test
public void multipleIncrementals() throws Exception
{
GraphDatabaseService db = null;
try
{
db = getEmbeddedTestDataBaseService();
Index<Node> index;
try ( Transaction tx = db.beginTx() )
{
index = db.index().forNodes( "yo" );
index.add( db.createNode(), "justTo", "commitATx" );
db.createNode();
tx.success();
}
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
PageCache pageCache = pageCacheRule.getPageCache( new DefaultFileSystemAbstraction() );
long lastCommittedTx = getLastCommittedTx( backupPath.getPath(), pageCache );
for ( int i = 0; i < 5; i++ )
{
try ( Transaction tx = db.beginTx() )
{
Node node = db.createNode();
index.add( node, "key", "value" + i );
tx.success();
}
backup = backup.incremental( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( lastCommittedTx + i + 1, getLastCommittedTx( backupPath.getPath(), pageCache ) );
}
}
finally
{
if ( db != null )
{
db.shutdown();
}
}
}
@Test
public void backupIndexWithNoCommits() throws Exception
{
GraphDatabaseService db = null;
try
{
db = getEmbeddedTestDataBaseService();
try ( Transaction transaction = db.beginTx() )
{
db.index().forNodes( "created-no-commits" );
transaction.success();
}
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertTrue( backup.isConsistent() );
}
finally
{
if ( db != null )
{
db.shutdown();
}
}
}
private long getLastCommittedTx( String path, PageCache pageCache ) throws IOException
{
File neoStore = new File( path, MetaDataStore.DEFAULT_NAME );
return MetaDataStore.getRecord( pageCache, neoStore, Position.LAST_TRANSACTION_ID );
}
@Test
public void backupEmptyIndex() throws Exception
{
String key = "name";
String value = "Neo";
GraphDatabaseService db = getEmbeddedTestDataBaseService();
try
{
Index<Node> index;
Node node;
try ( Transaction tx = db.beginTx() )
{
index = db.index().forNodes( key );
node = db.createNode();
node.setProperty( key, value );
tx.success();
}
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( DbRepresentation.of( db ), getDbRepresentation() );
FileUtils.deleteDirectory( new File( backupPath.getPath() ) );
backup = OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( DbRepresentation.of( db ), getDbRepresentation() );
try ( Transaction tx = db.beginTx() )
{
index.add( node, key, value );
tx.success();
}
FileUtils.deleteDirectory( new File( backupPath.getPath() ) );
backup = OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertTrue( "Should be consistent", backup.isConsistent() );
assertEquals( DbRepresentation.of( db ), getDbRepresentation() );
}
finally
{
db.shutdown();
}
}
@Test
public void shouldRetainFileLocksAfterFullBackupOnLiveDatabase() throws Exception
{
File sourcePath = new File( "target/var/serverdb-lock" );
FileUtils.deleteDirectory( sourcePath );
GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabaseBuilder( sourcePath )
.setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE )
.setConfig( GraphDatabaseFacadeFactory.Configuration.record_format, LowLimitV3_0.NAME )
.newGraphDatabase();
try
{
assertStoreIsLocked( sourcePath );
OnlineBackup.from( "127.0.0.1" ).full( backupPath.getPath() );
assertStoreIsLocked( sourcePath );
}
finally
{
db.shutdown();
}
}
@Test
public void shouldIncrementallyBackupDenseNodes() throws Exception
{
GraphDatabaseService db = startGraphDatabase( serverPath, true );
try
{
createInitialDataset( db );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
DbRepresentation representation = addLotsOfData( db );
backup.incremental( backupPath.getPath() );
assertEquals( representation, getDbRepresentation() );
}
finally
{
db.shutdown();
}
}
@Test
public void shouldLeaveIdFilesAfterBackup() throws Exception
{
GraphDatabaseService db = startGraphDatabase( serverPath, true );
try
{
createInitialDataset( db );
OnlineBackup backup = OnlineBackup.from( "127.0.0.1" );
backup.full( backupPath.getPath() );
ensureStoresHaveIdFiles( backupPath );
DbRepresentation representation = addLotsOfData( db );
backup.incremental( backupPath.getPath() );
assertEquals( representation, getDbRepresentation() );
ensureStoresHaveIdFiles( backupPath );
}
finally
{
db.shutdown();
}
}
private void ensureStoresHaveIdFiles( File path ) throws IOException
{
for ( StoreFile file : StoreFile.values() )
{
if ( file.isRecordStore() )
{
File idFile = new File( path, file.fileName( StoreFileType.ID ) );
assertTrue( "Missing id file " + idFile, idFile.exists() );
assertTrue( "Id file " + idFile + " had 0 highId",
IdGeneratorImpl.readHighId( new DefaultFileSystemAbstraction(), idFile ) > 0 );
}
}
}
private DbRepresentation addLotsOfData( GraphDatabaseService db )
{
try ( Transaction tx = db.beginTx() )
{
Node node = db.createNode();
int threshold = parseInt( dense_node_threshold.getDefaultValue() );
for ( int i = 0; i < threshold*2; i++ )
{
node.createRelationshipTo( db.createNode(), TEST );
}
tx.success();
}
return DbRepresentation.of( db );
}
private static void assertStoreIsLocked( File path )
{
try
{
new TestGraphDatabaseFactory().newEmbeddedDatabase( path ).shutdown();
fail( "Could start up database in same process, store not locked" );
}
catch ( RuntimeException ex )
{
assertThat( ex.getCause().getCause(), instanceOf( StoreLockException.class ) );
}
StartupChecker proc = new LockProcess().start( path );
try
{
assertFalse( "Could start up database in subprocess, store is not locked", proc.startupOk() );
}
finally
{
SubProcess.stop( proc );
}
}
public interface StartupChecker
{
boolean startupOk();
}
@SuppressWarnings( "serial" )
private static class LockProcess extends SubProcess<StartupChecker, File> implements StartupChecker
{
private volatile Object state;
@Override
public boolean startupOk()
{
Object result;
do
{
result = state;
}
while ( result == null );
return !( state instanceof Exception );
}
@Override
protected void startup( File path ) throws Throwable
{
GraphDatabaseService db = null;
try
{
db = new TestGraphDatabaseFactory().newEmbeddedDatabase( path );
}
catch ( RuntimeException ex )
{
if ( ex.getCause().getCause() instanceof StoreLockException )
{
state = ex;
return;
}
}
state = new Object();
if ( db != null )
{
db.shutdown();
}
}
}
private static boolean checkLogFileExistence( String directory )
{
return new File( directory, StoreLogService.INTERNAL_LOG_NAME ).exists();
}
private long lastTxChecksumOf( File storeDir, PageCache pageCache ) throws IOException
{
File neoStore = new File( storeDir, MetaDataStore.DEFAULT_NAME );
return MetaDataStore.getRecord( pageCache, neoStore, Position.LAST_TRANSACTION_CHECKSUM );
}
private ServerInterface startServer( File path ) throws Exception
{
ServerInterface server = new EmbeddedServer( path, "127.0.0.1:6362" );
server.awaitStarted();
servers.add( server );
return server;
}
private void shutdownServer( ServerInterface server ) throws Exception
{
server.shutdown();
servers.remove( server );
}
private DbRepresentation addMoreData( File path )
{
GraphDatabaseService db = startGraphDatabase( path, false );
DbRepresentation representation;
try ( Transaction tx = db.beginTx() )
{
Node node = db.createNode();
node.setProperty( "backup", "Is great" );
db.createNode().createRelationshipTo( node,
RelationshipType.withName( "LOVES" ) );
tx.success();
}
finally
{
representation = DbRepresentation.of( db );
db.shutdown();
}
return representation;
}
private GraphDatabaseService startGraphDatabase( File storeDir, boolean withOnlineBackup )
{
GraphDatabaseFactory dbFactory = new TestGraphDatabaseFactory()
{
@Override
protected GraphDatabaseService newDatabase( File storeDir, Map<String,String> config,
GraphDatabaseFacadeFactory.Dependencies dependencies )
{
return new CommunityFacadeFactory()
{
@Override
protected EditionModule createEdition( PlatformModule platformModule )
{
return new CommunityEditionModule( platformModule )
{
@Override
protected TransactionHeaderInformationFactory createHeaderInformationFactory()
{
return new TransactionHeaderInformationFactory.WithRandomBytes()
{
@Override
protected TransactionHeaderInformation createUsing( byte[] additionalHeader )
{
return new TransactionHeaderInformation( 1, 2, additionalHeader );
}
};
}
};
}
}.newFacade( storeDir, config, dependencies );
}
};
return dbFactory.newEmbeddedDatabaseBuilder( storeDir )
.setConfig( OnlineBackupSettings.online_backup_enabled, String.valueOf( withOnlineBackup ) )
.setConfig( GraphDatabaseSettings.keep_logical_logs, Settings.TRUE )
.setConfig( GraphDatabaseFacadeFactory.Configuration.record_format, LowLimitV3_0.NAME )
.newGraphDatabase();
}
private DbRepresentation createInitialDataSet( File path )
{
GraphDatabaseService db = startGraphDatabase( path, false );
try
{
createInitialDataset( db );
return DbRepresentation.of( db );
}
finally
{
db.shutdown();
}
}
private void createInitialDataset( GraphDatabaseService db )
{
// 4 transactions: THE transaction, "mykey" property key, "db-index" index, "KNOWS" rel type.
try ( Transaction tx = db.beginTx() )
{
Node node = db.createNode( Label.label( "Me" ) );
node.setProperty( "myKey", "myValue" );
Index<Node> nodeIndex = db.index().forNodes( "db-index" );
nodeIndex.add( node, "myKey", "myValue" );
db.createNode().createRelationshipTo( node, RelationshipType.withName( "KNOWS" ) );
tx.success();
}
}
private GraphDatabaseService getEmbeddedTestDataBaseService()
{
return new TestGraphDatabaseFactory().newEmbeddedDatabaseBuilder( serverPath )
.setConfig( OnlineBackupSettings.online_backup_enabled, Settings.TRUE )
.setConfig( GraphDatabaseFacadeFactory.Configuration.record_format, LowLimitV3_0.NAME )
.newGraphDatabase();
}
private Config getFormatConfig()
{
return new Config(
MapUtil.stringMap( GraphDatabaseFacadeFactory.Configuration.record_format.name(), LowLimitV3_0.NAME ) );
}
private DbRepresentation getDbRepresentation()
{
return DbRepresentation.of( backupPath, getFormatConfig() );
}
}