/// <summary> ///Initializes the instance of <see cref="Alachisoft.NCache.Web.Caching.CacheServerInfo"/> for this application. /// </summary> /// <param name="name">String IP/Name of the server to be connected with</param> /// <param name="port">Port for the server to be connected with </param> public CacheServerInfo(string name, int port) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("name/IP cannot be null"); } if (port < 1) throw new ArgumentException("Invalid value of port.Port cannot be less than 0"); ServerInfo = new RemoteServer(name, port); }
public void RemoveServer(RemoteServer server) { if (_servers != null && server != null) { lock (_servers.SyncRoot) { if (_servers.Contains(server)) { RemoteServer existingServer = (RemoteServer)_servers[_servers.IndexOf(server)]; if (!existingServer.IsUserProvided) { if (_currentServer == (_servers.Count - 1)) { _currentServer--; } _servers.Remove(server); } } } } }
public RemoteServer GetMappedServer(string ip, int port) { RemoteServer mapping = null; if (_mappedServer != null || _mappedServer.Count != 0) { foreach (RemoteServer rm in _mappedServer.Keys) { if (rm.Name.Equals(ip)) { mapping = new RemoteServer(); mapping = (RemoteServer)_mappedServer[rm]; } } } // Incase the map is null the method will return the original IP and Port if (mapping == null) { mapping = new RemoteServer(ip, port); } return(mapping); }
// function to return the initial server and port to connect with internal RemoteServer GetInitialServer() { RemoteServer serverInfo = new RemoteServer(); if (_clientConfig.initParam.ServerList.Length > 0) { serverInfo = _clientConfig.initParam.ServerList[0].ServerInfo; return serverInfo; } else if (_clientConfig.initParam.ServerList != null && _clientConfig.initParam.ServerList.Length > 0) { serverInfo = new RemoteServer(_clientConfig.initParam.ServerList[0].Name, _clientConfig.initParam.ServerList[0].Port); return serverInfo; } return serverInfo; }
private void StartBalancingClients(object state) { try { CommandResponse response = (CommandResponse)state; //Copied entire logic from ProcessResponse->Node_Joined_Event to this method because of Azure Common Client. RemoteServer newServerJoined = new RemoteServer(); if (response.ServerPort > 0) { if (_clientConfig.IPMappingConfigured) { this.GetServerMapping(null, false); RemoteServer rm = _clientConfig.GetMappedServer(response.ServerIPAddress.ToString(), response.ServerPort); newServerJoined = rm; } else { newServerJoined = new RemoteServer(response.ServerIPAddress, response.ServerPort); } _clientConfig.AddServer(newServerJoined); } if (response.ReconnectClients && _clientConfig.BalanceNodes) { bool isReleaseLock = false; try { this._lock.AcquireWriterLock(Timeout.Infinite); isReleaseLock = true; this._connection.StatusLatch.SetStatusBit(ConnectionStatus.Connecting | ConnectionStatus.LoadBalance, ConnectionStatus.Connected | ConnectionStatus.Disconnected); int totalTimeToWait = _operationTimeout; //_clientConfig.ResponseWaitTime; int timeSlice = 2000; int nextInterval = NextWaitInterval(ref totalTimeToWait, timeSlice); do { if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Info("Broker.StartBalancingClients", "total wait time remaining: " + totalTimeToWait.ToString()); _logger.NCacheLog.Info("Broker.StartBalancingClients", "current wait interval: " + nextInterval.ToString()); } Thread.Sleep(nextInterval); lock (this._requestTable.SyncRoot) { if (this._requestTable.Count == 0) { break; } if (_logger.IsDetailedLogsEnabled) _logger.NCacheLog.Info("Broker.StartBalancingClients", "Responses remaining: " + this._requestTable.Count); } nextInterval = NextWaitInterval(ref totalTimeToWait, timeSlice); } while (nextInterval > 0); ResetBroker(this._serverIP); _connection.StatusLatch.SetStatusBit(ConnectionStatus.Connecting, ConnectionStatus.LoadBalance); _connection.Disconnect(); Thread.Sleep(5000); Exception exception = null; if (!ConnectRemoteServer(this._connection, NodeIP, NewServerPort, false, false, true, ref exception)) { this._lock.ReleaseWriterLock(); isReleaseLock = false; TryNextServer(); } else this._connection.StatusLatch.SetStatusBit(ConnectionStatus.Connected, ConnectionStatus.Connecting); } finally { if (isReleaseLock) this._lock.ReleaseWriterLock(); } } } catch (Exception e) { } }
private Connection ReconnectServer(Connection connection, RemoteServer nextServer) { bool connected = false; int retries = this._connectionRetries; OperationNotSupportedException exceptionThrown = null; try { _lock.AcquireWriterLock(_connectionMutexTimeout); } catch (Exception) { return connection; //lock could not be granted before the timeout expires. } try { CheckRetryConnectionDelay(); //[ Checking if retry connection Interval is over or not] if (!_retryConnection) return connection; while (retries-- > 0 && !_isDisposing) { try { if (!connection.IsConnected) { connection.StatusLatch.SetStatusBit(ConnectionStatus.Connecting, ConnectionStatus.Connected | ConnectionStatus.Disconnected); if (nextServer == null) break; if (nextServer.IP != null) { for (int i = 0; i < nextServer.PortRange; i++) { try { if (!connected) { Exception exception = null; connected = ConnectRemoteServer(connection, nextServer.IP, nextServer.Port + i, this._balanceNode, this._importHashmap, true, ref exception); } if (connected) { break; } } catch (OperationNotSupportedException operationException) { exceptionThrown = operationException; } } } System.Threading.Thread.Sleep(_retryInterval); continue; } else { connected = true; break; } } catch (Exception) { throw; } } } catch (Exception) { throw; } finally { byte setStatus = connected ? ConnectionStatus.Connected : ConnectionStatus.Disconnected; byte unsetStatus = (byte) ((!connected ? ConnectionStatus.Connected : ConnectionStatus.Disconnected) | ConnectionStatus.Connecting); connection.StatusLatch.SetStatusBit(setStatus, unsetStatus); _retryConnection = connected; //[ Connection is up again so we can retry ] _lock.ReleaseWriterLock(); } return connection; }
public void RemoveServer(RemoteServer server) { if (_servers != null && server != null) { lock (_servers.SyncRoot) { if (_servers.Contains(server)) { RemoteServer existingServer = (RemoteServer)_servers[_servers.IndexOf(server)]; if (!existingServer.IsUserProvided) { if (_currentServer == (_servers.Count - 1)) _currentServer--; _servers.Remove(server); } } } } }
private void LoadRemoteServerMappingConfig(XmlNodeList cacheConfig) { Hashtable updatedServerMap = new Hashtable(); try { for (int i = 0; i < cacheConfig.Count; i++) { XmlNode currentConfig = cacheConfig.Item(i); if (currentConfig.Name.Equals("server-end-point")) { XmlNodeList _mappingConfig = currentConfig.ChildNodes; for (int j = 0; j < _mappingConfig.Count; j++) { XmlNode mapNodeConfig = _mappingConfig.Item(j); if (mapNodeConfig.Name.Equals("end-point")) { RemoteServer publicServer = new RemoteServer(); RemoteServer privateServer = new RemoteServer(); try { privateServer.Name = mapNodeConfig.Attributes["private-ip"].InnerText; privateServer.Port = Convert.ToInt32(mapNodeConfig.Attributes["private-port"].InnerText); publicServer.Name = mapNodeConfig.Attributes["public-ip"].InnerText; publicServer.Port = Convert.ToInt32(mapNodeConfig.Attributes["public-port"].InnerText); } catch (Exception) { } if (privateServer.Name != null || privateServer.Port != null) { lock (_mappedServer.SyncRoot) { if (_mappedServer.Count != 0) { foreach (RemoteServer rm in _mappedServer.Keys) { if (!rm.Name.Equals(privateServer.Name)) { updatedServerMap.Add(privateServer, publicServer); } } } else { _mappedServer.Add(privateServer, publicServer); } } } } } _isAzureRemoteClient = true; } } foreach (RemoteServer rms in updatedServerMap.Keys) { _mappedServer.Add(rms, updatedServerMap[rms]); } } catch (Exception) { } }
/// <summary> /// Try to connect with the server. The connection object will be used to connect with the ip /// address on port provided /// </summary> /// <param name="connection">This object will be used to connect with server</param> /// <param name="server">remote server information</param> /// <param name="registerNotifs">if re registring of events is needed</param> /// <returns>true if connecion is established, false otherwise</returns> private bool ConnectRemoteServer(Connection connection, RemoteServer server, bool registerNotifs) { bool connected = false; Exception exception = null; if (server != null && server.IP != null) { connected = ConnectRemoteServer(connection, server.IP, server.Port, this._balanceNode, this._importHashmap, registerNotifs, ref exception); } return connected; }
internal void StartServices(string cacheId, string server, int port) { this._cacheId = cacheId; if ( !string.IsNullOrEmpty( System.Configuration.ConfigurationSettings.AppSettings.Get( "NCacheClient.AsynchronousEventNotification"))) { try { _notifyAsync = Convert.ToBoolean( System.Configuration.ConfigurationSettings.AppSettings.Get( "NCacheClient.AsynchronousEventNotification")); } catch (Exception ex) { throw new Exception("Invalid value specified for NCacheClient.AsynchronousEventNotification."); } if (!_notifyAsync) { if ( !string.IsNullOrEmpty( System.Configuration.ConfigurationSettings.AppSettings.Get( "NCacheClient.NumberofEventProccesingThreads"))) { try { _asyncProccesorThreadCount = Convert.ToInt32( System.Configuration.ConfigurationSettings.AppSettings.Get( "NCacheClient.NumberofEventProccesingThreads")); } catch (Exception e) { throw new Exception( "Invalid value specified for NCacheClient.NumberofEventProccesingThreads."); } } if (_asyncProccesorThreadCount <= 0) _asyncProccesorThreadCount = 1; if (_asyncProccesorThreadCount > 5) _asyncProccesorThreadCount = 5; _eventProcessor = new AsyncProcessor(_asyncProccesorThreadCount); _eventProcessor.Start(); } } //Check the type of license the application try { _clientConfig.LoadConfiguration(); } catch (Exception) { } bool enable_logs = false; bool detailed_logs = false; if (System.Configuration.ConfigurationSettings.AppSettings.Get("enableNCWebLogs") != null) { enable_logs = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["enableNCWebLogs"]); } else enable_logs = _clientConfig.EnableClientLogs; if (System.Configuration.ConfigurationSettings.AppSettings.Get("enableDetailedNCWebLogs") != null) { detailed_logs = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["enableDetailedNCWebLogs"]); } else detailed_logs = _clientConfig.EnableDetailedClientLogs; InitializeLogs(enable_logs, detailed_logs); if (System.Configuration.ConfigurationSettings.AppSettings.Get("enablePerfStats") != null) { _perfStatsEnabled = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["enablePerfStats"]); } if (_perfStatsEnabled) { _perfStatsColl.InitializePerfCounters(); } int conTimeout = _connectionRetries*(_connectionTimeout + _retryInterval); if (conTimeout > 0) _connectionMutexTimeout = conTimeout; if (_operationTimeout < 60000) _operationTimeout = 60000; //minimum timeout is 60 seconds. _connection = new Connection(_commandReieved, _serverLost, _logger, _perfStatsColl, _responseIntegrator, _clientConfig.BindIP); RemoteServer remoteServer = new RemoteServer(server, port); if (this._importHashmap) { this._processor = new AsyncProcessor(); } if (remoteServer.IP != null) { remoteServer.IsUserProvided = true; try { ConnectRemoteServer(_connection, remoteServer, true); } catch (OperationNotSupportedException oe) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.StartServices", oe.ToString()); } } if (!IsConnected) { try { TryNextServer(); } catch (OperationNotSupportedException oe) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.StartServices", oe.ToString()); throw; } } }
internal void AddMappedServers(List<NCache.Config.Mapping> mappedServerList) { Hashtable updatedServerMap = new Hashtable(); if (mappedServerList != null) { foreach (NCache.Config.Mapping node in mappedServerList) { RemoteServer publicServer = new RemoteServer(); RemoteServer privateServer = new RemoteServer(); privateServer.Name = node.PrivateIP; privateServer.Port = node.PrivatePort; publicServer.Name = node.PublicIP; publicServer.Port = node.PublicPort; if (privateServer.Name != null || privateServer.Port != null) { lock (_mappedServer.SyncRoot) { if (_mappedServer.Count != 0) { bool keyExists= false; foreach (RemoteServer rm in _mappedServer.Keys) { if (!rm.Name.Equals(privateServer.Name)) { keyExists = false; } else { keyExists = true; RemoteServer originalPublicServer = (RemoteServer)_mappedServer[rm]; String existingServer = originalPublicServer.Name + ":" + originalPublicServer.Port.ToString(); String newServer = publicServer.Name + ":" + publicServer.Port.ToString(); if (!existingServer.Equals(newServer)) { updatedServerMap.Add(privateServer, publicServer); } break; } } if (keyExists == false) { updatedServerMap.Add(privateServer, publicServer); } } else { _mappedServer.Add(privateServer, publicServer); } } } } foreach (RemoteServer rms in updatedServerMap.Keys) { _mappedServer[rms] = updatedServerMap[rms]; } } }
private void LoadRemoteServerMappingConfig(XmlNodeList cacheConfig) { Hashtable updatedServerMap = new Hashtable(); try { for (int i = 0; i < cacheConfig.Count; i++) { XmlNode currentConfig = cacheConfig.Item(i); if (currentConfig.Name.Equals("server-end-point")) { XmlNodeList _mappingConfig = currentConfig.ChildNodes; for (int j = 0; j < _mappingConfig.Count; j++) { XmlNode mapNodeConfig = _mappingConfig.Item(j); if (mapNodeConfig.Name.Equals("end-point")) { RemoteServer publicServer = new RemoteServer(); RemoteServer privateServer = new RemoteServer(); try { privateServer.Name = mapNodeConfig.Attributes["private-ip"].InnerText; privateServer.Port = Convert.ToInt32(mapNodeConfig.Attributes["private-port"].InnerText); publicServer.Name = mapNodeConfig.Attributes["public-ip"].InnerText; publicServer.Port = Convert.ToInt32(mapNodeConfig.Attributes["public-port"].InnerText); } catch (Exception) { } if (privateServer.Name != null || privateServer.Port != null) { lock (_mappedServer.SyncRoot) { if (_mappedServer.Count != 0) { foreach (RemoteServer rm in _mappedServer.Keys) { if (!rm.Name.Equals(privateServer.Name)) { updatedServerMap.Add(privateServer, publicServer); } } } else { _mappedServer.Add(privateServer, publicServer); } } } } } _isAzureRemoteClient = true; } } foreach (RemoteServer rms in updatedServerMap.Keys) { _mappedServer.Add(rms, updatedServerMap[rms]); } } catch (Exception) { } }
private void LoadRemoteServerConfig(XmlNodeList cacheConfig) { try { if (!_loadServersFromConfigFile) return; for (int i = 0; i < cacheConfig.Count; i++) { XmlNode currentConfig = cacheConfig.Item(i); if (currentConfig.Name.Equals("server")) { RemoteServer remoteServer = new RemoteServer(); short serverPriority = 1; try { remoteServer.Name = currentConfig.Attributes["name"].InnerText; if (currentConfig.Attributes.GetNamedItem("port-range") != null) remoteServer.PortRange = Convert.ToInt16(currentConfig.Attributes["port-range"].InnerText); } catch (Exception) { } remoteServer.Port = ServerPort; if ((remoteServer.Name != null || remoteServer.IP != null) && remoteServer.Port != -1) { lock (_servers.SyncRoot) { if (!_servers.Contains(remoteServer)) { if (_mappedServer != null || _mappedServer.Count != 0) { RemoteServer rm = GetMappedServer(remoteServer.Name, remoteServer.Port); rm.Priority = remoteServer.Priority; rm.IsUserProvided = true; if(!_servers.Contains(rm)) _servers.Add(rm); } else { remoteServer.IsUserProvided = true; _servers.Add(remoteServer); } } } } } } lock (_servers.SyncRoot) { _servers.Sort(); } } catch (Exception) { } }
public RemoteServer GetMappedServer(string ip,int port) { RemoteServer mapping=null; if (_mappedServer != null || _mappedServer.Count != 0) { foreach (RemoteServer rm in _mappedServer.Keys) { if (rm.Name.Equals(ip)) { mapping = new RemoteServer(); mapping = (RemoteServer)_mappedServer[rm]; } } } // Incase the map is null the method will return the original IP and Port if (mapping == null) { mapping = new RemoteServer(ip, port); } return mapping; }
/// <summary> /// Initializes the instance of <see cref="Alachisoft.NCache.Web.Caching.CacheServerInfo"/> for this application. /// </summary> internal CacheServerInfo() { ServerInfo = new RemoteServer(); }
private void LoadRemoteServerConfig(XmlNodeList cacheConfig) { try { if (!_loadServersFromConfigFile) { return; } int PriorityCounter = 1; for (int i = 0; i < cacheConfig.Count; i++) { XmlNode currentConfig = cacheConfig.Item(i); if (currentConfig.Name.Equals("server")) { RemoteServer remoteServer = new RemoteServer(); try { remoteServer.Name = currentConfig.Attributes["name"].InnerText; remoteServer.Priority = Convert.ToInt16(PriorityCounter); PriorityCounter = PriorityCounter + 1; if (currentConfig.Attributes.GetNamedItem("port-range") != null) { remoteServer.PortRange = Convert.ToInt16(currentConfig.Attributes["port-range"].InnerText); } } catch (Exception) { } remoteServer.Port = ServerPort; if ((remoteServer.Name != null || remoteServer.IP != null) && remoteServer.Port != -1) { lock (_servers.SyncRoot) { if (!_servers.Contains(remoteServer)) { if (_mappedServer != null && _mappedServer.Count != 0) { RemoteServer rm = GetMappedServer(remoteServer.Name, remoteServer.Port); remoteServer.Name = rm.Name; remoteServer.Port = rm.Port; if (!_servers.Contains(remoteServer)) { _servers.Add(remoteServer); } } else { remoteServer.IsUserProvided = true; _servers.Add(remoteServer); } } } } } } lock (_servers.SyncRoot) { _servers.Sort(); } } catch (Exception) { } }
/// <summary> /// Try to connect with the server. The connection object will be used to connect with the ip /// address on port provided /// </summary> /// <param name="connection">This object will be used to connect with server</param> /// <param name="addr">ip address of server</param> /// <param name="port">port on which socket server is running</param> /// <param name="balanceNodes">balance clients load on servers</param> /// <param name="importHashmap">if hashmap is to be fetched from connecting server</param> /// <param name="registerNotifs">if re registring of events is needed</param> /// <returns>true if connecion is established, false otherwise</returns> private bool ConnectRemoteServer(Connection connection, IPAddress addr, int port, bool balanceNodes, bool importHashmap, bool registerNotifs, ref Exception exception) { bool connected = connection.Connect(addr, port); //remove old entry from message integrator if exist _responseIntegrator.RemoveServer(new Address(addr, port)); if (connected) { try { Dictionary<string, int> runningServers = null; //Populating the server list at initialization time. if (_clientConfig.IPMappingConfigured) { GetServerMapping(connection, true); } if (balanceNodes) { CommandResponse response = IsOptimalServer(connection, addr, port); RemoteServer rm = _clientConfig.GetMappedServer(response.ServerIPAddress.ToString(), response.ServerPort); if (response != null && (addr.ToString() == rm.Name || port == rm.Port)) { connection.Disconnect(); connection.Connect(rm.Name, rm.Port); } } if (_logger.IsDetailedLogsEnabled) _logger.NCacheLog.Info("Broker.ConnectRemoteServer", "[Local : (" + connection.PrimaryClientSocket.LocalEndPoint.ToString() + ") Server : (" + addr.ToString() + ":" + port + ")] connected successfully"); InitializeCache(connection, addr, port, balanceNodes); if (connection.SupportDualSocket) InitializeSecondarySocket(connection, addr, port); runningServers = GetRunningServers(connection, addr, port); connection.Init(); if (runningServers != null) { int outPort; foreach (string str in runningServers.Keys) { RemoteServer rServer = new RemoteServer(); runningServers.TryGetValue(str, out outPort); rServer.IP = System.Net.IPAddress.Parse(str); rServer.Port = outPort; _clientConfig.AddServer(rServer); } } if (_logger.IsDetailedLogsEnabled) _logger.NCacheLog.Info("Broker.ConnectRemoteServer", "[Local : (" + connection.PrimaryClientSocket.LocalEndPoint.ToString() + ") Server : (" + addr.ToString() + ":" + port + ")] initialized cache successfully"); } catch (OperationNotSupportedException ons) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.ConnectRemoteServer", ons.ToString()); connection.Disconnect(); connected = false; throw; } catch (Exception e) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.ConnectRemoteServer", e.ToString()); connection.Disconnect(); connected = false; exception = e; } } else { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.ConnectRemoteServer", "Could not connect to server (" + addr.ToString() + ":" + port + ")"); } if (connected) { if (_processor != null) this._processor.Start(); connection.StatusLatch.SetStatusBit(ConnectionStatus.Connected, ConnectionStatus.Disconnected | ConnectionStatus.Connecting); this._serverIP = connection.ServerAddress; this._port = connection.Port; this._pool.Add(connection.ServerAddress, connection); if (importHashmap) { this.GetHashmap(connection); } if (registerNotifs) { _cache.ReRegisterGeneralNotification(connection); connection.NotifRegistered = true; } if (this._importHashmap) { _cache.RegisterHashmapChangedEvent(connection); } _cache.GetTypeInfoMap(connection); } return connected; }
/// <summary> /// New hashmap recieved. Depending on new and old hashmap, some connections are /// disposed and some new connections are formed(not always as in some cases only buckets have /// transfered between servers). This method should be called asynchronously so the recieve thread /// will be free to recieve other command responces. /// </summary> /// <param name="newHashmap">new hashmap returned from primary server</param> private void NewHashmapRecieved(NewHashmap newHashmap) { if (newHashmap == null) { _logger.NCacheLog.CriticalInfo("Broker.NewHashmapReceived", "Hashmap is null... returning"); return; } lock (_hashmapUpdateMutex) { try { if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Debug("Broker.NewHashmapReceived", "Hashmap " + newHashmap.ToString()); } long oldId = _pool != null ? _pool.LastViewId : -2; if (newHashmap.LastViewId == this._pool.LastViewId) { _logger.NCacheLog.CriticalInfo("Broker.NewHashmapReceived", "Hashmap is same as current pool. Pool " + this._pool.ToString() + " New Hashmap " + newHashmap.ToString() + " ... returning"); return; } if (_clientConfig.IPMappingConfigured) { this.GetServerMapping(null, false); } for (int i = 0; i < newHashmap.Members.Count; i++) { string ip = (string) newHashmap.Members[i]; int serverPort = this._port; if (_clientConfig.IPMappingConfigured) { RemoteServer server = _clientConfig.GetMappedServer(ip, serverPort); ip = server.Name; serverPort = server.Port; newHashmap.Members[i] = ip + ":" + serverPort.ToString(); } Address addr = new Address(ip, serverPort); if (!this._pool.Contains(addr)) { try { IPAddress address = IPAddress.Parse(ip); Connection connection = new Connection(this._commandReieved, this._serverLost, this._logger, _perfStatsColl, _responseIntegrator, _clientConfig.BindIP); Exception exception = null; if (ConnectRemoteServer(connection, address, serverPort, false, false, false, ref exception)) { this._pool.Add(addr, connection); this._clientConfig.AddServer(new RemoteServer(address, serverPort)); if (_logger.IsDetailedLogsEnabled) _logger.NCacheLog.Debug("Broker.NewHashmapRecieved", "Connection made to " + ip + ", and added to pool"); } else { if (exception != null && _logger.IsErrorLogsEnabled) { _logger.NCacheLog.Error("Broker.NewHashmapRecieved", "Could not connect to " + ip + ". " + exception.ToString()); } } } catch (Exception exc) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.NewHashmapRecieved", exc.ToString()); } } else { Connection connection = this._pool[addr]; if (connection != null && !connection.IsConnected) { if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Debug("Broker.NewHashmapRecieved", "Not connected to " + ip + " in the pool"); } try { Exception exception = null; TryConnecting(connection, ref exception); } catch (Exception exc) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.NewHashmapRecieved", exc.ToString()); } } else { if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Debug("Broker.NewHashmapRecieved", "Already connected to " + ip + " in the pool"); } } } } if (this._importHashmap) { //List of Connection ip's which as per new hashmap are no more valid List<Address> invalidIPConnection = new List<Address>(); foreach (Address ipAddress in this._pool.Servers) { if (_clientConfig.IPMappingConfigured) { if ( !newHashmap.Members.Contains(ipAddress.IpAddress.ToString() + ":" + ipAddress.Port.ToString())) { invalidIPConnection.Add(ipAddress); } } else { if (!newHashmap.Members.Contains(ipAddress.IpAddress.ToString())) { invalidIPConnection.Add(ipAddress); } } } foreach (Address ip in invalidIPConnection) { this._pool[ip].Disconnect(); this._pool.Remove(ip); if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Debug("Broker.NewHashmapRecieved", "Disconnected from " + ip + ", and removed from pool"); } } } RemoteServer srvr = new RemoteServer(); string add = null; for (int key = 0; key < newHashmap.Map.Count; key++) { add = (string) newHashmap.Map[key]; srvr = _clientConfig.GetMappedServer(add, this._port); newHashmap.Map[key] = new Address(srvr.Name, srvr.Port); } this._pool.SetHashmap(newHashmap); if (_logger.IsDetailedLogsEnabled) { _logger.NCacheLog.Debug("Broker.NewHashmapReceived", "Hashmap applied " + newHashmap.ToString() + " Pool " + this._pool.ToString()); } } catch (Exception exc) { if (_logger.IsErrorLogsEnabled) _logger.NCacheLog.Error("Broker.NewHashmapRecieved", exc.Message); } } }
private void ProcessResponse(CommandResponse response, Address remoteServerAddress) { CommandBase command = null; Request request = null; lock (_requestTable.SyncRoot) { request = (Request) _requestTable[response.RequestId]; if (request != null) { //The async Add/Insert/Remove complete events need to verify the command type to raise events specific to a commmand try { if (request.Commands.Count > 0) command = (CommandBase) request.Commands[remoteServerAddress]; } catch (Exception ex) { } } } response.CacheId = _cacheId; switch (response.Type) { case Alachisoft.NCache.Common.Protobuf.Response.Type.INIT: case Alachisoft.NCache.Common.Protobuf.Response.Type.ADD: case Alachisoft.NCache.Common.Protobuf.Response.Type.REMOVE: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET: case Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT: case Alachisoft.NCache.Common.Protobuf.Response.Type.CLEAR: case Alachisoft.NCache.Common.Protobuf.Response.Type.COUNT: case Alachisoft.NCache.Common.Protobuf.Response.Type.REGISTER_NOTIF: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_ENUMERATOR: case Alachisoft.NCache.Common.Protobuf.Response.Type.ADD_BULK: case Alachisoft.NCache.Common.Protobuf.Response.Type.INSERT_BULK: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_OPTIMAL_SERVER: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_BULK: case Alachisoft.NCache.Common.Protobuf.Response.Type.REMOVE_BULK: case Alachisoft.NCache.Common.Protobuf.Response.Type.CONTAINS: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_CACHE_ITEM: case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH: case Alachisoft.NCache.Common.Protobuf.Response.Type.SEARCH_ENTRIES: case Alachisoft.NCache.Common.Protobuf.Response.Type.REGISTER_KEY_NOTIF: case Alachisoft.NCache.Common.Protobuf.Response.Type.REGISTER_BULK_KEY_NOTIF: case Alachisoft.NCache.Common.Protobuf.Response.Type.UNREGISTER_KEY_NOTIF: case Alachisoft.NCache.Common.Protobuf.Response.Type.UNREGISTER_BULK_KEY_NOTIF: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_TYPEINFO_MAP: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_HASHMAP: case Alachisoft.NCache.Common.Protobuf.Response.Type.UNLOCK: case Alachisoft.NCache.Common.Protobuf.Response.Type.LOCK: case Alachisoft.NCache.Common.Protobuf.Response.Type.ISLOCKED: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_LOGGING_INFO: case Alachisoft.NCache.Common.Protobuf.Response.Type.DISPOSE: case Alachisoft.NCache.Common.Protobuf.Response.Type.DELETE: case Alachisoft.NCache.Common.Protobuf.Response.Type.DELETE_BULK: case Alachisoft.NCache.Common.Protobuf.Response.Type.EXCEPTION: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_NEXT_CHUNK: case Alachisoft.NCache.Common.Protobuf.Response.Type.ADD_ATTRIBUTE: case Alachisoft.NCache.Common.Protobuf.Response.Type.GET_SERVER_MAPPING: if (request == null) return; lock (request) { request.AddResponse(remoteServerAddress, response); Monitor.PulseAll(request); } if (_logger.IsDetailedLogsEnabled) _logger.NCacheLog.Debug("Broker.ProcessResponse", "RequestID : " + request.RequestId + " " + request.Name + " received response from server " + remoteServerAddress + ". Seq # " + response.SequenceId); break; case Alachisoft.NCache.Common.Protobuf.Response.Type.ITEM_REMOVED_CALLBACK: if (_cache != null && _cache.AsyncEventHandler != null) { _cache.EventListener.OnCustomRemoveCallback(response.CallbackId, response.Key, response.Value, response.Reason, response.FlagValueEntry.Flag, true, null, response.DataFilter); } break; case Alachisoft.NCache.Common.Protobuf.Response.Type.NODE_JOINED_EVENT: ThreadPool.QueueUserWorkItem(new WaitCallback(StartBalancingClients), response); break; case Alachisoft.NCache.Common.Protobuf.Response.Type.HASHMAP_CHANGED_EVENT: ThreadPool.QueueUserWorkItem(new WaitCallback(UpdateHashmapAsync), response.Value); break; case Alachisoft.NCache.Common.Protobuf.Response.Type.NODE_LEFT_EVENT: RemoteServer serverLeft = new RemoteServer(); if (response.ServerPort > 0) { //Get Mapped Server will return the same "IP and port" incase of non-existance of the map RemoteServer rm = _clientConfig.GetMappedServer(response.ServerIPAddress.ToString(), response.ServerPort); serverLeft = rm; _clientConfig.RemoveServer(serverLeft); } break; case Alachisoft.NCache.Common.Protobuf.Response.Type.ITEM_UPDATED_CALLBACK: if (_cache != null && _cache.AsyncEventHandler != null) { _cache.EventListener.OnCustomUpdateCallback(response.CallbackId, response.Key, true, null, null, null, response.DataFilter); } break; case Alachisoft.NCache.Common.Protobuf.Response.Type.BULK_EVENT: if (response.EventList.Count > 0) { ThreadPool.QueueUserWorkItem(_bulkEventCallback, new object[] {remoteServerAddress, response.EventList}); break; } break; } if (request != null) { if (_perfStatsColl2 != null) _perfStatsColl2.DecrementRequestQueueSizeStats(); } }
internal void AddMappedServers(List <NCache.Config.Mapping> mappedServerList) { Hashtable updatedServerMap = new Hashtable(); if (mappedServerList != null) { foreach (NCache.Config.Mapping node in mappedServerList) { RemoteServer publicServer = new RemoteServer(); RemoteServer privateServer = new RemoteServer(); privateServer.Name = node.PrivateIP; privateServer.Port = node.PrivatePort; publicServer.Name = node.PublicIP; publicServer.Port = node.PublicPort; if (privateServer.Name != null || privateServer.Port != null) { lock (_mappedServer.SyncRoot) { if (_mappedServer.Count != 0) { bool keyExists = false; foreach (RemoteServer rm in _mappedServer.Keys) { if (!rm.Name.Equals(privateServer.Name)) { keyExists = false; } else { keyExists = true; RemoteServer originalPublicServer = (RemoteServer)_mappedServer[rm]; String existingServer = originalPublicServer.Name + ":" + originalPublicServer.Port.ToString(); String newServer = publicServer.Name + ":" + publicServer.Port.ToString(); if (!existingServer.Equals(newServer)) { updatedServerMap.Add(privateServer, publicServer); } break; } } if (keyExists == false) { updatedServerMap.Add(privateServer, publicServer); } } else { _mappedServer.Add(privateServer, publicServer); } } } } foreach (RemoteServer rms in updatedServerMap.Keys) { _mappedServer[rms] = updatedServerMap[rms]; } } }
/// <summary> /// Add remote server to list only if it is not present /// </summary> /// <param name="server"></param> public void AddServer(RemoteServer server) { if (_servers != null && (!string.IsNullOrEmpty(server.Name) || server.IP != null)) { lock (_servers.SyncRoot) { if (!_servers.Contains(server)) { _servers.Add(server); } } } }