Exemple #1
0
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     if (this._requestListener != null)
     {
         _requestListener.ChannelDisconnected(this, reason);
     }
 }
Exemple #2
0
 public void Dispose()
 {
     _shardListener      = null;
     _remoteShardChannel = null;
     //_activeChannelsList = null;
     _servers = null;
 }
Exemple #3
0
        public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
        {
            try
            {
                if (channel != null && ((IDualChannel)channel).ShouldTryReconnecting && _primary != null && _primary.Address.Equals(channel.PeerAddress))
                {
                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsInfoEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Info("RemoteShard.ChannelDisconnected.ShoudTryReconnecting", ((IDualChannel)channel).ShouldTryReconnecting.ToString());
                    }

                    lock (_onChannel)
                    {
                        _remoteShardChannel = null;
                    }
                    BrokenConnectionInfo info = new BrokenConnectionInfo();
                    info.BrokenAddress = channel.PeerAddress;
                    info.SessionType   = SessionTypes.Shard;

                    _connectionRestoration.RegisterListener(info, this, context.LocalShardName);
                }
            }
            catch (Exception e)
            {
                if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.ShardLogger.Error("RemoteShard.ChannelDisconnected()", e.ToString());
                }
            }
        }
Exemple #4
0
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsWarnEnabled)
     {
         LoggerManager.Instance.ShardLogger.Warn("LocalChannel.OnChDisconnected", "local channel disconnected.");
     }
 }
Exemple #5
0
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     //if (dbMgtServer != null && channel.PeerAddress != null)
     //{
     //    dbMgtServer.RemoveConfigServerChannel(channel.PeerAddress);
     //}
 }
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     if (dbMgtServer != null && channel.PeerAddress != null)
     {
         dbMgtServer.OnChannelDisconnected(this._sessionId);
         dbMgtServer.RemoveConfigServerChannel(channel.PeerAddress);
     }
 }
 private void OnPrimaryGone(ShardInfo shardInfo)
 {
     if (_primary == null)
     {
         return;
     }
     _primary = null;
     _primaryChannel.Disconnect();
     _primaryChannel = null;
 }
        //Temporary overload added for the RemoteShard
        public IRequestResponseChannel GetValidChannel(IDualChannel newChannel, IRequestResponseChannel existingChannel)
        {
            IDictionary <Server, IDualChannel> existingChannelDic = new Dictionary <Server, IDualChannel>();

            if (existingChannel != null)
            {
                Server server = new Server(existingChannel.PeerAddress, Status.Initializing);
                existingChannelDic.Add(server, existingChannel as IDualChannel);
            }
            return(GetValidChannel(newChannel, existingChannelDic));
        }
