How to switch authentication mechanism in mongo during runtime? - java

I want to test if my MongoClient has authenticated correctly using default authentication mechanism and if it's not I want to try connecting with different one.
I have following code used for openning mongo connection which uses MONGODB-CR:
MongoCredential credential = MongoCredential.createMongoCRCredential(this.user, this.db, this.pass.toCharArray());
ServerAddress serverAddress = new ServerAddress(this.host, this.port.intValue());
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(new MongoCredential[]{credential}));
I need to find a way to test if authentication was complete. If it was not I want to try with different mechanism - SCRAM-SHA-1. The problem is I dont know how to test connection. Calling most of mongoClient methods leads to MongoCommandException:
com.mongodb.MongoSecurityException: Exception authenticating
at com.mongodb.connection.NativeAuthenticator.authenticate(NativeAuthenticator.java:48)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.NativeAuthenticator.authenticate(NativeAuthenticator.java:46)
... 5 common frames omitted
But this is actually not an Exception It's just information in logs, so I'm not able to catch it.
Any ideas how to test if MongoClient has authenticated correctly?

Related

Not able to connect oracle Database while using Cluster type HOST

I'm facing the following errors while connecting oracle DB, I'm using spring boot JDBC template to connect to database. The errors are below,
Exception in thread "main" java.lang.Exception: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at com.falabella.util.OracleDB.main(OracleDB.java:70)
Caused by: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
Caused by: java.net.UnknownHostException: NODE-01: nodename nor servname provided, or not known
Below are my finding, My database server host having the cluster and it has two nodes, like below,
Cluster (wood.clsuter.com)
| NODE01 (wood-01)
| NODE02 (wood-02)
My connection string is like this, jdbc:oracle:thin:#wood-clsuter.com:1531/service_name
When I'm using the cluster name in the connection string, I'm facing the below error
Caused by: java.net.UnknownHostException: wood-01: nodename nor servname provided, or not known
Whereas if I use any of the node name in the connection string , able to connect Data base without any issue, the working connection string is like below,
jdbc:oracle:thin:#wood-01.com:1531/service_name or
jdbc:oracle:thin:#wood-02.com:1531/service_name
Since I need to use my DB requests as load balancing, I need to use the cluster name instead of slave nodes,
I would like to know the root cause of this issue, such kind of production environment issues,
Could you please help me out with this?
You need to change connect string to:
"jdbc:oracle:thin:#(DESCRIPTION=(FAILOVER=ON)(LOAD_BALANCE=ON)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=wood-01.com)(PORT = 1531))(ADDRESS = (PROTOCOL = TCP)(HOST = wood-02.com)(PORT = 1531)))(CONNECT_DATA=(SERVICE_NAME =service_name)(FAILOVER_MODE=(TYPE=select)(METHOD=basic))))"

Socket timeout with mongo DB after 30 mins of inactivity

After 30 mins of inactivity or so I start getting the below error when I try to insert into mongo, When I try again it starts to work. Error Below. I'm on Azure:
[INFO ] 2018-09-10T12:00:43,188 [http-nio-8080-exec-6] connection - Closed connection [connectionId{localValue:3, serverValue:26}] to XX.XX.XX.XX:27017 because there was a socket exception raised by this connection.
[ERROR] 2018-09-10T12:00:43,189 [http-nio-8080-exec-6] [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Timeout while receiving message; nested exception is com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message] with root cause
java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method) ~[?:1.8.0_181]
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[?:1.8.0_181]
ava.net.SocketTimeoutException: Read timed out
t java.net.SocketInputStream.read(SocketInputStream.java:171) ~[?:1.8.0_181]
at java.net.SocketInputStream.read(SocketInputStream.java:141) ~[?:1.8.0_181]
Here is how I initialize my mongo Template:
#Bean
public MongoDbFactory mongoDbFactory() {
String[] addresses = mongoUri.split(",");
List<ServerAddress> servers = new ArrayList<>();
for (String address : addresses) {
String[] split = address.trim().split(":");
servers.add(new ServerAddress(split[0].trim(), Integer.parseInt(split[1].trim())));
}
MongoClientOptions.Builder mongoOperations = MongoClientOptions.builder();
mongoOperations.socketTimeout(1000 * 20); // I tried to increase the socket timeout to see if it helps but no help either
mongoOperations.connectTimeout(1000 * 10);
MongoClient mongoClient = new MongoClient(servers, MongoCredential.createCredential(userName, dbName, password.toCharArray()), mongoOperations.build());
return new SimpleMongoDbFactory(mongoClient, dbName);
}
#Bean
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(mongoDbFactory());
}
My mongod version is 3.6.4 and I'm using the same version of java driver.
I tried to increase/decrease the tcp_keepalive_time setting as provided in the docs using
sudo sysctl -w net.ipv4.tcp_keepalive_time=120 but no help either.
ohk. so we found that the mongo java driver jar was older than the mongo server we were using which was causing this issue. make sure that the driver supports the version of mongo server.

