-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
HumanUnderstandableExecutionMonitor.java
504 lines (449 loc) · 19.7 KB
/
HumanUnderstandableExecutionMonitor.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
/*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.unsafe.impl.batchimport.staging;
import java.io.PrintStream;
import java.util.TimeZone;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.unsafe.impl.batchimport.CountGroupsStage;
import org.neo4j.unsafe.impl.batchimport.IdMapperPreparationStage;
import org.neo4j.unsafe.impl.batchimport.NodeDegreeCountStage;
import org.neo4j.unsafe.impl.batchimport.NodeStage;
import org.neo4j.unsafe.impl.batchimport.RelationshipGroupStage;
import org.neo4j.unsafe.impl.batchimport.RelationshipStage;
import org.neo4j.unsafe.impl.batchimport.DataStatistics;
import org.neo4j.unsafe.impl.batchimport.ScanAndCacheGroupsStage;
import org.neo4j.unsafe.impl.batchimport.SparseNodeFirstRelationshipStage;
import org.neo4j.unsafe.impl.batchimport.cache.NodeRelationshipCache;
import org.neo4j.unsafe.impl.batchimport.cache.idmapping.IdMapper;
import org.neo4j.unsafe.impl.batchimport.input.Input;
import org.neo4j.unsafe.impl.batchimport.input.Input.Estimates;
import org.neo4j.unsafe.impl.batchimport.stats.Keys;
import org.neo4j.unsafe.impl.batchimport.stats.Stat;
import org.neo4j.unsafe.impl.batchimport.store.BatchingNeoStores;
import static java.lang.Integer.min;
import static java.lang.Long.max;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static org.neo4j.helpers.Format.bytes;
import static org.neo4j.helpers.Format.count;
import static org.neo4j.helpers.Format.date;
import static org.neo4j.helpers.Format.duration;
import static org.neo4j.helpers.collection.Iterables.last;
import static org.neo4j.unsafe.impl.batchimport.cache.GatheringMemoryStatsVisitor.totalMemoryUsageOf;
/**
* Prints progress you can actually understand, with capabilities to on demand print completely incomprehensible
* details only understandable to a select few.
*/
public class HumanUnderstandableExecutionMonitor implements ExecutionMonitor
{
public interface Monitor
{
void progress( ImportStage stage, int percent );
}
public static final Monitor NO_MONITOR = new Monitor()
{
@Override
public void progress( ImportStage stage, int percent )
{ // empty
}
};
public interface ExternalMonitor
{
boolean somethingElseBrokeMyNiceOutput();
}
public static final ExternalMonitor NO_EXTERNAL_MONITOR = new ExternalMonitor()
{
@Override
public boolean somethingElseBrokeMyNiceOutput()
{
return false;
}
};
enum ImportStage
{
nodeImport,
relationshipImport,
linking,
postProcessing;
}
private static final String ESTIMATED_REQUIRED_MEMORY_USAGE = "Estimated required memory usage";
private static final String ESTIMATED_DISK_SPACE_USAGE = "Estimated disk space usage";
private static final String ESTIMATED_NUMBER_OF_RELATIONSHIP_PROPERTIES = "Estimated number of relationship properties";
private static final String ESTIMATED_NUMBER_OF_RELATIONSHIPS = "Estimated number of relationships";
private static final String ESTIMATED_NUMBER_OF_NODE_PROPERTIES = "Estimated number of node properties";
private static final String ESTIMATED_NUMBER_OF_NODES = "Estimated number of nodes";
private static final int DOT_GROUP_SIZE = 10;
private static final int DOT_GROUPS_PER_LINE = 5;
private static final int PERCENTAGES_PER_LINE = 5;
// assigned later on
private final PrintStream out;
private final Monitor monitor;
private final ExternalMonitor externalMonitor;
private DependencyResolver dependencyResolver;
// progress of current stage
private long goal;
private long stashedProgress;
private long progress;
private ImportStage currentStage;
public HumanUnderstandableExecutionMonitor( PrintStream out, Monitor monitor, ExternalMonitor externalMonitor )
{
this.out = out;
this.monitor = monitor;
this.externalMonitor = externalMonitor;
}
@Override
public void initialize( DependencyResolver dependencyResolver )
{
this.dependencyResolver = dependencyResolver;
Estimates estimates = dependencyResolver.resolveDependency( Estimates.class );
BatchingNeoStores neoStores = dependencyResolver.resolveDependency( BatchingNeoStores.class );
IdMapper idMapper = dependencyResolver.resolveDependency( IdMapper.class );
NodeRelationshipCache nodeRelationshipCache = dependencyResolver.resolveDependency( NodeRelationshipCache.class );
long biggestCacheMemory = defensivelyPadMemoryEstimate( max(
idMapper.calculateMemoryUsage( estimates.numberOfNodes() ),
nodeRelationshipCache.calculateMemoryUsage( estimates.numberOfNodes() ) ) );
printStageHeader( "Import starting",
ESTIMATED_NUMBER_OF_NODES, count( estimates.numberOfNodes() ),
ESTIMATED_NUMBER_OF_NODE_PROPERTIES, count( estimates.numberOfNodeProperties() ),
ESTIMATED_NUMBER_OF_RELATIONSHIPS, count( estimates.numberOfRelationships() ),
ESTIMATED_NUMBER_OF_RELATIONSHIP_PROPERTIES, count( estimates.numberOfRelationshipProperties() ),
ESTIMATED_DISK_SPACE_USAGE, bytes(
nodesDiskUsage( estimates, neoStores ) +
relationshipsDiskUsage( estimates, neoStores ) +
// TODO also add some padding to include relationship groups?
estimates.sizeOfNodeProperties() + estimates.sizeOfRelationshipProperties() ),
ESTIMATED_REQUIRED_MEMORY_USAGE, bytes( baselineMemoryRequirement( neoStores ) + biggestCacheMemory ) );
out.println();
}
private static long baselineMemoryRequirement( BatchingNeoStores neoStores )
{
return totalMemoryUsageOf( neoStores );
}
private static long nodesDiskUsage( Estimates estimates, BatchingNeoStores neoStores )
{
return // node store
estimates.numberOfNodes() * neoStores.getNodeStore().getRecordSize() +
// label index (1 byte per label is not a terrible estimate)
estimates.numberOfNodeLabels();
}
private static long relationshipsDiskUsage( Estimates estimates, BatchingNeoStores neoStores )
{
return estimates.numberOfRelationships() * neoStores.getRelationshipStore().getRecordSize();
}
@Override
public void start( StageExecution execution )
{
// Divide into 4 progress stages:
if ( execution.getStageName().equals( NodeStage.NAME ) )
{
// Import nodes:
// - import nodes
// - prepare id mapper
initializeNodeImport(
dependencyResolver.resolveDependency( Input.Estimates.class ),
dependencyResolver.resolveDependency( IdMapper.class ),
dependencyResolver.resolveDependency( BatchingNeoStores.class ) );
}
else if ( execution.getStageName().equals( RelationshipStage.NAME ) )
{
endPrevious();
// Import relationships:
// - import relationships
initializeRelationshipImport(
dependencyResolver.resolveDependency( Input.Estimates.class ),
dependencyResolver.resolveDependency( IdMapper.class ),
dependencyResolver.resolveDependency( BatchingNeoStores.class ) );
}
else if ( execution.getStageName().equals( NodeDegreeCountStage.NAME ) )
{
endPrevious();
// Link relationships:
// - read node degrees
// - backward linking
// - node relationship linking
// - forward linking
initializeLinking(
dependencyResolver.resolveDependency( BatchingNeoStores.class ),
dependencyResolver.resolveDependency( NodeRelationshipCache.class ),
dependencyResolver.resolveDependency( DataStatistics.class ) );
}
else if ( execution.getStageName().equals( CountGroupsStage.NAME ) )
{
endPrevious();
// Misc:
// - relationship group defragmentation
// - counts store
initializeMisc(
dependencyResolver.resolveDependency( BatchingNeoStores.class ),
dependencyResolver.resolveDependency( DataStatistics.class ) );
}
else if ( includeStage( execution ) )
{
stashedProgress += progress;
progress = 0;
}
}
private void endPrevious()
{
updateProgress( goal ); // previous ended
// TODO print some end stats for this stage?
}
private void initializeNodeImport( Estimates estimates, IdMapper idMapper, BatchingNeoStores neoStores )
{
// TODO how to handle UNKNOWN?
long numberOfNodes = estimates.numberOfNodes();
printStageHeader( "(1/4) Node import",
ESTIMATED_NUMBER_OF_NODES, count( numberOfNodes ),
ESTIMATED_DISK_SPACE_USAGE, bytes(
// node store
nodesDiskUsage( estimates, neoStores ) +
// property store(s)
estimates.sizeOfNodeProperties() ),
ESTIMATED_REQUIRED_MEMORY_USAGE, bytes(
baselineMemoryRequirement( neoStores ) +
defensivelyPadMemoryEstimate( idMapper.calculateMemoryUsage( numberOfNodes ) ) ) );
// A difficulty with the goal here is that we don't know how much woek there is to be done in id mapper preparation stage.
// In addition to nodes themselves and SPLIT,SORT,DETECT there may be RESOLVE,SORT,DEDUPLICATE too, if there are collisions
long goal = idMapper.needsPreparation()
? (long) (numberOfNodes + weighted( IdMapperPreparationStage.NAME, numberOfNodes * 4 ))
: numberOfNodes;
initializeProgress( goal, ImportStage.nodeImport );
}
private void initializeRelationshipImport( Estimates estimates, IdMapper idMapper, BatchingNeoStores neoStores )
{
long numberOfRelationships = estimates.numberOfRelationships();
printStageHeader( "(2/4) Relationship import",
ESTIMATED_NUMBER_OF_RELATIONSHIPS, count( numberOfRelationships ),
ESTIMATED_DISK_SPACE_USAGE, bytes(
relationshipsDiskUsage( estimates, neoStores ) +
estimates.sizeOfRelationshipProperties() ),
ESTIMATED_REQUIRED_MEMORY_USAGE, bytes(
baselineMemoryRequirement( neoStores ) +
totalMemoryUsageOf( idMapper ) ) );
initializeProgress( numberOfRelationships, ImportStage.relationshipImport );
}
private void initializeLinking( BatchingNeoStores neoStores,
NodeRelationshipCache nodeRelationshipCache, DataStatistics distribution )
{
printStageHeader( "(3/4) Relationship linking",
ESTIMATED_REQUIRED_MEMORY_USAGE, bytes(
baselineMemoryRequirement( neoStores ) +
defensivelyPadMemoryEstimate( nodeRelationshipCache.calculateMemoryUsage( distribution.getNodeCount() ) ) ) );
// The reason the highId of the relationship store is used, as opposed to actual number of imported relationships
// is that the stages underneath operate on id ranges, not knowing which records are actually in use.
long relationshipRecordIdCount = neoStores.getRelationshipStore().getHighId();
// The progress counting of linking stages is special anyway, in that it uses the "progress" stats key,
// which is based on actual number of relationships, not relationship ids.
long actualRelationshipCount = distribution.getRelationshipCount();
initializeProgress(
relationshipRecordIdCount + // node degrees
actualRelationshipCount * 2 + // start/end forwards, see RelationshipLinkingProgress
actualRelationshipCount * 2, // start/end backwards, see RelationshipLinkingProgress
ImportStage.linking
);
}
private void initializeMisc( BatchingNeoStores neoStores, DataStatistics distribution )
{
printStageHeader( "(4/4) Post processing",
ESTIMATED_REQUIRED_MEMORY_USAGE, bytes( baselineMemoryRequirement( neoStores ) ) );
long actualNodeCount = distribution.getNodeCount();
// The reason the highId of the relationship store is used, as opposed to actual number of imported relationships
// is that the stages underneath operate on id ranges, not knowing which records are actually in use.
long relationshipRecordIdCount = neoStores.getRelationshipStore().getHighId();
long groupCount = neoStores.getTemporaryRelationshipGroupStore().getHighId();
initializeProgress(
groupCount + // Count groups
groupCount + // Write groups
groupCount + // Node --> Group
actualNodeCount + // Node counts
relationshipRecordIdCount, // Relationship counts
ImportStage.postProcessing
);
}
private static long defensivelyPadMemoryEstimate( long bytes )
{
return (long) (bytes * 1.1);
}
private void initializeProgress( long goal, ImportStage stage )
{
this.goal = goal;
this.stashedProgress = 0;
this.progress = 0;
this.currentStage = stage;
}
private void updateProgress( long progress )
{
// OK so format goes something like 5 groups of 10 dots per line, which is 5%, i.e. 50 dots for 5%, i.e. 1000 dots for 100%,
// i.e. granularity is 1/1000
int maxDot = dotOf( goal );
int currentProgressDot = dotOf( stashedProgress + this.progress );
int currentLine = currentProgressDot / dotsPerLine();
int currentDotOnLine = currentProgressDot % dotsPerLine();
int progressDot = min( maxDot, dotOf( stashedProgress + progress ) );
int line = progressDot / dotsPerLine();
int dotOnLine = progressDot % dotsPerLine();
while ( currentLine < line || (currentLine == line && currentDotOnLine < dotOnLine) )
{
int target = currentLine < line ? dotsPerLine() : dotOnLine;
printDots( currentDotOnLine, target );
currentDotOnLine = target;
if ( currentLine < line || currentDotOnLine == dotsPerLine() )
{
int percentage = percentage( currentLine );
out.println( format( " %s%%", percentage ) );
monitor.progress( currentStage, percentage );
currentLine++;
if ( currentLine == lines() )
{
out.println();
}
currentDotOnLine = 0;
}
}
// TODO not quite right
this.progress = max( this.progress, progress );
}
private static int percentage( int line )
{
return (line + 1) * PERCENTAGES_PER_LINE;
}
private void printDots( int from, int target )
{
int current = from;
while ( current < target )
{
if ( current > 0 && current % DOT_GROUP_SIZE == 0 )
{
out.print( " " );
}
out.print( "." );
current++;
}
}
private int dotOf( long progress )
{
// calculated here just to reduce amount of state kept in this instance
int dots = dotsPerLine() * lines();
double dotSize = goal / (double) dots;
return (int) (progress / dotSize);
}
private static int lines()
{
return 100 / PERCENTAGES_PER_LINE;
}
private static int dotsPerLine()
{
return DOT_GROUPS_PER_LINE * DOT_GROUP_SIZE;
}
private void printStageHeader( String name, Object... data )
{
out.println( name + " " + date( TimeZone.getDefault() ) );
if ( data.length > 0 )
{
for ( int i = 0; i < data.length; )
{
out.println( " " + data[i++] + ": " + data[i++] );
}
}
}
@Override
public void end( StageExecution execution, long totalTimeMillis )
{
}
@Override
public void done( long totalTimeMillis, String additionalInformation )
{
endPrevious();
out.println();
out.println( "IMPORT DONE in " + duration( totalTimeMillis ) + ". " + additionalInformation );
}
@Override
public long nextCheckTime()
{
return currentTimeMillis() + 200;
}
@Override
public void check( StageExecution execution )
{
reprintProgressIfNecessary();
if ( includeStage( execution ) )
{
updateProgress( progressOf( execution ) );
}
}
private void reprintProgressIfNecessary()
{
if ( externalMonitor.somethingElseBrokeMyNiceOutput() )
{
long prevProgress = this.progress;
long prevStashedProgress = this.stashedProgress;
this.progress = 0;
this.stashedProgress = 0;
updateProgress( prevProgress + prevStashedProgress );
this.progress = prevProgress;
this.stashedProgress = prevStashedProgress;
}
}
private static boolean includeStage( StageExecution execution )
{
String name = execution.getStageName();
return !name.equals( RelationshipGroupStage.NAME ) &&
!name.equals( SparseNodeFirstRelationshipStage.NAME ) &&
!name.equals( ScanAndCacheGroupsStage.NAME );
}
private static double weightOf( String stageName )
{
if ( stageName.equals( IdMapperPreparationStage.NAME ) )
{
return 0.5D;
}
return 1;
}
private static long weighted( String stageName, long progress )
{
return (long) (progress * weightOf( stageName ));
}
private static long progressOf( StageExecution execution )
{
// First see if there's a "progress" stat
Stat progressStat = findProgressStat( execution.steps() );
if ( progressStat != null )
{
return weighted( execution.getStageName(), progressStat.asLong() );
}
// No, then do the generic progress calculation by looking at "done_batches"
long doneBatches = last( execution.steps() ).stats().stat( Keys.done_batches ).asLong();
int batchSize = execution.getConfig().batchSize();
long progress = weighted( execution.getStageName(), doneBatches * batchSize );
return progress;
}
private static Stat findProgressStat( Iterable<Step<?>> steps )
{
for ( Step<?> step : steps )
{
Stat stat = step.stats().stat( Keys.progress );
if ( stat != null )
{
return stat;
}
}
return null;
}
}