diff --git a/community/server/src/main/java/org/neo4j/server/rrd/RrdFactory.java b/community/server/src/main/java/org/neo4j/server/rrd/RrdFactory.java index 51387cc6bcea..847ec593b1b2 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/RrdFactory.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/RrdFactory.java @@ -19,6 +19,12 @@ */ package org.neo4j.server.rrd; +import org.rrd4j.ConsolFun; +import org.rrd4j.core.DsDef; +import org.rrd4j.core.RrdDb; +import org.rrd4j.core.RrdDef; +import org.rrd4j.core.RrdToolkit; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -26,15 +32,7 @@ import java.util.List; import java.util.Map; -import org.rrd4j.ConsolFun; -import org.rrd4j.core.DsDef; -import org.rrd4j.core.RrdDb; -import org.rrd4j.core.RrdDef; -import org.rrd4j.core.RrdToolkit; - -import org.neo4j.io.fs.FileUtils; -import org.neo4j.kernel.GraphDatabaseAPI; -import org.neo4j.kernel.InternalAbstractGraphDatabase; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; import org.neo4j.kernel.logging.ConsoleLogger; @@ -45,6 +43,7 @@ import org.neo4j.server.rrd.sampler.NodeIdsInUseSampleable; import org.neo4j.server.rrd.sampler.PropertyCountSampleable; import org.neo4j.server.rrd.sampler.RelationshipCountSampleable; +import org.neo4j.server.web.ServerInternalSettings; import static java.lang.Double.NaN; import static java.util.Arrays.asList; @@ -52,7 +51,6 @@ import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; - import static org.rrd4j.ConsolFun.AVERAGE; import static org.rrd4j.ConsolFun.MAX; import static org.rrd4j.ConsolFun.MIN; @@ -71,28 +69,36 @@ public RrdFactory( Config config, Logging logging ) this.log = logging.getConsoleLog( getClass() ); } - public org.neo4j.server.database.RrdDbWrapper createRrdDbAndSampler( final Database db, JobScheduler scheduler ) throws IOException + public org.neo4j.server.database.RrdDbWrapper createRrdDbAndSampler( final Database db, JobScheduler scheduler ) + throws IOException { NeoStoreProvider neoStore = db.getGraph().getDependencyResolver().resolveDependency( NeoStoreProvider.class ); + AvailabilityGuard guard = db.getGraph().getDependencyResolver().resolveDependency( AvailabilityGuard.class ); Sampleable[] primitives = { - new NodeIdsInUseSampleable( neoStore ), - new PropertyCountSampleable( neoStore ), - new RelationshipCountSampleable( neoStore ) + new NodeIdsInUseSampleable( neoStore, guard ), + new PropertyCountSampleable( neoStore, guard ), + new RelationshipCountSampleable( neoStore, guard ) }; Sampleable[] usage = {}; + File oldRrdFile = new File( db.getGraph().getStoreDir(), "rrd" ); + if ( oldRrdFile.exists() ) + { + oldRrdFile.delete(); + } + File rrdFile = config.get( ServerSettings.rrdb_location ); - if( rrdFile == null || !rrdFile.exists() ) + if ( rrdFile == null ) { - Map params = config.getParams(); - params.put( ServerSettings.rrdb_location.name(), getDefaultRrdFile( db.getGraph() ) ); + Map params = config.getParams(); + params.put( ServerSettings.rrdb_location.name(), getDefaultRrdFile( config ).getAbsolutePath() ); config.applyChanges( params ); rrdFile = config.get( ServerSettings.rrdb_location ); } - - final RrdDbWrapper rrdb = createRrdb( rrdFile, isEphemereal( db.getGraph() ), join( primitives, usage ) ); + + final RrdDbWrapper rrdb = createRrdb( rrdFile, join( primitives, usage ) ); scheduler.scheduleAtFixedRate( new RrdJob( new RrdSamplerImpl( rrdb.get(), primitives ) ), @@ -114,52 +120,18 @@ private Sampleable[] join( Sampleable[]... sampleables ) return result.toArray( new Sampleable[result.size()] ); } - private String getDefaultRrdFile( GraphDatabaseAPI db ) throws IOException - { - return isEphemereal( db ) ? tempRrdFile() : new File( db.getStoreDir(), "rrd" ).getAbsolutePath(); - } - - protected String tempRrdFile() throws IOException - { - final File tempFile = File.createTempFile( "neo4j", "rrd" ); - tempFile.delete(); - tempFile.mkdir(); - - Runtime.getRuntime().addShutdownHook( new Thread() - { - @Override - public void run() - { - try - { - FileUtils.deleteRecursively(tempFile); - } - catch ( IOException e ) - { - // Ignore - } - } - }); - - return tempFile.getAbsolutePath(); - } - - private boolean isEphemereal( GraphDatabaseAPI db ) + private File getDefaultRrdFile( Config config ) throws IOException { - Config config = db.getDependencyResolver().resolveDependency( Config.class ); - - if ( config == null ) + String path = config.get( ServerInternalSettings.rrd_store ).getAbsolutePath(); + File rrdStore = new File( path ); + if ( !rrdStore.exists() && !rrdStore.mkdirs() ) { - return false; - } - else - { - Boolean ephemeral = config.get( InternalAbstractGraphDatabase.Configuration.ephemeral ); - return ephemeral != null && ephemeral; + throw new IOException( "Cannot create directory " + rrdStore ); } + return rrdStore; } - protected RrdDbWrapper createRrdb( File rrdFile, boolean ephemeral, Sampleable... sampleables ) + protected RrdDbWrapper createRrdb( File rrdFile, Sampleable... sampleables ) { if ( rrdFile.exists() ) { @@ -167,7 +139,7 @@ protected RrdDbWrapper createRrdb( File rrdFile, boolean ephemeral, Sampleable.. { if ( !validateStepSize( rrdFile ) ) { - return recreateArchive( rrdFile, ephemeral, sampleables ); + return recreateArchive( rrdFile, sampleables ); } Sampleable[] missing = checkDataSources( rrdFile.getAbsolutePath(), sampleables ); @@ -175,19 +147,19 @@ protected RrdDbWrapper createRrdb( File rrdFile, boolean ephemeral, Sampleable.. { updateDataSources( rrdFile.getAbsolutePath(), missing ); } - return wrap( new RrdDb( rrdFile.getAbsolutePath() ), ephemeral ); + return new RrdDbWrapper.Plain( new RrdDb( rrdFile.getAbsolutePath() ) ); } catch ( IOException e ) { // RRD file may have become corrupt log.error( "Unable to open rrd store, attempting to recreate it", e ); - return recreateArchive( rrdFile, ephemeral, sampleables ); + return recreateArchive( rrdFile, sampleables ); } catch ( IllegalArgumentException e ) { // RRD file may have become corrupt log.error( "Unable to open rrd store, attempting to recreate it", e ); - return recreateArchive( rrdFile, ephemeral, sampleables ); + return recreateArchive( rrdFile, sampleables ); } } else @@ -197,7 +169,7 @@ protected RrdDbWrapper createRrdb( File rrdFile, boolean ephemeral, Sampleable.. addArchives( rrdDef ); try { - return wrap( new RrdDb( rrdDef ), ephemeral ); + return new RrdDbWrapper.Plain( new RrdDb( rrdDef ) ); } catch ( IOException e ) { @@ -207,35 +179,6 @@ protected RrdDbWrapper createRrdb( File rrdFile, boolean ephemeral, Sampleable.. } } - private RrdDbWrapper wrap( RrdDb db, boolean ephemeral ) throws IOException - { - return ephemeral ? cleaningRrdDb( db ) : new RrdDbWrapper.Plain( db ); - } - - private RrdDbWrapper cleaningRrdDb( final RrdDb db ) - { - return new RrdDbWrapper() - { - @Override - public RrdDb get() - { - return db; - } - - @Override - public void close() throws IOException - { - try - { - db.close(); - } - finally - { - new File( db.getPath() ).delete(); - } - } - }; - } private boolean validateStepSize( File rrdFile ) throws IOException { @@ -243,18 +186,18 @@ private boolean validateStepSize( File rrdFile ) throws IOException try { r = new RrdDb( rrdFile.getAbsolutePath(), true ); - return ( r.getRrdDef().getStep() == STEP_SIZE ); + return (r.getRrdDef().getStep() == STEP_SIZE); } finally { - if( r != null ) + if ( r != null ) { r.close(); } } } - private RrdDbWrapper recreateArchive( File rrdFile, boolean ephemeral, Sampleable[] sampleables ) + private RrdDbWrapper recreateArchive( File rrdFile, Sampleable[] sampleables ) { File file = new File( rrdFile.getParentFile(), rrdFile.getName() + "-invalid-" + System.currentTimeMillis() ); @@ -262,17 +205,17 @@ private RrdDbWrapper recreateArchive( File rrdFile, boolean ephemeral, Sampleabl if ( rrdFile.renameTo( file ) ) { log.error( "current RRDB is invalid, renamed it to %s", file.getAbsolutePath() ); - return createRrdb( rrdFile, ephemeral, sampleables ); + return createRrdb( rrdFile, sampleables ); } throw new RuntimeException( "RRD file ['" + rrdFile.getAbsolutePath() - + "'] is invalid, but I do not have write permissions to recreate it." ); + + "'] is invalid, but I do not have write permissions to recreate it." ); } private static Sampleable[] checkDataSources( String rrdPath, Sampleable[] sampleables ) throws IOException { RrdDb rrdDb = new RrdDb( rrdPath, true ); - List missing = new ArrayList(); + List missing = new ArrayList<>(); for ( Sampleable sampleable : sampleables ) { if ( rrdDb.getDatasource( sampleable.getName() ) == null ) @@ -314,8 +257,8 @@ private void addArchives( RrdDef rrdDef ) private void addArchive( RrdDef rrdDef, ConsolFun fun, long length, long resolution ) { rrdDef.addArchive( fun, 0.2, - (int) ( resolution * STEP_SIZE ), - (int) ( length / ( resolution * STEP_SIZE ) ) ); + (int) (resolution * STEP_SIZE), + (int) (length / (resolution * STEP_SIZE)) ); } private void defineDataSources( RrdDef rrdDef, Sampleable[] sampleables ) diff --git a/community/server/src/main/java/org/neo4j/server/rrd/RrdSamplerImpl.java b/community/server/src/main/java/org/neo4j/server/rrd/RrdSamplerImpl.java index 686b3fc0d75d..9ee7a330123d 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/RrdSamplerImpl.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/RrdSamplerImpl.java @@ -19,12 +19,12 @@ */ package org.neo4j.server.rrd; -import java.io.IOException; - import org.rrd4j.core.RrdDb; import org.rrd4j.core.Sample; import org.rrd4j.core.Util; +import java.io.IOException; + /** * Manages sampling the state of the database and storing the samples in a round * robin database instance. @@ -61,10 +61,6 @@ protected RrdSamplerImpl(RrdDb rrdDb, Sampleable... samplables) { sample.update(); } - catch ( UnableToSampleException e ) - { - e.printStackTrace(); - } catch ( IOException e ) { throw new RuntimeException( "IO Error trying to access round robin database path. See nested exception.", e ); diff --git a/community/server/src/main/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBase.java b/community/server/src/main/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBase.java index 6c7030fbf6f0..c8aeb8ae3d1a 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBase.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBase.java @@ -21,6 +21,7 @@ import org.rrd4j.DsType; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.impl.store.NeoStore; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; import org.neo4j.server.rrd.Sampleable; @@ -28,22 +29,42 @@ public abstract class DatabasePrimitivesSampleableBase implements Sampleable { private final NeoStoreProvider neoStore; + private final AvailabilityGuard guard; + private double lastReadValue = 0d; - public DatabasePrimitivesSampleableBase( NeoStoreProvider neoStore ) + public DatabasePrimitivesSampleableBase( NeoStoreProvider neoStore, AvailabilityGuard guard ) { - if( neoStore == null ) + if ( neoStore == null ) { throw new RuntimeException( "Database sampler needs a NeoStore to work, was given null." ); } this.neoStore = neoStore; - + this.guard = guard; } - protected NeoStore getNeoStore() + @Override + public double getValue() { - return neoStore.evaluate(); + if ( guard.isAvailable(0) ) + { + try + { + lastReadValue = readValue( neoStore.evaluate() ); + } + catch ( Exception e ) + { + /* + * oh well, this is unfortunate, perhaps the db went down after the check, so let's ignore this problem + * and return the old value, we'll sample again when the db is online again + */ + } + } + + return lastReadValue; } + protected abstract double readValue( NeoStore neoStore ); + @Override public DsType getType() { diff --git a/community/server/src/main/java/org/neo4j/server/rrd/sampler/NodeIdsInUseSampleable.java b/community/server/src/main/java/org/neo4j/server/rrd/sampler/NodeIdsInUseSampleable.java index 36e4f380d4a1..87cd841c4efc 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/sampler/NodeIdsInUseSampleable.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/sampler/NodeIdsInUseSampleable.java @@ -19,31 +19,26 @@ */ package org.neo4j.server.rrd.sampler; +import org.neo4j.kernel.AvailabilityGuard; +import org.neo4j.kernel.impl.store.NeoStore; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; -import org.neo4j.server.rrd.UnableToSampleException; public class NodeIdsInUseSampleable extends DatabasePrimitivesSampleableBase { - - public NodeIdsInUseSampleable( NeoStoreProvider neoStore ) + public NodeIdsInUseSampleable( NeoStoreProvider neoStore, AvailabilityGuard guard ) { - super( neoStore ); + super( neoStore, guard ); } - @Override public String getName() + @Override + public String getName() { return "node_count"; } - @Override public double getValue() + @Override + protected double readValue( NeoStore neoStore ) { - try - { - return getNeoStore().getNodeStore().getNumberOfIdsInUse(); - } - catch ( Exception e ) - { - throw new UnableToSampleException( "Unexpected exception caught while sampling", e ); - } + return neoStore.getNodeStore().getNumberOfIdsInUse(); } } diff --git a/community/server/src/main/java/org/neo4j/server/rrd/sampler/PropertyCountSampleable.java b/community/server/src/main/java/org/neo4j/server/rrd/sampler/PropertyCountSampleable.java index 800dd6afea3a..c0a535263a0c 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/sampler/PropertyCountSampleable.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/sampler/PropertyCountSampleable.java @@ -19,13 +19,15 @@ */ package org.neo4j.server.rrd.sampler; +import org.neo4j.kernel.AvailabilityGuard; +import org.neo4j.kernel.impl.store.NeoStore; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; public class PropertyCountSampleable extends DatabasePrimitivesSampleableBase { - public PropertyCountSampleable( NeoStoreProvider neoStore ) + public PropertyCountSampleable( NeoStoreProvider neoStore, AvailabilityGuard guard ) { - super( neoStore ); + super( neoStore, guard ); } @Override public String getName() @@ -33,8 +35,9 @@ public PropertyCountSampleable( NeoStoreProvider neoStore ) return "property_count"; } - @Override public double getValue() + @Override + protected double readValue( NeoStore neoStore ) { - return getNeoStore().getPropertyStore().getNumberOfIdsInUse(); + return neoStore.getPropertyStore().getNumberOfIdsInUse(); } } diff --git a/community/server/src/main/java/org/neo4j/server/rrd/sampler/RelationshipCountSampleable.java b/community/server/src/main/java/org/neo4j/server/rrd/sampler/RelationshipCountSampleable.java index 2626a90ac708..83bd91bab3ce 100644 --- a/community/server/src/main/java/org/neo4j/server/rrd/sampler/RelationshipCountSampleable.java +++ b/community/server/src/main/java/org/neo4j/server/rrd/sampler/RelationshipCountSampleable.java @@ -19,13 +19,15 @@ */ package org.neo4j.server.rrd.sampler; +import org.neo4j.kernel.AvailabilityGuard; +import org.neo4j.kernel.impl.store.NeoStore; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; public class RelationshipCountSampleable extends DatabasePrimitivesSampleableBase { - public RelationshipCountSampleable( NeoStoreProvider neoStore ) + public RelationshipCountSampleable( NeoStoreProvider neoStore, AvailabilityGuard guard ) { - super( neoStore ); + super( neoStore, guard ); } @Override public String getName() @@ -33,8 +35,9 @@ public RelationshipCountSampleable( NeoStoreProvider neoStore ) return "relationship_count"; } - @Override public double getValue() + @Override + protected double readValue( NeoStore neoStore ) { - return getNeoStore().getRelationshipStore().getNumberOfIdsInUse(); + return neoStore.getRelationshipStore().getNumberOfIdsInUse(); } } diff --git a/community/server/src/main/java/org/neo4j/server/web/ServerInternalSettings.java b/community/server/src/main/java/org/neo4j/server/web/ServerInternalSettings.java index 76884159d2d0..4b83304ea3c8 100644 --- a/community/server/src/main/java/org/neo4j/server/web/ServerInternalSettings.java +++ b/community/server/src/main/java/org/neo4j/server/web/ServerInternalSettings.java @@ -77,6 +77,8 @@ public class ServerInternalSettings public static final Setting auth_store = setting("dbms.security.auth_store.location", PATH, "data/dbms/auth"); + public static final Setting rrd_store = setting("dbms.security.auth_store.location", PATH, "data/rrd"); + public static final Setting legacy_db_location = setting( "org.neo4j.server.database.location", PATH, "data/graph.db" ); public static final Setting legacy_db_config = setting( "org.neo4j.server.db.tuning.properties", diff --git a/community/server/src/test/java/org/neo4j/server/helpers/CommunityServerBuilder.java b/community/server/src/test/java/org/neo4j/server/helpers/CommunityServerBuilder.java index 26f6197e8ca8..1dfae852833f 100644 --- a/community/server/src/test/java/org/neo4j/server/helpers/CommunityServerBuilder.java +++ b/community/server/src/test/java/org/neo4j/server/helpers/CommunityServerBuilder.java @@ -221,6 +221,7 @@ private void createPropertiesFile( File temporaryConfigFile ) properties.put( ServerSettings.auth_enabled.name(), "false" ); properties.put( ServerInternalSettings.auth_store.name(), "neo4j-home/data/dbms/authorization" ); + properties.put( ServerInternalSettings.rrd_store.name(), "neo4j-home/data/rrd/" ); for ( Object key : arbitraryProperties.keySet() ) { diff --git a/community/server/src/test/java/org/neo4j/server/rest/security/AuthenticationDocIT.java b/community/server/src/test/java/org/neo4j/server/rest/security/AuthenticationDocIT.java index 9622979dfca6..c463a0decef3 100644 --- a/community/server/src/test/java/org/neo4j/server/rest/security/AuthenticationDocIT.java +++ b/community/server/src/test/java/org/neo4j/server/rest/security/AuthenticationDocIT.java @@ -19,18 +19,19 @@ */ package org.neo4j.server.rest.security; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; - -import javax.ws.rs.core.HttpHeaders; - +import com.sun.jersey.core.util.Base64; import org.codehaus.jackson.JsonNode; 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.nio.charset.Charset; +import javax.ws.rs.core.HttpHeaders; + +import org.neo4j.io.fs.FileUtils; import org.neo4j.kernel.impl.annotations.Documented; import org.neo4j.server.CommunityNeoServer; import org.neo4j.server.configuration.ServerSettings; @@ -43,8 +44,6 @@ import org.neo4j.test.server.HTTP; import org.neo4j.test.server.HTTP.RawPayload; -import com.sun.jersey.core.util.Base64; - import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -316,7 +315,7 @@ public void startServerWithConfiguredUser() throws IOException public void startServer(boolean authEnabled) throws IOException { - new File( "neo4j-home/data/dbms/authorization" ).delete(); // TODO: Implement a common component for managing Neo4j file structure and use that here + FileUtils.deleteRecursively( new File( "neo4j-home/data/" ) ); // TODO: Implement a common component for managing Neo4j file structure and use that here server = CommunityServerBuilder.server() .withProperty( ServerSettings.auth_enabled.name(), Boolean.toString( authEnabled ) ) .build(); diff --git a/community/server/src/test/java/org/neo4j/server/rest/security/UsersDocIT.java b/community/server/src/test/java/org/neo4j/server/rest/security/UsersDocIT.java index 94ff0bfb72fb..f7430909461e 100644 --- a/community/server/src/test/java/org/neo4j/server/rest/security/UsersDocIT.java +++ b/community/server/src/test/java/org/neo4j/server/rest/security/UsersDocIT.java @@ -19,18 +19,19 @@ */ package org.neo4j.server.rest.security; -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; - -import javax.ws.rs.core.HttpHeaders; - +import com.sun.jersey.core.util.Base64; import org.codehaus.jackson.JsonNode; 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.nio.charset.Charset; +import javax.ws.rs.core.HttpHeaders; + +import org.neo4j.io.fs.FileUtils; import org.neo4j.kernel.impl.annotations.Documented; import org.neo4j.server.CommunityNeoServer; import org.neo4j.server.configuration.ServerSettings; @@ -42,7 +43,6 @@ import org.neo4j.test.server.ExclusiveServerTestBase; import org.neo4j.test.server.HTTP; -import com.sun.jersey.core.util.Base64; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; @@ -161,7 +161,7 @@ public void cleanup() public void startServer(boolean authEnabled) throws IOException { - new File( "neo4j-home/data/dbms/authorization" ).delete(); // TODO: Implement a common component for managing Neo4j file structure and use that here + FileUtils.deleteRecursively( new File( "neo4j-home/data/" ) ); // TODO: Implement a common component for managing Neo4j file structure and use that here server = CommunityServerBuilder.server().withProperty( ServerSettings.auth_enabled.name(), Boolean.toString( authEnabled ) ).build(); server.start(); diff --git a/community/server/src/test/java/org/neo4j/server/rrd/DatabasePrimitivesSampleableBaseDocTest.java b/community/server/src/test/java/org/neo4j/server/rrd/DatabasePrimitivesSampleableBaseDocTest.java index 4ce7aef3dbb5..2b9b6fd32c6f 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/DatabasePrimitivesSampleableBaseDocTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/DatabasePrimitivesSampleableBaseDocTest.java @@ -19,47 +19,48 @@ */ package org.neo4j.server.rrd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + import java.io.IOException; import javax.management.MalformedObjectNameException; -import org.junit.Test; - -import org.neo4j.kernel.GraphDatabaseAPI; +import org.neo4j.graphdb.DependencyResolver; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; import org.neo4j.server.rrd.sampler.DatabasePrimitivesSampleableBase; import org.neo4j.server.rrd.sampler.NodeIdsInUseSampleable; -import org.neo4j.test.TestGraphDatabaseFactory; +import org.neo4j.test.DatabaseRule; +import org.neo4j.test.ImpermanentDatabaseRule; import static org.junit.Assert.assertTrue; public class DatabasePrimitivesSampleableBaseDocTest { + @Rule + public final DatabaseRule dbRule = new ImpermanentDatabaseRule(); + private DatabasePrimitivesSampleableBase sampleable; + @Test public void sampleTest() throws MalformedObjectNameException, IOException { - GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); - - DatabasePrimitivesSampleableBase sampleable = new NodeIdsInUseSampleable( neoStore( db ) ); - assertTrue( "There should be no nodes in use.", sampleable.getValue() == 0 ); - - db.shutdown(); } @Test public void rrd_uses_temp_dir() throws Exception { - GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); - - DatabasePrimitivesSampleableBase sampleable = new NodeIdsInUseSampleable( neoStore( db ) ); - assertTrue( "There should be no nodes in use.", sampleable.getValue() == 0 ); - - db.shutdown(); } - private NeoStoreProvider neoStore( GraphDatabaseAPI db ) + @Before + public void setup() { - return db.getDependencyResolver().resolveDependency( NeoStoreProvider.class ); + DependencyResolver dependencyResolver = dbRule.getGraphDatabaseAPI().getDependencyResolver(); + NeoStoreProvider neoStore = dependencyResolver.resolveDependency( NeoStoreProvider.class ); + AvailabilityGuard guard = dependencyResolver.resolveDependency( AvailabilityGuard.class ); + sampleable = new NodeIdsInUseSampleable( neoStore, guard ); } + } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/NodeIdsInUseSampleableTest.java b/community/server/src/test/java/org/neo4j/server/rrd/NodeIdsInUseSampleableTest.java index f0771e97cebc..5b2a6cb16ed1 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/NodeIdsInUseSampleableTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/NodeIdsInUseSampleableTest.java @@ -19,24 +19,26 @@ */ package org.neo4j.server.rrd; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.neo4j.graphdb.DependencyResolver; +import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; -import org.neo4j.kernel.GraphDatabaseAPI; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; import org.neo4j.server.rrd.sampler.NodeIdsInUseSampleable; -import org.neo4j.test.TestGraphDatabaseFactory; +import org.neo4j.test.DatabaseRule; +import org.neo4j.test.ImpermanentDatabaseRule; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.core.Is.is; public class NodeIdsInUseSampleableTest { - public GraphDatabaseAPI db; + @Rule + public final DatabaseRule dbRule = new ImpermanentDatabaseRule(); public NodeIdsInUseSampleable sampleable; @Test @@ -48,32 +50,22 @@ public void emptyDbHasZeroNodesInUse() @Test public void addANodeAndSampleableGoesUp() { - double oldValue = sampleable.getValue(); + GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); + try ( Transaction tx = db.beginTx() ) + { + db.createNode(); + tx.success(); + } - createNode( db ); - - assertThat( sampleable.getValue(), greaterThan( oldValue ) ); - } - - private void createNode( GraphDatabaseAPI db ) - { - Transaction tx = db.beginTx(); - db.createNode(); - tx.success(); - tx.finish(); + assertThat( sampleable.getValue(), is (1d ) ); } @Before public void setUp() throws Exception { - db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase(); - DependencyResolver dependencyResolver = db.getDependencyResolver(); - sampleable = new NodeIdsInUseSampleable( dependencyResolver.resolveDependency( NeoStoreProvider.class ) ); - } - - @After - public void shutdown() throws Throwable - { - db.shutdown(); + DependencyResolver dependencyResolver = dbRule.getGraphDatabaseAPI().getDependencyResolver(); + NeoStoreProvider neoStore = dependencyResolver.resolveDependency( NeoStoreProvider.class ); + AvailabilityGuard guard = dependencyResolver.resolveDependency( AvailabilityGuard.class ); + sampleable = new NodeIdsInUseSampleable( neoStore, guard ); } } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/PropertyCountSampleableTest.java b/community/server/src/test/java/org/neo4j/server/rrd/PropertyCountSampleableTest.java index 9e3c17a0c21a..d46be39c51e2 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/PropertyCountSampleableTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/PropertyCountSampleableTest.java @@ -19,44 +19,30 @@ */ package org.neo4j.server.rrd; -import java.util.UUID; - -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import java.util.UUID; + import org.neo4j.graphdb.DependencyResolver; +import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; -import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.Transaction; -import org.neo4j.kernel.InternalAbstractGraphDatabase; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; -import org.neo4j.server.database.Database; -import org.neo4j.server.database.WrappedDatabase; import org.neo4j.server.rrd.sampler.PropertyCountSampleable; -import org.neo4j.test.TestGraphDatabaseFactory; +import org.neo4j.test.DatabaseRule; +import org.neo4j.test.ImpermanentDatabaseRule; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class PropertyCountSampleableTest { - public Database db; + @Rule + public final DatabaseRule dbRule = new ImpermanentDatabaseRule(); public PropertyCountSampleable sampleable; - public long referenceNodeId; - - @Before - public void setupReferenceNode() - { - db = new WrappedDatabase( (InternalAbstractGraphDatabase) new TestGraphDatabaseFactory().newImpermanentDatabase() ); - DependencyResolver dependencyResolver = db.getGraph().getDependencyResolver(); - sampleable = new PropertyCountSampleable( dependencyResolver.resolveDependency( NeoStoreProvider.class ) ); - - Transaction tx = db.getGraph().beginTx(); - referenceNodeId = db.getGraph().createNode().getId(); - tx.success(); - tx.finish(); - } @Test public void emptyDbHasZeroNodesInUse() @@ -65,49 +51,47 @@ public void emptyDbHasZeroNodesInUse() } @Test - public void addANodeAndSampleableGoesUp() + public void addANodeWithPropertyAndSampleableGoesUp() { - addPropertyToReferenceNode(); - + createNodeWithProperty(); assertThat( sampleable.getValue(), is( 1d ) ); - - addNodeIntoGraph(); - addNodeIntoGraph(); - - assertThat( sampleable.getValue(), is( 3d ) ); } - private void addNodeIntoGraph() + @Test + public void addOnlyPropertiesAndSampleableGoesUp() { - Transaction tx = db.getGraph().beginTx(); - Node referenceNode = db.getGraph().getNodeById( referenceNodeId ); - Node myNewNode = db.getGraph().createNode(); - myNewNode.setProperty( "id", UUID.randomUUID().toString() ); - myNewNode.createRelationshipTo( referenceNode, new RelationshipType() + long nodeId = createNodeWithProperty(); + assertThat( sampleable.getValue(), is( 1d ) ); + + GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); + try ( Transaction tx = db.beginTx() ) { - @Override - public String name() - { - return "knows_about"; - } - } ); + Node node = db.getNodeById( nodeId ); + node.setProperty( "id", UUID.randomUUID().toString() ); + tx.success(); + } - tx.success(); - tx.finish(); + assertThat( sampleable.getValue(), is( 2d ) ); } - private void addPropertyToReferenceNode() + @Before + public void setupReferenceNode() { - Transaction tx = db.getGraph().beginTx(); - Node n = db.getGraph().getNodeById( referenceNodeId ); - n.setProperty( "monkey", "rock!" ); - tx.success(); - tx.finish(); + DependencyResolver dependencyResolver = dbRule.getGraphDatabaseAPI().getDependencyResolver(); + NeoStoreProvider neoStore = dependencyResolver.resolveDependency( NeoStoreProvider.class ); + AvailabilityGuard gaurd = dependencyResolver.resolveDependency( AvailabilityGuard.class ); + sampleable = new PropertyCountSampleable( neoStore, gaurd ); } - @After - public void shutdownDatabase() throws Throwable + private long createNodeWithProperty() { - db.getGraph().shutdown(); + GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); + try ( Transaction tx = db.beginTx() ) + { + Node n = db.createNode(); + n.setProperty( "monkey", "rock!" ); + tx.success(); + return n.getId(); + } } } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/RelationshipCountSampleableTest.java b/community/server/src/test/java/org/neo4j/server/rrd/RelationshipCountSampleableTest.java index 66bdfccb73c1..c23b2f6cbcdc 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/RelationshipCountSampleableTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/RelationshipCountSampleableTest.java @@ -19,25 +19,28 @@ */ package org.neo4j.server.rrd; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.neo4j.graphdb.DependencyResolver; +import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; -import org.neo4j.kernel.GraphDatabaseAPI; +import org.neo4j.kernel.AvailabilityGuard; import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; import org.neo4j.server.rrd.sampler.RelationshipCountSampleable; -import org.neo4j.test.TestGraphDatabaseFactory; +import org.neo4j.test.DatabaseRule; +import org.neo4j.test.ImpermanentDatabaseRule; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; - import static org.neo4j.graphdb.DynamicRelationshipType.withName; public class RelationshipCountSampleableTest { - public GraphDatabaseAPI db; + @Rule + public final DatabaseRule dbRule = new ImpermanentDatabaseRule(); public RelationshipCountSampleable sampleable; @Test @@ -49,31 +52,24 @@ public void emptyDbHasZeroRelationships() @Test public void addANodeAndSampleableGoesUp() { - createARelationship( db ); + GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); + try( Transaction tx = db.beginTx() ) + { + Node node1 = db.createNode(); + Node node2 = db.createNode(); + node1.createRelationshipTo( node2, withName( "friend" ) ); + tx.success(); + } assertThat( sampleable.getValue(), is( 1d ) ); } - private void createARelationship( GraphDatabaseAPI db ) - { - Transaction tx = db.beginTx(); - Node node1 = db.createNode(); - Node node2 = db.createNode(); - node1.createRelationshipTo( node2, withName( "friend" ) ); - tx.success(); - tx.finish(); - } - @Before public void setUp() throws Exception { - db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); - sampleable = new RelationshipCountSampleable( db.getDependencyResolver().resolveDependency( NeoStoreProvider.class ) ); - } - - @After - public void shutdownDatabase() - { - this.db.shutdown(); + DependencyResolver dependencyResolver = dbRule.getGraphDatabaseAPI().getDependencyResolver(); + NeoStoreProvider neoStore = dependencyResolver.resolveDependency( NeoStoreProvider.class ); + AvailabilityGuard guard = dependencyResolver.resolveDependency( AvailabilityGuard.class ); + sampleable = new RelationshipCountSampleable( neoStore, guard ); } } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/RrdFactoryTest.java b/community/server/src/test/java/org/neo4j/server/rrd/RrdFactoryTest.java index a40aa0cf272b..1bd0d30a53e5 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/RrdFactoryTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/RrdFactoryTest.java @@ -19,7 +19,6 @@ */ package org.neo4j.server.rrd; -import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -32,21 +31,23 @@ import java.io.IOException; import java.util.Map; -import org.neo4j.kernel.InternalAbstractGraphDatabase; +import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.kernel.configuration.Config; import org.neo4j.kernel.logging.DevNullLoggingService; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.database.Database; import org.neo4j.server.database.RrdDbWrapper; import org.neo4j.server.database.WrappedDatabase; -import org.neo4j.test.ImpermanentGraphDatabase; +import org.neo4j.server.web.ServerInternalSettings; import org.neo4j.test.Mute; import org.neo4j.test.TargetDirectory; import org.neo4j.test.TestGraphDatabaseFactory; import static java.lang.Double.NaN; import static org.hamcrest.CoreMatchers.is; +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.test.Mute.muteAll; @@ -54,86 +55,71 @@ public class RrdFactoryTest { private Config config; private Database db; - - TargetDirectory target = TargetDirectory.forTest( RrdFactoryTest.class ); + private String storeDir; @Rule - public TargetDirectory.TestDirectory testDirectory = target.testDirectory(); + public final TargetDirectory.TestDirectory directory = TargetDirectory.testDirForTest( getClass() ); @Rule public Mute mute = muteAll(); @Before public void setUp() throws IOException { - db = new WrappedDatabase( new ImpermanentGraphDatabase( - TargetDirectory.forTest( getClass() ).cleanDirectory( "rrd" ).getAbsolutePath()) ); + storeDir = directory.graphDbDir().getAbsolutePath(); + db = new WrappedDatabase( (GraphDatabaseAPI) new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir ) ); config = new Config(); } - @After - public void tearDown() - { - db.getGraph().shutdown(); - } - @Test public void shouldTakeDirectoryLocationFromConfig() throws Exception { - String expected = testDirectory.directory().getAbsolutePath(); - addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected ); + // Given + addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, storeDir ); TestableRrdFactory factory = createRrdFactory(); + // When factory.createRrdDbAndSampler( db, new NullJobScheduler() ); - assertThat( factory.directoryUsed, is( expected ) ); - } - - private void addProperty( String rrdbLocationPropertyKey, String expected ) - { - Map params = config.getParams(); - params.put( rrdbLocationPropertyKey, expected ); - config.applyChanges( params ); + // Then + assertThat( factory.directoryUsed, is( storeDir ) ); } @Test public void recreateDatabaseIfWrongStepsize() throws Exception { - String expected = testDirectory.directory().getAbsolutePath(); - - addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected ); + addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, storeDir ); TestableRrdFactory factory = createRrdFactory(); factory.createRrdDbAndSampler( db, new NullJobScheduler() ); - assertThat( factory.directoryUsed, is( expected ) ); + assertThat( factory.directoryUsed, is( storeDir ) ); } @Test public void shouldMoveAwayInvalidRrdFile() throws IOException { //Given - String expected = new File( testDirectory.directory(), "rrd-test").getAbsolutePath(); - addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected ); + File rrdDir = new File( directory.directory(), ServerInternalSettings.rrd_store.getDefaultValue() ); + assertTrue( rrdDir.mkdirs() ); + String rrdFilePath = new File( rrdDir, "rrd-test" ).getAbsolutePath(); + addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, rrdFilePath ); TestableRrdFactory factory = createRrdFactory(); - createInvalidRrdFile( expected ); - + createInvalidRrdFile( rrdFilePath ); //When RrdDbWrapper rrdDbAndSampler = factory.createRrdDbAndSampler( db, new NullJobScheduler() ); - //Then assertSubdirectoryExists( "rrd-test-invalid", factory.directoryUsed ); rrdDbAndSampler.close(); } - private void createInvalidRrdFile( String expected ) throws IOException + private void createInvalidRrdFile( String rrdFilePath ) throws IOException { // create invalid rrd - File rrd = new File( expected ); - RrdDef rrdDef = new RrdDef( rrd.getAbsolutePath(), 3000 ); + RrdDef rrdDef = new RrdDef( rrdFilePath, 3000 ); rrdDef.addDatasource( "test", DsType.GAUGE, 1, NaN, NaN ); rrdDef.addArchive( ConsolFun.AVERAGE, 0.2, 1, 1600 ); RrdDb r = new RrdDb( rrdDef ); @@ -141,36 +127,43 @@ private void createInvalidRrdFile( String expected ) throws IOException } @Test - public void shouldCreateRrdFileInTempLocationForImpermanentDatabases() throws IOException + public void shouldCreateRrdFileInTheConfiguredDirectory() throws Exception { // Given - String expected = testDirectory.directory().getAbsolutePath(); - TestableRrdFactory factory = createRrdFactory( expected ); + File rrdDir = new File( directory.directory(), ServerInternalSettings.rrd_store.getDefaultValue() ); + assertTrue( rrdDir.mkdirs() ); + String rrdFilePath = new File( rrdDir, "rrd" ).getAbsolutePath(); + addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, rrdFilePath ); + TestableRrdFactory factory = createRrdFactory(); // When factory.createRrdDbAndSampler( db, new NullJobScheduler() ); - // Then - assertThat( factory.directoryUsed, is( expected ) ); + //Then + assertThat( factory.directoryUsed, is( rrdFilePath ) ); } @Test - public void shouldCreateRrdFileInDbSubdirectory() throws Exception + public void shouldDeleteOldRrdFileFromDbDirectoryIfItExists() throws Exception { - String storeDir = testDirectory.directory().getAbsolutePath(); - db = new WrappedDatabase( (InternalAbstractGraphDatabase) - new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir ) ); + // given + File oldRrdFile = new File( storeDir, "rrd" ); + assertTrue( oldRrdFile.createNewFile() ); TestableRrdFactory factory = createRrdFactory(); // When factory.createRrdDbAndSampler( db, new NullJobScheduler() ); //Then - String rrdParent = new File( factory.directoryUsed ).getParent(); - - assertThat( rrdParent, is( storeDir ) ); + assertFalse( oldRrdFile.exists() ); } + private void addProperty( String rrdbLocationPropertyKey, String expected ) + { + Map params = config.getParams(); + params.put( rrdbLocationPropertyKey, expected ); + config.applyChanges( params ); + } private void assertSubdirectoryExists( final String directoryThatShouldExist, String directoryUsed ) { @@ -179,7 +172,7 @@ private void assertSubdirectoryExists( final String directoryThatShouldExist, St for ( String aList : list ) { - if (aList.startsWith( directoryThatShouldExist )) + if ( aList.startsWith( directoryThatShouldExist ) ) { return; } @@ -190,36 +183,23 @@ private void assertSubdirectoryExists( final String directoryThatShouldExist, St private TestableRrdFactory createRrdFactory() { - return new TestableRrdFactory( config, new File( testDirectory.directory(), "rrd" ).getAbsolutePath() ); - } - - private TestableRrdFactory createRrdFactory( String tempRrdFile ) - { - return new TestableRrdFactory( config, tempRrdFile ); + return new TestableRrdFactory( config ); } private static class TestableRrdFactory extends RrdFactory { public String directoryUsed; - private final String tempRrdFile; - public TestableRrdFactory( Config config, String tempRrdFile ) + public TestableRrdFactory( Config config ) { super( config, DevNullLoggingService.DEV_NULL ); - this.tempRrdFile = tempRrdFile; - } - - @Override - protected String tempRrdFile() throws IOException - { - return tempRrdFile; } @Override - protected RrdDbWrapper createRrdb( File inDirectory, boolean ephemeral, Sampleable... sampleables ) + protected RrdDbWrapper createRrdb( File inDirectory, Sampleable... sampleables ) { directoryUsed = inDirectory.getAbsolutePath(); - return super.createRrdb( inDirectory, ephemeral, sampleables ); + return super.createRrdb( inDirectory, sampleables ); } } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/RrdSamplerTest.java b/community/server/src/test/java/org/neo4j/server/rrd/RrdSamplerTest.java index 2e010512a36e..5bb1ef26d7be 100644 --- a/community/server/src/test/java/org/neo4j/server/rrd/RrdSamplerTest.java +++ b/community/server/src/test/java/org/neo4j/server/rrd/RrdSamplerTest.java @@ -28,7 +28,6 @@ import static org.mockito.Matchers.anyLong; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -49,22 +48,6 @@ public void canSampleADatabase() throws IOException verify( sample ).setValue( "myTest", 15 ); } - @Test - public void shouldIgnoreUnableToSampleExceptions() throws IOException - { - Sampleable failingSampleable = new FailingSamplable( "myTest" ); - - RrdDb rrd = mock( RrdDb.class ); - final Sample sample = mock( Sample.class ); - when( rrd.createSample( anyLong() ) ).thenReturn( sample ); - - RrdSampler sampler = new RrdSamplerImpl( rrd, failingSampleable ); - - sampler.updateSample(); - - verify( sample, never() ).setValue( "myTest", 15 ); - } - private class TestSamplable implements Sampleable { private String name; @@ -91,29 +74,4 @@ public DsType getType() return DsType.GAUGE; } } - - private class FailingSamplable implements Sampleable - { - private String name; - - private FailingSamplable( String name ) - { - this.name = name; - } - - public String getName() - { - return name; - } - - public double getValue() - { - throw new UnableToSampleException( "Failing operation" ); - } - - public DsType getType() - { - return DsType.GAUGE; - } - } } diff --git a/community/server/src/test/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBaseTest.java b/community/server/src/test/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBaseTest.java new file mode 100644 index 000000000000..0979bc2bf997 --- /dev/null +++ b/community/server/src/test/java/org/neo4j/server/rrd/sampler/DatabasePrimitivesSampleableBaseTest.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2002-2015 "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 . + */ +package org.neo4j.server.rrd.sampler; + +import org.junit.Test; + +import org.neo4j.kernel.AvailabilityGuard; +import org.neo4j.kernel.impl.store.NeoStore; +import org.neo4j.kernel.impl.transaction.state.NeoStoreProvider; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DatabasePrimitivesSampleableBaseTest +{ + @Test + public void shouldSampleOnlyWhenDatabaseIsAvailable() throws Throwable + { + // given + double expected = 42d; + TheDatabasePrimitivesSampleableBase sampleable = createSampleable( true, expected ); + + // when + double value = sampleable.getValue(); + + // then + assertEquals( expected, value, 0d ); + } + + @Test + public void shouldNotSampleWhenDatabaseIsNotAvailable() throws Throwable + { + // given + TheDatabasePrimitivesSampleableBase sampleable = createSampleable( false, 42d ); + + // when + double value = sampleable.getValue(); + + // then + assertEquals( 0d, value, 0d ); + } + + private TheDatabasePrimitivesSampleableBase createSampleable( final boolean isAvailable, double sampleValue ) + { + AvailabilityGuard guard = mock( AvailabilityGuard.class ); + when( guard.isAvailable( 0 ) ).thenReturn( isAvailable ); + return new TheDatabasePrimitivesSampleableBase( sampleValue, guard ); + } + + private static class TheDatabasePrimitivesSampleableBase extends DatabasePrimitivesSampleableBase + { + private final double sampleValue; + + public TheDatabasePrimitivesSampleableBase( double sampleValue, AvailabilityGuard guard ) + { + super( mock( NeoStoreProvider.class ), guard ); + this.sampleValue = sampleValue; + } + + @Override + protected double readValue( NeoStore neoStore ) + { + return sampleValue; + } + + @Override + public String getName() + { + return "name"; + } + } +}