-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
RebuildFromLogs.java
306 lines (279 loc) · 12.8 KB
/
RebuildFromLogs.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
/*
* Copyright (c) 2002-2017 "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.tools.rebuild;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.neo4j.com.storecopy.ExternallyManagedPageCache;
import org.neo4j.consistency.ConsistencyCheckService;
import org.neo4j.consistency.checking.full.ConsistencyCheckIncompleteException;
import org.neo4j.consistency.checking.full.FullCheck;
import org.neo4j.consistency.statistics.Statistics;
import org.neo4j.cursor.IOCursor;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.Args;
import org.neo4j.helpers.progress.ProgressMonitorFactory;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.io.pagecache.impl.muninn.StandalonePageCacheFactory;
import org.neo4j.kernel.api.direct.DirectStoreAccess;
import org.neo4j.kernel.api.index.SchemaIndexProvider;
import org.neo4j.kernel.api.labelscan.LabelScanStore;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.api.TransactionCommitProcess;
import org.neo4j.kernel.impl.api.TransactionQueue;
import org.neo4j.kernel.impl.api.TransactionToApply;
import org.neo4j.kernel.impl.storageengine.impl.recordstorage.RecordStorageEngine;
import org.neo4j.kernel.impl.store.MetaDataStore;
import org.neo4j.kernel.impl.store.StoreAccess;
import org.neo4j.kernel.impl.transaction.CommittedTransactionRepresentation;
import org.neo4j.kernel.impl.transaction.TransactionRepresentation;
import org.neo4j.kernel.impl.transaction.log.PhysicalLogFile;
import org.neo4j.kernel.impl.transaction.log.PhysicalLogFiles;
import org.neo4j.kernel.impl.transaction.log.PhysicalLogVersionedStoreChannel;
import org.neo4j.kernel.impl.transaction.log.PhysicalTransactionCursor;
import org.neo4j.kernel.impl.transaction.log.ReadAheadLogChannel;
import org.neo4j.kernel.impl.transaction.log.ReadableClosablePositionAwareChannel;
import org.neo4j.kernel.impl.transaction.log.ReadableLogChannel;
import org.neo4j.kernel.impl.transaction.log.ReaderLogVersionBridge;
import org.neo4j.kernel.impl.transaction.log.entry.LogEntryReader;
import org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
import org.neo4j.logging.NullLog;
import static java.lang.String.format;
import static org.neo4j.kernel.impl.transaction.log.LogVersionBridge.NO_MORE_CHANNELS;
import static org.neo4j.kernel.impl.transaction.log.PhysicalLogFile.openForVersion;
import static org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_ID;
import static org.neo4j.kernel.impl.transaction.tracing.CommitEvent.NULL;
import static org.neo4j.storageengine.api.TransactionApplicationMode.EXTERNAL;
/**
* Tool to rebuild store based on available transaction logs.
*/
class RebuildFromLogs
{
private static final String UP_TO_TX_ID = "tx";
private final FileSystemAbstraction fs;
public RebuildFromLogs( FileSystemAbstraction fs )
{
this.fs = fs;
}
public static void main( String[] args ) throws Exception
{
if ( args == null )
{
printUsage();
return;
}
Args params = Args.parse( args );
@SuppressWarnings( "boxing" )
long txId = params.getNumber( UP_TO_TX_ID, BASE_TX_ID ).longValue();
List<String> orphans = params.orphans();
args = orphans.toArray( new String[orphans.size()] );
if ( args.length != 2 )
{
printUsage( "Exactly two positional arguments expected: " +
"<source dir with logs> <target dir for graphdb>, got " + args.length );
System.exit( -1 );
return;
}
File source = new File( args[0] ), target = new File( args[1] );
if ( !source.isDirectory() )
{
printUsage( source + " is not a directory" );
System.exit( -1 );
return;
}
if ( target.exists() )
{
if ( target.isDirectory() )
{
if ( directoryContainsDb( target.toPath() ) )
{
printUsage( "target graph database already exists" );
System.exit( -1 );
return;
}
System.err.println( "WARNING: the directory " + target + " already exists" );
}
else
{
printUsage( target + " is a file" );
System.exit( -1 );
return;
}
}
try ( FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction() )
{
new RebuildFromLogs( fileSystem ).rebuild( source, target, txId );
}
}
private static boolean directoryContainsDb( Path path )
{
return Files.exists( path.resolve( MetaDataStore.DEFAULT_NAME ) );
}
public void rebuild( File source, File target, long txId ) throws Exception
{
try ( PageCache pageCache = StandalonePageCacheFactory.createPageCache( fs ) )
{
PhysicalLogFiles logFiles = new PhysicalLogFiles( source, fs );
long highestVersion = logFiles.getHighestLogVersion();
if ( highestVersion < 0 )
{
printUsage( "Inconsistent number of log files found in " + source );
return;
}
long txCount = findLastTransactionId( logFiles, highestVersion );
ProgressMonitorFactory progress;
if ( txCount < 0 )
{
progress = ProgressMonitorFactory.NONE;
System.err.println(
"Unable to report progress, cannot find highest txId, attempting rebuild anyhow." );
}
else
{
progress = ProgressMonitorFactory.textual( System.err );
}
progress.singlePart( format( "Rebuilding store from %s transactions ", txCount ), txCount );
long lastTxId;
try ( TransactionApplier applier = new TransactionApplier( fs, target, pageCache ) )
{
lastTxId = applier.applyTransactionsFrom( source, txId );
}
// set last tx id in neostore otherwise the db is not usable
MetaDataStore.setRecord( pageCache, new File( target, MetaDataStore.DEFAULT_NAME ),
MetaDataStore.Position.LAST_TRANSACTION_ID, lastTxId );
try ( ConsistencyChecker checker = new ConsistencyChecker( target, pageCache ) )
{
checker.checkConsistency();
}
}
}
private long findLastTransactionId( PhysicalLogFiles logFiles, long highestVersion ) throws IOException
{
ReadableLogChannel logChannel = new ReadAheadLogChannel(
PhysicalLogFile.openForVersion( logFiles, fs, highestVersion, false ), NO_MORE_CHANNELS );
long lastTransactionId = -1;
LogEntryReader<ReadableClosablePositionAwareChannel> entryReader = new VersionAwareLogEntryReader<>();
try ( IOCursor<CommittedTransactionRepresentation> cursor =
new PhysicalTransactionCursor<>( logChannel, entryReader ) )
{
while ( cursor.next() )
{
lastTransactionId = cursor.get().getCommitEntry().getTxId();
}
}
return lastTransactionId;
}
private static void printUsage( String... msgLines )
{
for ( String line : msgLines )
{
System.err.println( line );
}
System.err.println( Args.jarUsage( RebuildFromLogs.class,
"[-full] <source dir with logs> <target dir for graphdb>" ) );
System.err.println( "WHERE: <source dir> is the path for where transactions to rebuild from are stored" );
System.err.println( " <target dir> is the path for where to create the new graph database" );
System.err.println( " -tx -- to rebuild the store up to a given transaction" );
}
private static class TransactionApplier implements AutoCloseable
{
private final GraphDatabaseAPI graphdb;
private final FileSystemAbstraction fs;
private final TransactionCommitProcess commitProcess;
TransactionApplier( FileSystemAbstraction fs, File dbDirectory, PageCache pageCache )
{
this.fs = fs;
this.graphdb = startTemporaryDb( dbDirectory.getAbsoluteFile(), pageCache );
this.commitProcess = graphdb.getDependencyResolver().resolveDependency( TransactionCommitProcess.class );
}
long applyTransactionsFrom( File sourceDir, long upToTxId ) throws Exception
{
PhysicalLogFiles logFiles = new PhysicalLogFiles( sourceDir, fs );
int startVersion = 0;
ReaderLogVersionBridge versionBridge = new ReaderLogVersionBridge( fs, logFiles );
PhysicalLogVersionedStoreChannel startingChannel = openForVersion( logFiles, fs, startVersion, false );
ReadableLogChannel channel = new ReadAheadLogChannel( startingChannel, versionBridge );
long txId = BASE_TX_ID;
TransactionQueue queue = new TransactionQueue( 10_000,
(tx, last) -> {commitProcess.commit( tx, NULL, EXTERNAL );} );
LogEntryReader<ReadableClosablePositionAwareChannel> entryReader = new VersionAwareLogEntryReader<>();
try ( IOCursor<CommittedTransactionRepresentation> cursor =
new PhysicalTransactionCursor<>( channel, entryReader ) )
{
while ( cursor.next() )
{
txId = cursor.get().getCommitEntry().getTxId();
TransactionRepresentation transaction = cursor.get().getTransactionRepresentation();
queue.queue( new TransactionToApply( transaction, txId ) );
if ( upToTxId != BASE_TX_ID && upToTxId == txId )
{
break;
}
}
}
queue.empty();
return txId;
}
@Override
public void close()
{
graphdb.shutdown();
}
}
private static class ConsistencyChecker implements AutoCloseable
{
private final GraphDatabaseAPI graphdb;
private final LabelScanStore labelScanStore;
private final Config tuningConfiguration = Config.embeddedDefaults();
private final SchemaIndexProvider indexes;
ConsistencyChecker( File dbDirectory, PageCache pageCache )
{
this.graphdb = startTemporaryDb( dbDirectory.getAbsoluteFile(), pageCache );
DependencyResolver resolver = graphdb.getDependencyResolver();
this.labelScanStore = resolver.resolveDependency( LabelScanStore.class );
this.indexes = resolver.resolveDependency( SchemaIndexProvider.class );
}
private void checkConsistency() throws ConsistencyCheckIncompleteException
{
StoreAccess nativeStores = new StoreAccess( graphdb.getDependencyResolver()
.resolveDependency( RecordStorageEngine.class ).testAccessNeoStores() ).initialize();
DirectStoreAccess stores = new DirectStoreAccess( nativeStores, labelScanStore, indexes );
FullCheck fullCheck = new FullCheck( tuningConfiguration, ProgressMonitorFactory.textual( System.err ),
Statistics.NONE, ConsistencyCheckService.defaultConsistencyCheckThreadsNumber() );
fullCheck.execute( stores, NullLog.getInstance() );
}
@Override
public void close() throws Exception
{
graphdb.shutdown();
}
}
static GraphDatabaseAPI startTemporaryDb( File targetDirectory, PageCache pageCache )
{
GraphDatabaseFactory factory = ExternallyManagedPageCache.graphDatabaseFactoryWithPageCache( pageCache );
return (GraphDatabaseAPI) factory.newEmbeddedDatabaseBuilder( targetDirectory ).newGraphDatabase();
}
}