java.io.IOException at RabbitMq connectionFactory initialization

When I try to make a .newConnection() to a rabbitMQ server I get the follwing error:
java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:126)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:122)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:373)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:134)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:997)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:956)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:914)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1068)
... ...
Caused by: com.rabbitmq.client.ShutdownSignalException: connection
error at
com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
at
com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
at
com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:494)
at
com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:315)
at
com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:64)
at
com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:134)
My code snippet is:
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setUsername("myUser");
connectionFactory.setUsername("myPass");
connectionFactory.setHost("rabbitmq.test.com"); //also tried with the IP
connectionFactory.setPort(customPort);
connectionFactory.setVirtualHost("/myVHost");
Connection connection = connectionFactory.newConnection();
I also tried the compact setup:
connectionFactory.setUri("amqp://myUser:myPass#rabbitmq.test.com:customPort/myVHost");
Now...the strange part is that if I log into GUI, I can access the queues for that vhost...
Any ideas on this situation please? Thanks in advance.
You seem to use the setUsername() function for setting the password.

solr indexing - connection timeout

I am loading data in Solr from MongoDB.
SolrInputDocument doc = new SolrInputDocument();
BasicDBObject record = (BasicDBObject) cursor.next();
doc.addField("_id", record.get("_id"));
// add more fields
server.add(doc);
server.commit();
I am getting below exception.
Exception in thread "main" org.apache.solr.client.solrj.SolrServerException: java.net.ConnectException: Connection timed out: connect
at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:483)
at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:244)
at org.apache.solr.client.solrj.request.AbstractUpdateRequest.process(AbstractUpdateRequest.java:105)
at org.apache.solr.client.solrj.SolrServer.add(SolrServer.java:64)
Caused by: java.net.ConnectException: Connection timed out: connect
This code worked for me before. I did not change anything in the code. But now its giving error after adding few documents. What's wrong here?

Mongo Java Driver creates three clients

I'm creating a application scoped mongo client to reuse it in my app. The first time the mongo client is accessed I see the following log entires in my server log indicating three clients are created. The third client is the one that is created in application scope as you can see by the preceding info message.
I can additionally see in the mongodb logs that 2 additional connections are opened and not closed or reused by succeeding calls.
[08.09.14 20:09:57:060 CEST] 000000c9 Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
[08.09.14 20:09:57:060 CEST] 000001ba Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
[08.09.14 20:09:57:070 CEST] 000000c9 mongodb I multiple Mongo instances for same host, jmx numbers might be off
[08.09.14 20:09:57:070 CEST] 000001ba mongodb I multiple Mongo instances for same host, jmx numbers might be off
[08.09.14 20:09:57:111 CEST] 000001ba SystemOut O INFO MongoDBConnection initializeClient - Creating mongo client for localhost:27017
[08.09.14 20:09:57:111 CEST] 000001ba Mongo I Creating Mongo instance (driver version 2.11.4) with authority MongoAuthority{type=Direct, serverAddresses=[localhost/127.0.0.1:27017], credentials={credentials={}}} and options MongoOptions{description='null', connectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, maxWaitTime=120000, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, autoConnectRetry=false, maxAutoConnectRetryTime=0, slaveOk=false, readPreference=primary, dbDecoderFactory=DefaultDBDecoder.DefaultFactory, dbEncoderFactory=DefaultDBEncoder.DefaultFactory, safe=false, w=0, wtimeout=0, fsync=false, j=false, socketFactory=javax.net.DefaultSocketFactory#f6fb9709, cursorFinalizerEnabled=true, writeConcern=WriteConcern { "getlasterror" : 1} / (Continue Inserting on Errors? false), alwaysUseMBeans=false}
Please also note the different server addresses in the logs: serverAddresses=[localhost/127.0.0.1:27017] and serverAddresses=[/127.0.0.1:27017]. I'm setting localhost as the host name in my code.
Below you find the producer method for the mongo client.
#Produces
#ApplicationScoped
public MongoClient initializeClient() {
log.info(String.format("Creating mongo client for %s:%s", host, port));
MongoClient client = null;
try {
client = new MongoClient(host, port);
}
catch (UnknownHostException e) {
log.error(e);
}
return client;
}
Does someone know what causes these two other instances to be created and how can I prevent that?

Categories