Exemple #9
0
        public MessageBroker(AbstractChannelFactory factory)
        {
            _ = factory ?? throw new ArgumentNullException(nameof(factory));

            this.subscribers             = new Dictionary <string, List <ISubscriber> >();
            this.recipients              = new Dictionary <string, IRecipient>();
            this.fireForgetChannel       = factory.CreateFireAndForgetChannel(this);
            this.publishSubscribeChannel = factory.CreatePublishSubscribeChannel(this);
            this.requestResponseChannel  = factory.CreateRequestResponseChannel(this);

            this.logger = (factory as AbstractChannelFactory).Logger;
        }
        public object EndSendMessage(Server destination, IAsyncResult result)
        {
            if (destination == null)
            {
                throw new DistributorException(ErrorCodes.Distributor.DESTINATION_NULL, new string[] { _shardInfo.Name });
            }
            Common.MiscUtil.IsArgumentNull(result);
            IRequestResponseChannel channel = null;

            try
            {
                if (_primaryChannel != null && destination.Address.Equals(_primaryChannel.PeerAddress))
                {
                    channel = _primaryChannel;
                    return(_primaryChannel.EndSendMessage(result));
                }

                //Otherwise send to other channel
                string address = ConvertToKey(destination.Address);
                if (_secondaryChannels.ContainsKey(address))
                {
                    channel = _secondaryChannels[address];
                    return(channel.EndSendMessage(result));
                }
            }
            catch (System.TimeoutException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.TIMEOUT,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            catch (Common.Exceptions.TimeoutException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.TIMEOUT,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            catch (ChannelException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.CHANNEL_NOT_RESPONDING,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            throw new DistributorException(ErrorCodes.Distributor.NO_CHANNEL_EXISTS,
                                           new string[] { destination.Address.ToString(), this.ShardInfo.Name });
        }
 public void ChannelAuthenticated(Server server, bool isAuthenticated)
 {
     if (_primaryChannel != null && _primaryChannel.PeerAddress.ToString().Equals(server.Address.ToString()))
     {
         _primaryChannel.IsAuthenticated = isAuthenticated;
     }
     else
     {
         if (_secondaryChannels.ContainsKey(server.ToString()))
         {
             IRequestResponseChannel channel = _secondaryChannels[server.ToString()];
             channel.IsAuthenticated = isAuthenticated;
         }
     }
 }
 public void RemoveUnauthenticatedChannel(Server server)
 {
     if (_primaryChannel.PeerAddress.ToString().Equals(server.Address.ToString()))
     {
         _primaryChannel.IsAuthenticated = false;
     }
     else
     {
         string key = ConvertToKey(server.Address);
         if (_secondaryChannels.ContainsKey(key))
         {
             IRequestResponseChannel channel = _secondaryChannels[key];
             channel.IsAuthenticated = false;
         }
     }
 }
        private void OnPrimarySelected(ShardInfo shardInfo)
        {
            _primary = shardInfo.Primary.ToServer();

            string key = ConvertToKey(shardInfo.Primary.Address); // IP:Port

            lock (_secondaryChannels)
            {
                if (_secondaryChannels.ContainsKey(key))
                {
                    _primaryChannel = _secondaryChannels[key];
                    _secondaryChannels.Remove(key);
                    return;
                }
            }
            _primaryChannel = CreateConnection(shardInfo.Primary.Address.IpAddress.ToString(),
                                               shardInfo.Primary.Address.Port);
        }
        public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
        {
            var  retries     = 3;
            bool isConnected = false;

            if (channel != null)
            {
                while (0 < retries--)
                {
                    try
                    {
                        if (channel.RetryConnect())
                        {
                            isConnected = true;
                            break;
                        }
                    }
                    catch
                    {
                        if (retries == 2)
                        {
                            Thread.Sleep(30000);
                        }
                        else if (retries == 1)
                        {
                            Thread.Sleep(60000);
                        }
                    }
                }
                if (_primaryChannel == null || channel == null)
                {
                    return;
                }

                if (isConnected)
                {
                    if (_channelDisconnectionListener != null)
                    {
                        Server server = new Server(channel.PeerAddress, Status.Running);
                        _channelDisconnectionListener.OnChannelDisconnected(this, server);
                    }
                }
            }
        }
Exemple #15
0
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     if (_disposed)
     {
         return;
     }
     lock (this)
     {
         _session = null;
         //Try to re-connect immediately.
         if (ConnectToPeerServer(false))
         {
             return;
         }
         //In case we are unable to reconnect
         DetermineRole();
         ConnectInBackground();
     }
 }
Exemple #16
0
        public void OnConnectionRestoration(IDualChannel channel)
        {
            // check if the shardConnected event is required to be raised
            bool shardConnected = false;

            if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsDebugEnabled)
            {
                LoggerManager.Instance.ShardLogger.Debug("RemoteShard.OnConnectionRestoration()", "Before Connection Restoration for " + channel != null ? channel.PeerAddress.ToString() : "channel is null");
                LoggerManager.Instance.ShardLogger.Debug("RemoteShard.OnConnectionRestoration()", "Before Connection Restoration Should Retry " + channel != null ? channel.ShouldTryReconnecting.ToString() : "channel is null");
                LoggerManager.Instance.ShardLogger.Debug("RemoteShard.OnConnectionRestoration()", "Before Connection Restoration primary is  " + _remoteShardChannel != null ? _remoteShardChannel.PeerAddress.ToString() : "priamry is null");
            }

            SessionInfo info = new SessionInfo();

            info.Cluster = this.Context.ClusterName;
            info.Shard   = this.Context.LocalShardName;
            ((IRequestResponseChannel)channel).SendMessage(info, true);

            lock (_onChannel)
            {
                _remoteShardChannel = _resolveDispute.GetValidChannel(_resolveDispute.SetConnectInfo(channel, ConnectInfo.ConnectStatus.RECONNECTING), _remoteShardChannel);
                ((IDualChannel)_remoteShardChannel).StartReceiverThread();
                ((IDualChannel)_remoteShardChannel).RegisterRequestHandler(this);
                shardConnected = true;
            }
            lock (_onPrimary)
            {
                _primary = new Server(channel.PeerAddress, Status.Running);
            }

            if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsDebugEnabled)
            {
                LoggerManager.Instance.ShardLogger.Debug("RemoteShard.OnConnectionRestoration()", "After Connection Restoration for " + channel != null ? channel.PeerAddress.ToString() : "channel is null");
                LoggerManager.Instance.ShardLogger.Debug("RemoteShard.OnConnectionRestoration()", "After Connection Restoration Should Retry " + channel != null ? channel.ShouldTryReconnecting.ToString() : "channel is null");
            }

            if (shardConnected)
            {
                ShardConnected();
            }
        }
        public bool Start()
        {
            if (_shardInfo == null)
            {
                return(false);
            }

            // _bindingIp = GetLocalAddress().ToString();

            if (_shardInfo.Primary != null)
            {
                _primaryChannel = CreateConnection(_shardInfo.Primary.Address.IpAddress.ToString(),
                                                   _shardInfo.Primary.Address.Port);

                //_primaryChannel.IsAuthenticated = Authenticate(_shardInfo.Primary.Address.IpAddress.ToString(), _shardInfo.Primary.Address.Port);
            }
            else
            {
                // TODO: Write exception to log
                //throw new Exception("At Query Distributor: No primary exists for " + shardInfo.Name. Shard would start in read only mode);
            }
            if (_shardInfo.RunningNodes != null)
            {
                foreach (ServerInfo serverInfo in _shardInfo.RunningNodes.Values)
                {
                    if (ShardInfo.Primary != null && serverInfo.Equals(ShardInfo.Primary))
                    {
                        continue;
                    }
                    IRequestResponseChannel channel = CreateConnection(serverInfo.Address.IpAddress.ToString(),
                                                                       serverInfo.Address.Port);

                    //channel.IsAuthenticated = Authenticate(serverInfo.Address.IpAddress.ToString(), serverInfo.Address.Port);
                    lock (_secondaryChannels)
                    {
                        _secondaryChannels[ConvertToKey(serverInfo.Address)] = channel;
                    }
                }
            }
            return(true);
        }
        public bool OnSessionEstablished(Session session)
        {
            if (_primaryChannel != null)
            {
                session.Connection.Disconnect();
                return(false);
            }
            IPAddress localIp = GetLocalAddress();

            _primaryChannel = _factory.GetChannel(session.Connection, session.IP.ToString(), session.RemotePort,
                                                  localIp.ToString(), _sessionType, _traceProvider, _channelFormatter);

            if (!_primaryChannel.Connect(true))
            {
                throw new DistributorException(ErrorCodes.Distributor.CHANNEL_CONNECT_FAILED, new string[]
                {
                    _name,
                    _primaryChannel.PeerAddress.IpAddress.ToString(), _primaryChannel.PeerAddress.Port.ToString()
                });
            }

            return(true);
        }
        private IRequestResponseChannel CreateConnection(string peerIP, int peerPort)
        {
            IRequestResponseChannel channel = _factory.GetChannel(peerIP, peerPort, null, _sessionType, _traceProvider,
                                                                  _channelFormatter);
            int retries = 3;

            while (retries > 0)
            {
                if (!channel.Connect(true))
                {
                    retries--;
                    if (retries == 0)
                    {
                        throw new DistributorException(ErrorCodes.Distributor.CHANNEL_CONNECT_FAILED,
                                                       new string[] { _name, peerIP, peerPort.ToString() });
                    }
                }
                break;
            }
            channel.IsAuthenticated = true; //set to false after authentication command failure
            channel.RegisterRequestHandler(this);
            return(channel);
        }
