public ClientConnectionManager(HazelcastClient client)
        {
            _client = client;

            var config = client.GetClientConfig();

            _networkConfig = config.GetNetworkConfig();

            config.GetNetworkConfig().IsRedoOperation();
            _credentials = config.GetCredentials();

            //init socketInterceptor
            var sic = config.GetNetworkConfig().GetSocketInterceptorConfig();

            if (sic != null && sic.IsEnabled())
            {
                //TODO Socket interceptor
                throw new NotImplementedException("Socket Interceptor not yet implemented.");
            }
            _socketInterceptor = null;

            const int defaultHeartbeatInterval = 5000;
            const int defaultHeartbeatTimeout  = 60000;

            var heartbeatTimeoutMillis =
                EnvironmentUtil.ReadInt("hazelcast.client.heartbeat.timeout") ?? defaultHeartbeatInterval;
            var heartbeatIntervalMillis =
                EnvironmentUtil.ReadInt("hazelcast.client.heartbeat.interval") ?? defaultHeartbeatTimeout;

            _heartbeatTimeout  = TimeSpan.FromMilliseconds(heartbeatTimeoutMillis);
            _heartbeatInterval = TimeSpan.FromMilliseconds(heartbeatIntervalMillis);
        }
Пример #2
0
        public ClientConnectionManager(HazelcastClient client)
        {
            _client = client;

            var config = client.GetClientConfig();

            _networkConfig = config.GetNetworkConfig();

            config.GetNetworkConfig().IsRedoOperation();
            _credentials = config.GetCredentials();

            //init socketInterceptor
            var sic = config.GetNetworkConfig().GetSocketInterceptorConfig();

            if (sic != null && sic.IsEnabled())
            {
                //TODO Socket interceptor
                throw new NotImplementedException("Socket Interceptor not yet implemented.");
            }
            _socketInterceptor = null;

            var timeout = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.invocation.timeout.seconds");

            if (timeout > 0)
            {
                ThreadUtil.TaskOperationTimeOutMilliseconds = timeout.Value * 1000;
            }

            _heartbeatTimeout = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.heartbeat.timeout") ??
                                _heartbeatTimeout;
            _heartbeatInterval = EnvironmentUtil.ReadEnvironmentVar("hazelcast.client.heartbeat.interval") ??
                                 _heartbeatInterval;
        }
Пример #3
0
        public ConnectionManager(HazelcastClient client)
        {
            _client       = client;
            _loadBalancer = client.LoadBalancer;
            //
            var config = client.ClientConfig;

            _networkConfig        = config.GetNetworkConfig();
            IsSmartRoutingEnabled = _networkConfig.IsSmartRouting();
            _labels = client.ClientConfig.Labels;

            var connectionTimeout = _networkConfig.GetConnectionTimeout();

            _connectionTimeout = connectionTimeout == 0 ? int.MaxValue : connectionTimeout;

            //TODO outboundPorts
            // this.networking = initNetworking();
            // this.outboundPorts.addAll(getOutboundPorts());
            // this.outboundPortCount = outboundPorts.size();

            _heartbeat = new HeartbeatManager(client, this);

            _authenticationTimeout = _heartbeat.HeartbeatTimeout;
            _shuffleMemberList     = EnvironmentUtil.ReadBool("hazelcast.client.shuffle.member.list") ?? false;
            _waitStrategy          = InitializeWaitStrategy(client.ClientConfig);

            var connectionStrategyConfig = client.ClientConfig.GetConnectionStrategyConfig();

            _asyncStart    = connectionStrategyConfig.AsyncStart;
            _reconnectMode = connectionStrategyConfig.ReconnectMode;
        }
