public static List<ShardNode> GetShardConfigurationFromMongoC(NodeEndPoint nodeEndpoint) { List<ShardNode> r = new List<ShardNode>(); try { // We connect to a mongoC MongoServer server = CreateMongoServer(nodeEndpoint); MongoDatabase db = server["config"]; MongoCollection shards = db["shards"]; var cursor = shards.FindAllAs(typeof(BsonDocument)); foreach (var shard in cursor) { ShardNode cfg = new ShardNode(); cfg.ID = (((BsonDocument)(shard)))["_id"].AsString; cfg.Host = (((BsonDocument)(shard)))["host"].AsString; r.Add(cfg); } } catch (Exception ee) { Trace.TraceError("GetShardConfigurationFromMongoC : Error while getting inner shard configuration : " + ee.Message + " " + ee.InnerException == null ? "" : ee.InnerException.Message); throw; } return r; }
/// <summary> /// Vérifie l'état d'un noeud /// </summary> /// <param name="endpoint"></param> /// <param name="state"></param> /// <returns></returns> private static bool CheckReplicaSetState(NodeEndPoint endpoint, NodeState state) { try { var status = GetReplicaSetStatus(endpoint); if (status == null) return false; var member = status.Members.SingleOrDefault(m => endpoint == new NodeEndPoint(m.Adress,Int32.Parse(m.Port))); if (member != null && member.State == state) return true; else return false; } catch (Exception ex) { Trace.TraceError(string.Format("MongoHelper.CheckState : {0}", ex.Message)); return false; } }
private static string GenerateConnectionString(NodeEndPoint endpoint) { StringBuilder connectionStringBuilder = new StringBuilder(); connectionStringBuilder.Append("mongodb://"); connectionStringBuilder.Append(endpoint.ToString()); connectionStringBuilder.Append("/?slaveOk=true"); return connectionStringBuilder.ToString(); }
public static bool IsSecondary(NodeEndPoint endpoint) { //V3 : self is always primary return false; //return CheckReplicaSetState(endpoint, NodeState.Secondary); }
public static bool Shutdown(NodeEndPoint endpoint) { endpoint = new NodeEndPoint("127.0.0.1", endpoint.Port); try { MongoServer server = CreateMongoServer(endpoint); server.Shutdown(); return true; } catch (EndOfStreamException) { // we expect an EndOfStreamException when the server shuts down so we ignore it return true; } catch (Exception) { return false; } }
public static bool IsPrimary(NodeEndPoint endpoint) { //V3 : self is always primary return true; //return CheckReplicaSetState(endpoint, NodeState.Primary); }
/// <summary> /// Récupère le status des replicaSets /// </summary> /// <returns></returns> public static ReplicaSetStatus GetReplicaSetStatus(NodeEndPoint nodeEndpoint) { MongoServer server = CreateMongoServer(nodeEndpoint); try { var statusCommand = new CommandDocument { { "replSetGetStatus", 1 } }; CommandResult result = server.RunAdminCommand(statusCommand); if (!result.Ok) return null; ReplicaSetStatus status = new ReplicaSetStatus(); foreach (var item in result.Response) { switch (item.Name) { case "set": status.ReplicasetName = item.Value.AsString; break; case "date": status.Date = item.Value.AsDateTime; break; case "members": foreach (var item2 in item.Value.AsBsonArray) { ReplicaSetNode node = new ReplicaSetNode(); foreach (var member in item2.AsBsonDocument) { switch (member.Name) { case "_id": node.Id = member.Value.AsInt32; break; case "name": string[] fullAdress = member.Value.AsString.Split(':'); if (fullAdress.Length > 1) { node.Adress = fullAdress[0]; node.Port = fullAdress[1]; } else node.Adress = member.Value.AsString; break; case "health": node.Health = member.Value.AsDouble == 0 ? "Down" : "Up"; break; case "stateStr": node.StateStr = member.Value.AsString; break; case "state": node.State = ReplicaSetNode.GetStateFromInt(member.Value.AsInt32); break; case "optimeDate": node.OpTime = member.Value.AsDateTime; break; case "errmsg": node.ErrMsg = member.Value.AsString; break; default: break; } } status.Members.Add(node); } break; default: break; } } return status; } catch (Exception ex) { if (ex.Message.Contains("(EMPTYCONFIG)")) { ReplicaSetStatus status = new ReplicaSetStatus(); status.IsEmptyConfig = true; Trace.TraceWarning(string.Format("MongoHelper.GetStatus Exception : {0}", ex)); return status; } else { Trace.TraceError(string.Format("MongoHelper.GetStatus Exception : {0}", ex)); return null; } } }
public static string GetArgumentsForRoutingMongo(string ip, string port, NodeEndPoint[] configDbInstances, string chunkSize = "64") { // Get all config mongo server StringBuilder configEndpointsBuilder = new StringBuilder(); // sort config to have the same declaration order configDbInstances = configDbInstances.OrderBy(x => x.Host).ToArray(); foreach (var configEndpoint in configDbInstances) { configEndpointsBuilder.Append(string.Format("{0},", configEndpoint.ToString())); } // Delete the last comma string configEndpoints = configEndpointsBuilder.ToString().Substring(0, configEndpointsBuilder.Length - 1); return string.Format(@"--configdb {0} --port {1} --chunkSize {2} --quiet", configEndpoints, port, chunkSize); }
public static MongoServer CreateMongoServer(NodeEndPoint endpoint) { return MongoServer.Create(GenerateConnectionString(endpoint)); }
/// <summary> /// Lance la configuration du replicaSet et de ses noeuds /// </summary> /// <param name="nodeEndpoint">A node in the replicaSet</param> /// <param name="replicaSetName">The replicaset Name</param> public static bool ConfigureReplicaSet(NodeEndPoint nodeEndpoint, string ReplicaSetRoleName, string replicaSetName, List<NodeEndPoint> nodes, bool isReconfigure) { BsonArray membersDoc = new BsonArray(); // Get all the instances of the replica int serverId = 0; foreach (NodeEndPoint node in nodes) { string host = node.ToString(); BsonDocument nodeDoc; ////Get role associated with this replicaSetName //if (MongoDBAzurePlatform.Instance.GetFunctionnalDataRole(node, ReplicaSetRoleName) == MongoDBAzurePlatform.FunctionnalDataRole.NormalMemberLocalDrive) //{ // //Normal member // nodeDoc = new BsonDocument { { "_id", serverId }, { "host", host } }; //} //else //{ // //Hidden member // nodeDoc = new BsonDocument { { "_id", serverId }, { "host", host }, { "hidden" , true }, { "priority", 0 }}; //} //V3 nodeDoc = new BsonDocument { { "_id", serverId }, { "host", replicaSetName + ":" + node.Port } }; membersDoc.Add(nodeDoc); serverId++; } var configDoc = new BsonDocument { { "_id", replicaSetName }, { "members", membersDoc } }; // Reconfiguration of replicaSet : replSetReconfig // First configuration of replicaSet : replSetInitiate CommandDocument replicaSetCommand; if (isReconfigure) //replicaSetCommand = new CommandDocument { { "replSetReconfig", configDoc }, { "force", true } }; #warning : prendre en compte la version voir ci-dessous // db.adminCommand({ "replSetReconfig" : { "_id" : "replica2", "version" : 2, "members" : [{ "_id" : 0, "host" : "10.61.118.37:20001" }, { "_id" : 1, "host" : "10.61.102.163:20001" }, { "_id" : 2, "host" : "10.61.82.81:20001", "hidden" : true, "priority" : 0 }] } }) replicaSetCommand = new CommandDocument { { "replSetReconfig", configDoc }}; else replicaSetCommand = new CommandDocument { { "replSetInitiate", configDoc } }; Trace.TraceInformation("Config MONGOD: " + replicaSetCommand.ToString()); // Get the MongoServer to submit a command MongoServer server = CreateMongoServer(nodeEndpoint); CommandResult cmdResult = server.RunAdminCommand(replicaSetCommand); string response = "no response"; try { response = cmdResult.Response.AsString; } catch (Exception) { } Trace.TraceInformation(string.Format("COMMAND RESULT FOR REPLICASET CONFIGURATION : Error message : {0} - is Ok : {1} - Response: {2}", cmdResult.ErrorMessage, cmdResult.Ok, response)); // Check if there are errors if (!cmdResult.Ok) Trace.TraceError(string.Format("Command result error : {0}", cmdResult.ErrorMessage)); return cmdResult.Ok; }