Exemple #20
0
        public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
        {
            if (_channelDisconnctedListener != null)
            {
                _channelDisconnctedListener.ChannelDisconnected(channel, reason);
            }

            if (!_autoReconnect)
            {
                return;
            }

            int  retries   = 3;
            bool connected = false;

            if (channel != null)
            {
                while (0 < retries--)
                {
                    try
                    {
                        lock (_mutex)
                        {
                            if (_channel.RetryConnect())
                            {
                                IServerAuthenticationCredential serverAuthCred = _session.Authenticate(credentials);
                                if (serverAuthCred != null && serverAuthCred.IsAuthenticated)
                                {
                                    _session.Channel.IsAuthenticated = serverAuthCred.IsAuthenticated;
                                    _session.SessionId = serverAuthCred.SessionId;
                                }
                                connected = true;

                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (retries == 2)
                        {
                            Thread.Sleep(30000);
                        }
                        else if (retries == 1)
                        {
                            Thread.Sleep(60000);
                        }
                    }
                }

                if (!connected)
                {
                    retries = 3;
                    TraceProvider traceProvider = EnableTracing ? new TraceProvider() : null;
                    if (_secondConfiguratioServer != null)
                    {
                        string disconnectedServer = channel.PeerAddress.ip;
                        string failOverServer     = null;

                        if (string.Compare(disconnectedServer, _firstConfiguratioServer, true) == 0)
                        {
                            failOverServer = _secondConfiguratioServer;
                        }
                        else
                        {
                            failOverServer = _firstConfiguratioServer;
                        }

                        _channel = new DualChannel(failOverServer, _port, null, SessionTypes.Management, traceProvider,
                                                   _channelFormatter);

                        while (0 < retries--)
                        {
                            try
                            {
                                if (_channel.Connect(true))
                                {
                                    _session.Channel = _channel;
                                    //
                                    //Connection re-established and needs to be authenticated
                                    IServerAuthenticationCredential serverAuthCred = _session.Authenticate(credentials);
                                    if (serverAuthCred != null && serverAuthCred.IsAuthenticated)
                                    {
                                        _session.Channel.IsAuthenticated = serverAuthCred.IsAuthenticated;
                                        _session.SessionId = serverAuthCred.SessionId;
                                    }
                                    break;
                                }
                            }
                            catch (ChannelException ex)
                            {
                                if (LoggerManager.Instance.CONDBLogger != null && LoggerManager.Instance.CONDBLogger.IsErrorEnabled)
                                {
                                    LoggerManager.Instance.CONDBLogger.Error("Error: OutProcConfigClient.ChannelDisconnected()", ex.ToString());
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #21
0
        public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
        {
            try
            {
                if (_shardChannels != null)
                {
                    bool connected = false;

                    if (channel != null)
                    {
                        Server server = new Server(channel.PeerAddress, Status.Stopped);
                        Server key    = null;
                        if (_shardChannels != null)
                        {
                            IList <Server> shardchannelKeys = _shardChannels.Keys.ToList();
                            if (server != null && server.Address != null && !server.Address.Equals(context.LocalAddress) && shardchannelKeys != null && shardchannelKeys.Count > 0)
                            {
                                foreach (Server node in shardchannelKeys)
                                {
                                    if (_shardChannels[node].PeerAddress != null && _shardChannels[node].PeerAddress.Equals(channel.PeerAddress))
                                    {
                                        key = node;
                                        break;
                                    }
                                }
                            }
                            IDualChannel tempChannel = channel as IDualChannel;
                            if (tempChannel != null && key != null && tempChannel.ShouldTryReconnecting)
                            {
                                lock (_shardChannels)
                                {
                                    //_shardChannels[key].Disconnect();
                                    _shardChannels.Remove(key);
                                    if (LoggerManager.Instance.ShardLogger != null &&
                                        LoggerManager.Instance.ShardLogger.IsDebugEnabled)
                                    {
                                        LoggerManager.Instance.ShardLogger.Debug("Localshard.Channeldisconnected(): ",
                                                                                 server.Address.ToString() + " removed from existing channels.");
                                    }
                                }
                                if (!key.Address.Equals(context.LocalAddress))
                                {
                                    BrokenConnectionInfo info = new BrokenConnectionInfo();
                                    info.BrokenAddress = key.Address;
                                    info.SessionType   = SessionTypes.Shard;

                                    _connectionRestoration.RegisterListener(info, this, context.LocalShardName);
                                }
                            }
                        }


                        try
                        {
                            if (!connected)
                            {
                                IShardListener listener = _shardListeners[Common.MiscUtil.CONFIGURATION_MANAGER];
                                listener.OnMemberLeft(new Server(channel.PeerAddress, Status.Stopped));
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #22
0
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     //if (configServer != null && channel.PeerAddress != null)
     //    configServer.RemoveClientChannel(channel.PeerAddress);
 }
 public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
 {
     throw new NotImplementedException("Shard Configuration");
 }
Exemple #24
0
        private void ConnectPrimary(Address primary)
        {
            // check if the shardConnected event is required to be raised
            bool shardConnected = false;

            // If primary is null, it means the respective shard has no primary anymore so
            if (primary == null)
            {
                if (_remoteShardChannel != null)
                {
                    ((DualChannel)_remoteShardChannel).ShouldTryReconnecting = false;
                    _remoteShardChannel.Disconnect();
                    _remoteShardChannel = null;
                }
            }
            else
            {
                if (_remoteShardChannel != null)
                {
                    if (_remoteShardChannel.PeerAddress.Equals(primary) && ((IDualChannel)this._remoteShardChannel).Connected)
                    {
                        return;
                    }
                }


                bool isConnected = false;
                IRequestResponseChannel channel = factory.GetChannel(primary.IpAddress.ToString(), _shardPort, context.LocalAddress.IpAddress.ToString(), SessionTypes.Shard, _traceProvider, _channelFormatter);
                try
                {
                    isConnected = channel.Connect(false);
                }
                catch (ChannelException e)
                {
                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnPrimaryChanged()", e.ToString());
                    }
                }
                //catch (Exception ex)
                //{
                //    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                //        LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnPrimaryChanged()", e.ToString());
                //}

                if (isConnected)
                {
                    SessionInfo info = new SessionInfo();
                    info.Cluster = this.Context.ClusterName;
                    info.Shard   = this.Context.LocalShardName;

                    channel.SendMessage(info, true);

                    lock (_onChannel)
                    {
                        _remoteShardChannel = _resolveDispute.GetValidChannel(_resolveDispute.SetConnectInfo(channel as IDualChannel, ConnectInfo.ConnectStatus.CONNECT_FIRST_TIME), _remoteShardChannel);
                        ((IDualChannel)_remoteShardChannel).StartReceiverThread();
                        ((IDualChannel)_remoteShardChannel).RegisterRequestHandler(this);
                        shardConnected = true;
                    }
                    lock (_onPrimary)
                    {
                        _primary = new Server(new Address(primary.IpAddress.ToString(), primary.Port), Status.Running);
                    }
                }
            }

            if (shardConnected)
            {
                ShardConnected();
            }
        }
Exemple #25
0
        public bool OnSessionEstablished(Session session)
        {
            // check if the shardConnected event is required to be raised
            bool   shardConnected           = false;
            Server server                   = new Server(new Common.Net.Address(session.IP.ToString(), this._shardPort), Status.Initializing);
            IRequestResponseChannel channel = factory.GetChannel(session.Connection, session.IP.ToString(), this._shardPort, context.LocalAddress.ToString(), SessionTypes.Shard, _traceProvider, _channelFormatter);

            LoggerManager.Instance.SetThreadContext(new LoggerContext()
            {
                ShardName = _name != null ? _name : "", DatabaseName = ""
            });
            try
            {
                if (_remoteShardChannel != null && !((IDualChannel)_remoteShardChannel).Connected && _remoteShardChannel.PeerAddress.Equals(server))
                {
                    session.Connection.Disconnect();
                    //throw new ChannelException("already connected with shard"+_name);
                }

                if (channel.Connect(false))
                {
                    ConnectInfo.ConnectStatus status = ConnectInfo.ConnectStatus.CONNECT_FIRST_TIME;
                    if (_remoteShardChannel != null && _remoteShardChannel.PeerAddress.Equals(server.Address))
                    {
                        status = ConnectInfo.ConnectStatus.RECONNECTING;
                    }

                    lock (_onChannel)
                    {
                        _remoteShardChannel = _resolveDispute.GetValidChannel(_resolveDispute.SetConnectInfo(channel as IDualChannel, status), _remoteShardChannel);
                        ((IDualChannel)_remoteShardChannel).StartReceiverThread();
                        ((IDualChannel)_remoteShardChannel).RegisterRequestHandler(this);

                        shardConnected = true;
                    }
                    if (_primary != null && !_primary.Address.Equals(server.Address))
                    {
                        BrokenConnectionInfo info = new BrokenConnectionInfo();
                        info.BrokenAddress = _primary.Address;
                        info.SessionType   = SessionTypes.Shard;
                        _connectionRestoration.UnregisterListener(info);
                    }
                    lock (_onPrimary)
                    {
                        _primary = server;
                    }

                    if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsInfoEnabled)
                    {
                        LoggerManager.Instance.ShardLogger.Info("RemoteShard.OnSessionEstd()", "Session of the shard " + _name + " estd successfully");
                    }
                    return(IsStarted = true);
                }
                else
                {
                    return(false);
                }
            }
            catch (ChannelException e)
            {
                if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.ShardLogger.Error("Error: RemoteShard.OnSessionEstd()", e.ToString());
                }
                return(false);
            }
            finally
            {
                if (shardConnected)
                {
                    ShardConnected();
                }
            }
        }
        public IAsyncResult BeginSendMessage(Server destination, object msg)
        {
            if (destination == null)
            {
                throw new DistributorException(ErrorCodes.Distributor.DESTINATION_NULL, new string[] { _shardInfo.Name });
            }
            IRequestResponseChannel channel = null;

            try
            {
                if (_primaryChannel != null && destination.Address.Equals(_primaryChannel.PeerAddress))
                {
                    if (_primaryChannel.IsAuthenticated)
                    {
                        channel = _primaryChannel;
                        var asyncResult = (RequestManager.AsyncResult)_primaryChannel.BeginSendMessage(msg);
                        asyncResult.ChannelAddress = channel.PeerAddress;
                        return(asyncResult);
                    }
                    else
                    {
                        throw new SecurityException(ErrorCodes.Security.UNAUTHENTIC_DB_SERVER_CONNECTION,
                                                    new string[] { this.Name, _primaryChannel.PeerAddress.IpAddress.ToString() });
                    }
                }

                //Otherwise send to other channel
                string address = ConvertToKey(destination.Address);
                if (_secondaryChannels.ContainsKey(address))
                {
                    channel = _secondaryChannels[address];
                    if (channel.IsAuthenticated)
                    {
                        var asyncResult = (RequestManager.AsyncResult)channel.BeginSendMessage(msg);
                        asyncResult.ChannelAddress = channel.PeerAddress;
                        return(asyncResult);
                    }
                    else
                    {
                        throw new SecurityException(ErrorCodes.Security.UNAUTHENTIC_DB_SERVER_CONNECTION,
                                                    new string[] { this.Name, _primaryChannel.PeerAddress.IpAddress.ToString() });
                    }
                }
            }
            catch (System.TimeoutException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.TIMEOUT,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            catch (Common.Exceptions.TimeoutException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.TIMEOUT,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            catch (ChannelException)
            {
                if (channel != null)
                {
                    throw new DistributorException(ErrorCodes.Distributor.CHANNEL_NOT_RESPONDING,
                                                   new string[] { channel.PeerAddress.ToString() });
                }
            }
            throw new DistributorException(ErrorCodes.Distributor.NO_CHANNEL_EXISTS,
                                           new string[] { destination.Address.ToString(), this.ShardInfo.Name });
        }
        public IList <Server> UpdateConnections(ShardInfo shardInfo)
        {
            IList <Server> serversAdded = new List <Server>();

            if (shardInfo.Primary == null)
            {
                OnPrimaryGone(shardInfo);
            }
            else if (_primary == null)
            {
                OnPrimarySelected(shardInfo);
                serversAdded.Add(Primary);
            }
            else
            {
                Server shardInfoPrimary = shardInfo.Primary.ToServer();
                if (!this._primary.Equals(shardInfoPrimary))
                {
                    lock (_secondaryChannels)
                    {
                        _secondaryChannels[ConvertToKey(_primary.Address)] = _primaryChannel;
                    }
                    OnPrimarySelected(shardInfo);
                    serversAdded.Add(Primary);
                }
            }

            foreach (var secondary in shardInfo.Secondaries)
            {
                string key = ConvertToKey(secondary.Address); //IP:port
                lock (_secondaryChannels)
                {
                    if (!_secondaryChannels.ContainsKey(key))
                    {
                        IRequestResponseChannel channel = CreateConnection(secondary.Address.IpAddress.ToString(),
                                                                           secondary.Address.Port);
                        //channel.IsAuthenticated = Authenticate(_shardInfo.Primary.Address.IpAddress.ToString(), _shardInfo.Primary.Address.Port);
                        _secondaryChannels.Add(key, channel);
                        serversAdded.Add(new Server(secondary.Address, Status.Running));
                    }
                }
            }

            var secondariesRemoved =
                from existingSecondary in _secondaryChannels.Keys
                where
                !shardInfo.Secondaries.Any(
                    newSecondary => ConvertToKey(newSecondary.Address).Equals(existingSecondary))
                select existingSecondary;

            foreach (var removedChannel in secondariesRemoved)
            {
                lock (_secondaryChannels)
                {
                    _secondaryChannels[removedChannel].Disconnect();
                    _secondaryChannels.Remove(removedChannel);
                }
            }
            _shardInfo = shardInfo;
            return(serversAdded);
        }
Exemple #28
0
 public ChannelDisconnectEventTask(IRequestResponseChannel channel, string reason, IRequestListener requestLisetner)
 {
     this.reason      = reason;
     _requestListener = requestLisetner;
     this.channel     = channel;
 }
Exemple #29
0
        public void ChannelDisconnected(IRequestResponseChannel channel, string reason)
        {
            if (channel == null)
            {
                return;
            }
            try
            {
                foreach (ReaderInfo readerInfo in _readersList)
                {
                    var operation = new DisposeReaderOperation
                    {
                        Database      = readerInfo.DatabaseName,
                        Collection    = readerInfo.CollectionName,
                        ReaderUID     = readerInfo.ReaderId,
                        OperationType = DatabaseOperationType.DisposeReader,
                        SessionId     = CsSessionId
                    };
                    try
                    {
                        _dbEngine.DiposeReader(operation);
                    }
                    catch (SecurityException exc)
                    {
                        if (LoggerManager.Instance.SecurityLogger != null &&
                            LoggerManager.Instance.SecurityLogger.IsErrorEnabled)
                        {
                            LoggerManager.Instance.SecurityLogger.Error("ClientSession.ChannelDisconected() ", exc);
                        }
                    }
                }
                _readersList.Clear();

                _conmmandInfos.Clear();

                _clientDisconnection.DisconnectClient(MiscUtil.GetAddressInfo(channel.PeerAddress.IpAddress,
                                                                              channel.PeerAddress.Port));
                _databaseEngineFactory.Dispose(_noSConnectionString);
                try
                {
                    channel.Disconnect();
                }
                catch (ThreadAbortException e)
                {
                    //Todo: maybe log in future or something.
                }

                // Log Client Disconnected.
                if (LoggerManager.Instance.ServerLogger.IsInfoEnabled)
                {
                    LoggerManager.Instance.ServerLogger.Info("ClientSession.ChannelDisconnected",
                                                             "Client [" + MiscUtil.GetAddressInfo(channel.PeerAddress.IpAddress,
                                                                                                  channel.PeerAddress.Port) + "] with sessionId'" + CsSessionId.SessionId + "' disconnected.");
                }

                LoggerManager.Instance.SetThreadContext(new LoggerContext()
                {
                    ShardName = "", DatabaseName = ""
                });
            }
            catch (Exception e)
            {
                try
                {
                    //Remove client session from session manager.
                    _clientDisconnection.DisconnectClient(MiscUtil.GetAddressInfo(channel.PeerAddress.IpAddress, channel.PeerAddress.Port));
                }
                catch (Exception ex) { }

                if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled)
                {
                    LoggerManager.Instance.ShardLogger.Error("ClientSessionDisconnect",
                                                             e.Message + " StackTrace: " + e.StackTrace);
                }
            }
        }