Unable to connect to MongoDb using MongoClientSettings as parameter to MongoClient - mongodb

I am developing a C# MVC Web API which uses MongoDb as backend.I tried connecting to my mongodb database using
MongoClient mongoClient = new MongoClient(connectionString)
where connectionstring is in format : mongodb://Username:Password#hostname.eastus.cloudapp.azure.com
Mongo db is hosted in a virtual machine in Azure.I am able to connect to the database and all works good.But I am getting frequent exceptions:
"MongoDb.driver.MongoConnectionException".An exception occurred while
receivinf a message from server--->System.IO.IOException:Unable to
read data from the transport connection : A connection attempt failed
because the connected party did not properly respond after a period of
time,......"
So after a bit of research I have learnt that Azure is killing idle connections and I have to set MaxConnectionIdleTime.
In order to set MaxConnectionIdleTime I decided to connect to Mongodb in the below way
var credential = MongoCredential.CreateCredential("dbname", "UserName", "Password");
var settings = new MongoClientSettings
{
Credentials = new[] { credential },
Server = new MongoServerAddress("HostName", 27017),
MaxConnectionIdleTime = new TimeSpan(0, 3, 0)
};
MongoClient mongoClient = new MongoClient(settings);
In this case I am using the same username,password combination given in the connection string which I used to connect before.
While trying to connect here I am getting inner Exception:
MongoDB.Driver.MongoAuthenticationException: "Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1".

"MongoDb.driver.MongoConnectionException".An exception occurred while receivinf a message from server--->System.IO.IOException:Unable to read data from the transport connection : A connection attempt failed because the connected party did not properly respond after a period of time,....
The reason behind this exception is when hosted in Azure,Azure tries to kill the idle connections but the C# driver is not aware of this.The driver tries to execute queries on the killed connections without knowing the connection is not existing.
The solution that worked out for me is to set maxIdleTimeMS=45000 in connection string.
This way driver will not use a connection which has been idle for long time.
Here is the connection string that worked out for me
connectionString="Username:Password#hostname.eastus.cloudapp.azure.com/?connectTimeoutMS=30000&socketTimeoutMS=30000&waitQueueTimeoutMS=30000&maxIdleTimeMS=45000"

