internal bool AssertConnectedSocket()
        {
            try
            {
                TryConnectIfNeeded();
                var isConnected = socket != null;
                return(isConnected);
            }
            catch (SocketException ex)
            {
                log.Error(ErrorConnect.Fmt(Host, Port));

                if (socket != null)
                {
                    socket.Close();
                }

                socket = null;

                DeactivatedAt = DateTime.UtcNow;
                var message = "" + Host + ":" + Port;
                var throwEx = new RedisException(message, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
		private void Connect()
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
			{
				SendTimeout = SendTimeout,
				ReceiveTimeout = ReceiveTimeout
			};
			try
			{
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

				if (!socket.Connected)
				{
					socket.Close();
					socket = null;
					return;
				}
				Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

				if (Password != null)
					SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

				db = 0;
				var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
				clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
				lastCommand = null;
				lastSocketException = null;
				LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

				if (isPreVersion1_26 == null)
				{
					isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
				}

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
			}
			catch (SocketException ex)
			{
                if (socket != null)
                    socket.Close();
                socket = null;

				HadExceptions = true;
				var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
				log.Error(throwEx.Message, ex);
				throw throwEx;
			}
		}
        private void Connect()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                db = 0;
                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
        private RedisSentinelWorker GetValidSentinelWorker()
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (this.worker != null)
            {
                return(this.worker);
            }

            RedisException lastEx = null;

            while (this.worker == null && ShouldRetry())
            {
                var step = 0;
                try
                {
                    this.worker = GetNextSentinel();
                    step        = 1;
                    GetRedisManager();

                    step = 2;
                    this.worker.BeginListeningForConfigurationChanges();
                    this.failures = 0; //reset
                    return(this.worker);
                }
                catch (RedisException ex)
                {
                    if (Log.IsDebugEnabled)
                    {
                        var name = step switch {
                            0 => "GetNextSentinel()",
                            1 => "GetRedisManager()",
                            2 => "BeginListeningForConfigurationChanges()",
                            _ => $"Step {step}",
                        };
                        Log.Debug($"Failed to {name}: {ex.Message}");
                    }

                    if (OnWorkerError != null)
                    {
                        OnWorkerError(ex);
                    }

                    lastEx      = ex;
                    this.worker = null;
                    this.failures++;
                    Interlocked.Increment(ref RedisState.TotalFailedSentinelWorkers);
                }
            }

            this.failures = 0; //reset
            TaskUtils.Sleep(WaitBetweenFailedHosts);
            throw new RedisException("No Redis Sentinels were available", lastEx);
        }
        private RedisException CreateConnectionError()
        {
            DeactivatedAt = DateTime.UtcNow;
            var throwEx = new RedisException(
                string.Format("Unable to Connect: sPort: {0}",
                              clientPort), lastSocketException);

            log.Error(throwEx.Message);
            throw throwEx;
        }
        private RedisException CreateConnectionError()
        {
            HadExceptions = true;
            var throwEx = new RedisException(
                string.Format("Unable to Connect: sPort: {0}",
                              clientPort), lastSocketException);

            log.Error(throwEx.Message);
            throw throwEx;
        }
Beispiel #7
0
        private void Connect()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout = SendTimeout,
            };
            try
            {
                if (!TryPing(this.Host, this.Port, 200))
                {
                    throw new SocketException();
                }

                socket.Connect(Host, Port);

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                db = 0;
                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                if (isPreVersion1_26 == null)
                {
                    isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
        private RedisException CreateConnectionError(Exception originalEx)
        {
            DeactivatedAt = DateTime.UtcNow;
            var throwEx = new RedisException(string.Format("[{0}] Unable to Connect: sPort: {1}{2}",
                                                           DateTime.UtcNow.ToString("HH:mm:ss.fff"),
                                                           clientPort,
                                                           originalEx != null ? ", Error: " + originalEx.Message + "\n" + originalEx.StackTrace : ""),
                                             originalEx ?? lastSocketException);

            log.Error(throwEx.Message);
            throw throwEx;
        }
		private void Connect()
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
			{
				SendTimeout = SendTimeout
			};
			try
			{
                socket = GetSocketCanConnect();
                if (!socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                    socket = null;
                    return;
                }

				Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

				if (Password != null)
					SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

				db = 0;
				var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
				clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
				lastCommand = null;
				lastSocketException = null;
				LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

				if (isPreVersion1_26 == null)
				{
					isPreVersion1_26 = this.ServerVersion.CompareTo("1.2.6") <= 0;

					//force version reload
					log.DebugFormat("redis-server Version: {0}", isPreVersion1_26);
				}
			}
			catch (SocketException ex)
			{
                if (socket != null)
                    socket.Close();
                socket = null;

				HadExceptions = true;
				var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
				log.Error(throwEx.Message, ex);
				throw throwEx;
			}
		}
        private RedisSentinelWorker GetValidSentinelWorker()
        {
            if (isDisposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (this.worker != null)
            {
                return(this.worker);
            }

            RedisException lastEx = null;

            while (this.worker == null && ShouldRetry())
            {
                try
                {
                    this.worker = GetNextSentinel();
                    GetRedisManager();
                    this.worker.BeginListeningForConfigurationChanges();
                    this.failures = 0; //reset
                    return(this.worker);
                }
                catch (RedisException ex)
                {
                    if (OnWorkerError != null)
                    {
                        OnWorkerError(ex);
                    }

                    lastEx      = ex;
                    this.worker = null;
                    this.failures++;
                    Interlocked.Increment(ref RedisState.TotalFailedSentinelWorkers);
                }
            }

            this.failures = 0; //reset
            Thread.Sleep(WaitBetweenFailedHosts);

            throw new RedisException("No Redis Sentinels were available", lastEx);
        }
        private RedisSentinelWorker GetValidSentinel()
        {
            if (this.worker != null)
            {
                return(this.worker);
            }

            RedisException lastEx = null;

            while (this.RedisManager == null && ShouldRetry())
            {
                try
                {
                    this.worker       = GetNextSentinel();
                    this.RedisManager = worker.GetClientManager();
                    this.worker.BeginListeningForConfigurationChanges();
                    return(this.worker);
                }
                catch (RedisException ex)
                {
                    if (OnWorkerError != null)
                    {
                        OnWorkerError(ex);
                    }

                    lastEx = ex;
                    if (this.worker != null)
                    {
                        this.worker.Dispose();
                    }

                    this.failures++;
                }
            }

            throw new RedisException("RedisSentinel is not accessible", lastEx);
        }
		private RedisException CreateConnectionError()
		{
			HadExceptions = true;
            var throwEx = new RedisException(
				string.Format("Unable to Connect: sPort: {0}",
					clientPort), lastSocketException);
			log.Error(throwEx.Message);
			throw throwEx;
		}
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
                SendTimeout = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

                if (db != 0)
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = int.Parse(ServerVersion.Replace(".", "").PadRight(4, '0'));
                    }
                }
                catch {}
                    
                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand = null;
                lastSocketException = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                    socket.Close();
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    HadExceptions = true;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
                        var ctor = typeof(SslStream).GetConstructors()
                                   .First(x => x.GetParameters().Length == 5);

                        var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
                    }

                    sslStream.AuthenticateAsClient(Host);

                    if (!sslStream.IsEncrypted)
                    {
                        throw new Exception("Could not establish an encrypted connection to " + Host);
                    }

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                if (Client != null)
                {
                    SendExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts   = ServerVersion.Split('.');
                        var version = int.Parse(parts[0]) * 1000;
                        if (parts.Length > 1)
                        {
                            version += int.Parse(parts[1]) * 100;
                        }
                        if (parts.Length > 2)
                        {
                            version += int.Parse(parts[2]);
                        }

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
                SendTimeout = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    HadExceptions = true;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                            leaveInnerStreamOpen: false,
                            userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                            userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
                        var ctor = typeof(SslStream).GetConstructors()
                            .First(x => x.GetParameters().Length == 5);

                        var policyType = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
                    }

                    sslStream.AuthenticateAsClient(Host);

                    if (!sslStream.IsEncrypted)
                        throw new Exception("Could not establish an encrypted connection to " + Host);

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (!string.IsNullOrEmpty(Password))
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

                if (db != 0)
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());

                if (Client != null)
                    SendExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts = ServerVersion.Split('.');
                        var version = int.Parse(parts[0])*1000;
                        if (parts.Length > 1)
                            version += int.Parse(parts[1])*100;
                        if (parts.Length > 2)
                            version += int.Parse(parts[2]);

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }
                    
                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand = null;
                lastSocketException = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                    socket.Close();
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
Beispiel #16
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts   = ServerVersion.Split('.');
                        var version = int.Parse(parts[0]) * 1000;
                        if (parts.Length > 1)
                        {
                            version += int.Parse(parts[1]) * 100;
                        }
                        if (parts.Length > 2)
                        {
                            version += int.Parse(parts[2]);
                        }

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {
                SendTimeout = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());

                if (db != 0)
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        var parts = ServerVersion.Split('.');
                        var version = int.Parse(parts[0])*1000;
                        if (parts.Length > 1)
                            version += int.Parse(parts[1])*100;
                        if (parts.Length > 2)
                            version += int.Parse(parts[2]);

                        ServerVersionNumber = version;
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }
                    
                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand = null;
                lastSocketException = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                    socket.Close();
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
Beispiel #18
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout == 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    HadExceptions = true;
                    return;
                }
                Bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);

                if (Password != null)
                {
                    SendExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = int.Parse(ServerVersion.Replace(".", "").PadRight(4, '0'));
                    }
                }
                catch {}

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException ex)
            {
                if (socket != null)
                {
                    socket.Close();
                }
                socket = null;

                HadExceptions = true;
                var throwEx = new RedisException("could not connect to redis Instance at " + Host + ":" + Port, ex);
                log.Error(throwEx.Message, ex);
                throw throwEx;
            }
        }
 private RedisException CreateConnectionError()
 {
     DeactivatedAt = DateTime.UtcNow;
     var throwEx = new RedisException(
         string.Format("Unable to Connect: sPort: {0}",
             clientPort), lastSocketException);
     log.Error(throwEx.Message);
     throw throwEx;
 }