Пример #4
0
        //[Test]
        public virtual void TestConfig()
        {
            var config        = new ClientConfig();
            var networkConfig = new ClientNetworkConfig();

            networkConfig.SetAddresses(new[] { "127.0.0.1:5701" });
            config.SetNetworkConfig(networkConfig);
            config.SetGroupConfig(new GroupConfig("mike-local", "password"));
            var _client = HazelcastClient.NewHazelcastClient(config);


            Assert.NotNull(_client);

            _client.Shutdown();
        }
        /// <exception cref="System.IO.IOException"></exception>
        public ClientConnection(ClientConnectionManager clientConnectionManager,
                                ClientInvocationService invocationService,
                                int id,
                                Address address,
                                ClientNetworkConfig clientNetworkConfig)
        {
            _clientConnectionManager = clientConnectionManager;
            _id = id;

            var isa           = address.GetInetSocketAddress();
            var socketOptions = clientNetworkConfig.GetSocketOptions();
            var socketFactory = socketOptions.GetSocketFactory() ?? new DefaultSocketFactory();

            _clientSocket = socketFactory.CreateSocket();

            try
            {
                _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                var lingerOption = new LingerOption(true, 5);
                if (socketOptions.GetLingerSeconds() > 0)
                {
                    lingerOption.LingerTime = socketOptions.GetLingerSeconds();
                }
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                _clientSocket.NoDelay = socketOptions.IsTcpNoDelay();

                _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1;

                var bufferSize = socketOptions.GetBufferSize() * 1024;
                if (bufferSize < 0)
                {
                    bufferSize = BufferSize;
                }

                _clientSocket.SendBufferSize    = bufferSize;
                _clientSocket.ReceiveBufferSize = bufferSize;

                var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1
                    ? clientNetworkConfig.GetConnectionTimeout()
                    : ConnectionTimeout;
                var socketResult = _clientSocket.BeginConnect(address.GetHost(), address.GetPort(), null, null);

                if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected)
                {
                    // NOTE, MUST CLOSE THE SOCKET
                    _clientSocket.Close();
                    throw new IOException("Failed to connect to " + address);
                }
                _sendBuffer    = ByteBuffer.Allocate(BufferSize);
                _receiveBuffer = ByteBuffer.Allocate(BufferSize);

                _builder = new ClientMessageBuilder(invocationService.HandleClientMessage);

                var networkStream = new NetworkStream(_clientSocket, false);
                if (clientNetworkConfig.GetSSLConfig().IsEnabled())
                {
                    var sslStream = new SslStream(networkStream, false,
                                                  (sender, certificate, chain, sslPolicyErrors) =>
                                                  RemoteCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors,
                                                                                      clientNetworkConfig), null);
                    var certificateName = clientNetworkConfig.GetSSLConfig().GetCertificateName() ?? "";
                    sslStream.AuthenticateAsClient(certificateName);
                    _stream = sslStream;
                }
                else
                {
                    _stream = networkStream;
                }
                _live = new AtomicBoolean(true);
            }
            catch (Exception e)
            {
                _clientSocket.Close();
                if (_stream != null)
                {
                    _stream.Close();
                }
                throw new IOException("Cannot connect! Socket error:" + e.Message);
            }
        }
        private bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors, ClientNetworkConfig clientNetworkConfig)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            var validation = true;

            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
            {
                var isValidateChain = clientNetworkConfig.GetSSLConfig().IsValidateCertificateChain();
                if (isValidateChain)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("SSL Configured to ignore Certificate chain validation. Ignoring:");
                }
                foreach (var status in chain.ChainStatus)
                {
                    Logger.Info("Certificate chain status:" + status.StatusInformation);
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
            {
                var isValidateName = clientNetworkConfig.GetSSLConfig().IsValidateCertificateName();
                if (isValidateName)
                {
                    Logger.Warning("Certificate error:" + sslPolicyErrors);
                    validation = false;
                }
                else
                {
                    Logger.Info("Certificate name mismatched but client is configured to ignore Certificate name validation.");
                }
            }
            if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            {
                Logger.Warning("Certificate error:" + sslPolicyErrors);
                validation = false;
            }
            return(validation);
        }
