private void Connect( IPEndPoint endPoint, TimeSpan timeout ) { var connection = new MongoConnection(null, endPoint); // no connection pool bool isPrimary; try { var isMasterCommand = new CommandDocument("ismaster", 1); var isMasterResult = connection.RunCommand(server, "admin.$cmd", QueryFlags.SlaveOk, isMasterCommand); isPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); if (!isPrimary && !server.Settings.SlaveOk) { throw new MongoConnectionException("Server is not a primary and SlaveOk is false"); } maxDocumentSize = isMasterResult.Response["maxBsonObjectSize", server.MaxDocumentSize].ToInt32(); maxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, maxDocumentSize + 1024); // derived from maxDocumentSize } catch { try { connection.Close(); } catch { } // ignore exceptions throw; } this.connection = connection; this.isPrimary = isPrimary; }
// note: this method will run on a thread from the ThreadPool private void QueryNodeWorkItem( object parameters ) { // this method has to work at a very low level because the connection pool isn't set up yet var args = (QueryNodeParameters)parameters; var response = new QueryNodeResponse { Address = args.Address, EndPoint = args.EndPoint }; try { var connection = new MongoConnection(null, args.EndPoint); // no connection pool try { var isMasterCommand = new CommandDocument("ismaster", 1); var isMasterResult = connection.RunCommand(server, "admin.$cmd", QueryFlags.SlaveOk, isMasterCommand); response.IsMasterResult = isMasterResult; response.Connection = connection; // might become the first connection in the connection pool response.IsPrimary = isMasterResult.Response["ismaster", false].ToBoolean(); response.MaxDocumentSize = isMasterResult.Response["maxBsonObjectSize", server.MaxDocumentSize].ToInt32(); response.MaxMessageLength = Math.Max(MongoDefaults.MaxMessageLength, response.MaxDocumentSize + 1024); // derived from maxDocumentSize if (server.Settings.ReplicaSetName != null) { var getStatusCommand = new CommandDocument("replSetGetStatus", 1); var getStatusResult = connection.RunCommand(server, "admin.$cmd", QueryFlags.SlaveOk, getStatusCommand); var replicaSetName = getStatusResult.Response["set"].AsString; if (replicaSetName != server.Settings.ReplicaSetName) { var message = string.Format("Host {0} belongs to a different replica set: {1}", args.EndPoint, replicaSetName); throw new MongoConnectionException(message); } } } catch { try { connection.Close(); } catch { } // ignore exceptions throw; } } catch (Exception ex) { response.Exception = ex; } args.ResponseQueue.Enqueue(response); }