Mongo embedded server: the single instance is not primary in replica set

Viewed 742

We use Mongo in our project (spring-boot-starter-data-mongodb 2.3.0.RELEASE) and we need to use it with @Transactional. So for testing we configure the following embedded Mongo with a replicaSet containing the single instance:

EmbeddedMongoConfig

@Configuration
@Slf4j
public class EmbeddedMongoConfig extends AbstractMongoClientConfiguration {


    @Value("${spring.data.mongodb.host:localhost}")
    private String dbHost;

    @Value("${spring.data.mongodb.database:sp-audit}")
    private String dbName;

    @Value("${spring.data.mongodb.port:27017}")
    private int dbPort;

    @Bean
    @Primary
    public IMongodConfig mongoConfigTest() throws IOException {
        return new MongodConfigBuilder()
            .version(Version.Main.PRODUCTION)
            .withLaunchArgument("--replSet", "rs0")
            .net(new Net(dbHost, dbPort, Network.localhostIsIPv6()))
            .cmdOptions(new MongoCmdOptionsBuilder()
                .useNoJournal(false)
                .build())
            .build();
    }

    @Bean
    public MongodExecutable embeddedMongoServer() throws IOException {
        MongodExecutable server = MongodStarter.getDefaultInstance().prepare(mongoConfigTest());
        server.start();
        return server;
    }

    @Bean
    @Primary
    public MongoClient mongoClient() {
        MongoClient client = MongoClients.create();
        MongoDatabase adminDatabase = client.getDatabase("admin");
        adminDatabase.runCommand(new Document("replSetInitiate", new Document()));
        log.info("embedded replicaSet status : " + adminDatabase.runCommand(new Document("replSetGetStatus", 1)));
        return client;
    }

    @Override
    protected String getDatabaseName() {
        return dbName;
    }
}

DatabaseConfiguration

@Bean
public MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
}

Everything looks fine, but tests are failed with an Exception:

com.mongodb.MongoClientException: Sessions are not supported by the MongoDB cluster to which this client is connected
    at com.mongodb.client.internal.MongoClientImpl.startSession(MongoClientImpl.java:128)
    at org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory.getSession(SimpleMongoClientDatabaseFactory.java:84)
    at org.springframework.data.mongodb.MongoTransactionManager.newResourceHolder(MongoTransactionManager.java:350)
    at org.springframework.data.mongodb.MongoTransactionManager.doBegin(MongoTransactionManager.java:139)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.startTransaction(AbstractPlatformTransactionManager.java:400)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.test.context.transaction.TransactionContext.startTransaction(TransactionContext.java:103)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:206)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit.jupiter.SpringExtension.beforeEach(SpringExtension.java:108)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$1(TestMethodTestDescriptor.java:161)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeMethodsOrCallbacksUntilExceptionOccurs$5(TestMethodTestDescriptor.java:197)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:197)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:160)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

The further research showed, that when it tries to start session, it checks if my server isPrimary or isSecondary, but gets null and fails (chain is MongoClientImpl.java:128 -> MongoClientDelegate.java:74 -> ClusterDescription.java:128)

Also, i have this in logs:

[cluster-ClusterId{value='5efcaf70e882a14d213c6a8f', description='null'}-localhost:27017] INFO  o.m.d.cluster.info() - Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=REPLICA_SET_GHOST, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2794500, setName='null', canonicalAddress=null, hosts=[], passives=[], arbiters=[], primary='null', tagSet=TagSet{[]}, electionId=null, setVersion=null, lastWriteDate=null, lastUpdateTimeNanos=366578580256200}

where you can see, that primary='null'.

Why it is null? How to make it be primary, as it is the single instance?

upd

embedded replicaSet status log message from mongoClient():

embedded replicaSet status : 
Document{{
    set=rs0, 
    date=Thu Jul 02 09:19:24 MSK 2020, 
    myState=2, 
    term=1, 
    syncingTo=, 
    syncSourceHost=, 
    syncSourceId=-1, 
    heartbeatIntervalMillis=2000, 
    optimes=Document{{lastCommittedOpTime=Document{{ts=Timestamp{value=0, seconds=0, inc=0}, t=-1}}, appliedOpTime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}, durableOpTime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}}}, 
    lastStableCheckpointTimestamp=Timestamp{value=0, seconds=0, inc=0}, 
    members=[
        Document{{_id=0, name=127.0.0.1:27017, health=1.0, state=2, stateStr=SECONDARY, uptime=1, optime=Document{{ts=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, t=-1}}, optimeDate=Thu Jul 02 09:19:23 MSK 2020, syncingTo=, syncSourceHost=, syncSourceId=-1, infoMessage=could not find member to sync from, configVersion=1, self=true, lastHeartbeatMessage=}}
    ], 
    ok=1.0, 
    operationTime=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, 
    $clusterTime=Document{{clusterTime=Timestamp{value=6844763807676366849, seconds=1593670763, inc=1}, signature=Document{{hash=org.bson.types.Binary@c98f581, keyId=0}}}}
    }
} 
1 Answers

As @Joe mentioned, the problem was so, that node inside the replicaset didn't have enough time to configure properly before entering the method annotated with @Transactional in tests.

I added Thread.sleep(3000) to mongoClient() and it worked for me. Not the best solution, but it's working at the moment

Related