Пример #7
0
        /// <exception cref="System.IO.IOException"></exception>
        public ClientConnection(ClientConnectionManager clientConnectionManager,
                                ClientInvocationService invocationService,
                                int id,
                                Address address,
                                ClientNetworkConfig clientNetworkConfig)
        {
            _clientConnectionManager = clientConnectionManager;
            _id = id;

            var isa           = address.GetInetSocketAddress();
            var socketOptions = clientNetworkConfig.GetSocketOptions();
            var socketFactory = socketOptions.GetSocketFactory();

            if (socketFactory == null)
            {
                socketFactory = new DefaultSocketFactory();
            }
            _clientSocket = socketFactory.CreateSocket();
            try
            {
                _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                var lingerOption = new LingerOption(true, 5);
                if (socketOptions.GetLingerSeconds() > 0)
                {
                    lingerOption.LingerTime = socketOptions.GetLingerSeconds();
                }
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                _clientSocket.NoDelay = socketOptions.IsTcpNoDelay();

                _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1;

                var bufferSize = socketOptions.GetBufferSize() * 1024;
                if (bufferSize < 0)
                {
                    bufferSize = BufferSize;
                }

                _clientSocket.SendBufferSize    = bufferSize;
                _clientSocket.ReceiveBufferSize = bufferSize;

                _clientSocket.UseOnlyOverlappedIO = true;

                var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1
                    ? clientNetworkConfig.GetConnectionTimeout()
                    : ConnectionTimeout;
                var socketResult = _clientSocket.BeginConnect(address.GetHost(), address.GetPort(), null, null);

                if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected)
                {
                    // NOTE, MUST CLOSE THE SOCKET
                    _clientSocket.Close();
                    throw new IOException("Failed to connect to " + address);
                }
                _sendBuffer    = ByteBuffer.Allocate(BufferSize);
                _receiveBuffer = ByteBuffer.Allocate(BufferSize);

                _builder = new ClientMessageBuilder(invocationService.HandleClientMessage);

                _live = true;
            }
            catch (Exception e)
            {
                _clientSocket.Close();
                throw new IOException("Cannot connect! Socket error:" + e.Message);
            }
        }
Пример #8
0
        public Connection(ConnectionManager connectionManager, InvocationService invocationService, int id, Address address,
                          ClientNetworkConfig clientNetworkConfig)
        {
            _connectionManager = connectionManager;
            _id = id;

            var isa           = address.GetInetSocketAddress();
            var socketOptions = clientNetworkConfig.GetSocketOptions();

            try
            {
                _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                if (socketOptions.GetLingerSeconds() > 0)
                {
                    var lingerOption = new LingerOption(true, socketOptions.GetLingerSeconds());
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                }
                else
                {
                    var lingerOption = new LingerOption(true, 0);
                    _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, lingerOption);
                }
                _clientSocket.NoDelay        = socketOptions.IsTcpNoDelay();
                _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1;

                var bufferSize = socketOptions.GetBufferSize() * 1024;
                if (bufferSize < 0)
                {
                    bufferSize = BufferSize;
                }

                _clientSocket.SendBufferSize    = bufferSize;
                _clientSocket.ReceiveBufferSize = bufferSize;

                var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1
                    ? clientNetworkConfig.GetConnectionTimeout()
                    : ConnectionTimeout;
                var socketResult = _clientSocket.BeginConnect(address.GetInetAddress(), address.Port, null, null);

                if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected)
                {
                    // NOTE, MUST CLOSE THE SOCKET
                    _clientSocket.Close();
                    throw new IOException("Failed to connect to " + address);
                }
                _sendBuffer    = ByteBuffer.Allocate(BufferSize);
                _receiveBuffer = ByteBuffer.Allocate(BufferSize);

                _decoder = new ClientMessageDecoder(invocationService.HandleClientMessage);

                var networkStream = new NetworkStream(_clientSocket, false);
                var sslConfig     = clientNetworkConfig.GetSSLConfig();
                if (sslConfig.IsEnabled())
                {
                    var sslStream = new SslStream(networkStream, false,
                                                  (sender, certificate, chain, sslPolicyErrors) =>
                                                  RemoteCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors, clientNetworkConfig),
                                                  null);
                    var certificateName            = sslConfig.GetCertificateName() ?? "";
                    var cerPath                    = sslConfig.GetCertificateFilePath();
                    var enabledSslProtocols        = sslConfig.GetSslProtocol();
                    var checkCertificateRevocation = sslConfig.IsCheckCertificateRevocation();

                    var clientCertificates = GetClientCertificatesOrDefault(cerPath, sslConfig);

                    sslStream.AuthenticateAsClient(certificateName, clientCertificates, enabledSslProtocols,
                                                   checkCertificateRevocation);

                    Logger.Info(
                        $"Client connection ready. Encrypted:{sslStream.IsEncrypted}, MutualAuthenticated:{sslStream.IsMutuallyAuthenticated} using ssl protocol:{sslStream.SslProtocol}");

                    _stream = sslStream;
                }
                else
                {
                    _stream = networkStream;
                }
                _live = new AtomicBoolean(true);
                _connectionStartTime = Clock.CurrentTimeMillis();
            }
            catch (Exception e)
            {
                _clientSocket.Close();
                if (_stream != null)
                {
                    _stream.Close();
                }
                throw new IOException("Cannot init connection.", e);
            }
        }