I have had a similar error with my Azure hosted MongoDb (Cosmos Db). It turned out to be network settings such that I had blocked all access. Changing it to Allow access from "All networks" fixed the issue.
The error is very misleading, I would have expected a connection timeout.
A timeout occured after 30000ms selecting a server using
CompositeServerSelector{ Selectors =
MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector,
LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000
} }. Client view of cluster state is { ClusterId : "1", ConnectionMode
: "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers :
[{ ServerId: "{ ClusterId : 1, EndPoint :
"Unspecified/XXXX.documents.azure.com:10255" }", EndPoint:
"Unspecified/XXXX.documents.azure.com:10255", State: "Disconnected",
Type: "Unknown", HeartbeatException:
"MongoDB.Driver.MongoConnectionException: An exception occurred while
opening a connection to the server. --->
MongoDB.Driver.MongoAuthenticationException: Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1. --->
MongoDB.Driver.MongoCommandException: Command saslContinue failed: Not
Authenticated.
To troubleshot I tried from MongoDb Compass as well and that didn't work either, showing me it wasn't the code.

Related

Cannot connect to Atlas MongoDB from Azure Functions

I just created an Azure Function that should connect to my instance of MongoDB on Atlas, basically following this tutorial:
https://www.mongodb.com/blog/post/how-to-integrate-azure-functions-with-mongodb
From my local development with Visual Studio, everything works fine and I can connect to the Atlas environment, but when I deploy the code on Azure, the following exception raises:
A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017" }", EndPoint: "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
---> MongoDB.Driver.MongoConnectionException: An exception occurred while receiving a message from the server.
---> System.IO.EndOfStreamException: Attempted to read past the end of the stream.
If I instead set the Network Access to "everywhere", again everything works fine.
Now, in the Network Access panel of Atlas, I added the IPs retrieved from the Azure Portal under my function app => Networking => Inbound traffic and Outbound traffic (a total of 1 IP for inbound and 3 IPs for outbound).
But adding those 4 IPs has not solved the issue.
What else should I do?
If you are using static IP, for a workaround, you can check this: How do I set a static IP in Functions?
You can also set up a Private Endpoint and for the security of the database credentials check secrets engine integration using vault.
You can refer to How to connect Azure Function with MongoDB Atlas ,Azure functions unable to connect with Mongo Db Atlas M10 and How to connect Azure Function with MongoDB Atlas

Error: Unable to connect to kuzzle server at 127.0.0.1:7512: Connection lost. (ws status=503)

i receive lot of :
[kuzzle networkError] : Error: Unable to connect to kuzzle server at 127.0.0.1:7512: Connection lost. (ws status=503)
since i start using apikey from createApikey, may it be related to a bad usage of the token ?
seems to happen after every successful query

C# says invalid certificate error on Linux Centos

We are using C# driver "Mongo Db driver 2.9.2" in C# API(.NET core version 2.2) deployed in Linux CentOS to connect to Mongo server 4.2 deployed on Linux CentOS. TLS is enabled on Mongo and self signed certificates are used. Same code and certificates are working from Windows machine but on Linux we are getting following error. Please suggest:
A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : \"1\", ConnectionMode : \"Automatic\", Type : \"Unknown\", State : \"Disconnected\", Servers : [{ ServerId: \"{ ClusterId : 1, EndPoint : \"Unspecified/ServerName\" }\", EndPoint: \"Unspecified/ip-ServerName\", State: \"Disconnected\", Type: \"Unknown\", HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.\n at System.Net.Security.SslState.StartSendAuthResetSignal
We could resolve this by using server certificate instead of wild card certificate.

Unable to connect to MongoLab from java driver

I have Mongolab account , there is only one user in that account.
I can connect to the DB using MongoChef tool, however when I try and connect to that DB from within Eclipse using the java driver 3.2.0 , I continuously get an authentication failure. I get the following error.I am on Java 7 .
EDIT
Java Code used to connect to the MongoLab hosted MongoDB instance.
String mongoURL = new StringBuilder().append("mongodb://").append(mongoUserName).append(":").append(mongoPassword).append("#").append(mongoServer).append(":").append(mongoPort).append("/").append(dbName).toString();
System.out.println(" The Mongo URL is " +mongoURL);
MongoClientURI uri = new MongoClientURI(mongoURL);
MongoClient mongo = new MongoClient(uri);
Exception received when trying to connect.
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while
waiting for a server that matches
ReadPreferenceServerSelector{readPreference=primary}. Client view of
cluster state is {type=UNKNOWN,
servers=[{address=ds061974.mongolab.com:61974, type=UNKNOWN,
state=CONNECTING, exception={com.mongodb.MongoSecurityException:
Exception authenticating MongoCredential{mechanism=null,
userName='xxxx', source='hidden', password=<hidden>,
mechanismProperties={}}}, caused by
{com.mongodb.MongoCommandException: Command failed with error 18:
'Authentication failed.' on server ds061974.mongolab.com:61974. The
full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication
failed." }}}]
try this code:
ServerAddress addr = new ServerAddress(mongoServer, mongoPort);
MongoCredential credential = MongoCredential.createMongoCredential(
mongoUserName, mongoPassword, dbName);
MongoClient mongoClient = new MongoClient(addr, Arrays.asList(credential), null);

MongoDB: A timeout occured after 30000ms selecting a server using CompositeServerSelector

I'm completely stumped. I am using the latest c# drivers (2.3.0.157) and the latest MongoDB (3.2). The DB is running as a standalone setup with no replication or sharding. I've tried running locally on Windows as well as remotely on Amazon LINUX.
I continue to get a timeout error but mysteriously sometimes it just works (maybe once every 20 - 30 attempts).
I am creating the connection as such:
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ToString();
private static readonly string DataBase = ConfigurationManager.ConnectionStrings["MongoDBDatabase"].ToString();
private static IMongoDatabase _database;
public static IMongoDatabase GetDatabase(string database)
{
if (_database == null)
{
var client = new MongoClient(ConnectionString);
_database = client.GetDatabase(database);
}
return _database;
}
And calling it like this:
public static List<Earnings> GetEarnings()
{
var db = GetDatabase(DataBase);
if (db == null) return new List<Earnings>();
var logs = db.GetCollection<Earnings>("EarningsData");
var all = logs.Find(new BsonDocument()).ToEnumerable().OrderBy(x => x.Symbol).ToList();
return all;
}
And it'll time out on the logs.Find part of the method. Here's the full message:
Additional information:
A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode = Primary, TagSets = [] } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Direct", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "XX.XX.XX.XX:27017" }", EndPoint: "XX.XX.XX.XX:27017", State: "Disconnected", Type: "Unknown" }] }.
I've tried using the fully qualified host name, adding connect=direct and connect=replicaSet to the connection string, using MongoClientSettings instead of the connection string and everything else I could possibly find on forums and StackOverflow. I'm at a loss and not even sure where to look next. Any advice?
I should also add, I can connect fine from the command line and RoboMongo...
We finally figured out how to work around this issue but I still don't understand what's happening. In our case, we have a server that spawns ~10 signalr hubs that get their data from MongoDB. It seems that when the app was starting up it was making several rapid calls to MongoDB to get the initial set of data and while it would occasionally worked, most times it didn't. We ended up solving this by adding a one second delay between loading each SignalR hub so the initial query was delayed a bit and we didn't have contention.
The weird thing about this is none of these collections have a large amount of data and the initial load is usually < 100 documents per collection (max). Once things are initialized it doesn't seem to matter how often we hit MongoDB. It just seems to be on the initial load.
An old topic but I found I was getting a similar error (2.11.0-beta2, netcoreapp3.1) and then I realised DocumentDb is restricted to connectivity within the same VPC. It's mentioned here.
https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-from-outside-a-vpc.html
Amazon DocumentDB (with MongoDB compatibility) clusters are deployed within an Amazon Virtual Private Cloud (Amazon VPC). They can be accessed directly by Amazon EC2 instances or other AWS services that are deployed in the same Amazon VPC. Additionally, Amazon DocumentDB can be accessed by EC2 instances or other AWS services in different VPCs in the same AWS Region or other Regions via VPC peering.
Check you're in the same VPC. If not, good luck.