Exemplo n.º 1
0
        private HazelcastClient(ClientConfig config)
        {
            _config = config;
            var groupConfig = config.GetGroupConfig();

            _instanceName = "hz.client_" + _id + (groupConfig != null ? "_" + groupConfig.GetName() : string.Empty);

            _lifecycleService = new LifecycleService(this);
            try
            {
                //TODO make partition strategy parametric
                var partitioningStrategy = new DefaultPartitioningStrategy();
                _serializationService =
                    new SerializationServiceBuilder().SetManagedContext(new HazelcastClientManagedContext(this,
                                                                                                          config.GetManagedContext()))
                    .SetConfig(config.GetSerializationConfig())
                    .SetPartitioningStrategy(partitioningStrategy)
                    .SetVersion(SerializationService.SerializerVersion)
                    .Build();
            }
            catch (Exception e)
            {
                throw ExceptionUtil.Rethrow(e);
            }
            _proxyManager = new ProxyManager(this);

            //TODO EXECUTION SERVICE
            _executionService = new ClientExecutionService(_instanceName, config.GetExecutorPoolSize());
            _clusterService   = new ClientClusterService(this);
            _loadBalancer     = config.GetLoadBalancer() ?? new RoundRobinLB();

            _addressProvider          = new AddressProvider(_config);
            _connectionManager        = new ClientConnectionManager(this);
            _invocationService        = CreateInvocationService();
            _listenerService          = new ClientListenerService(this);
            _userContext              = new ConcurrentDictionary <string, object>();
            _partitionService         = new ClientPartitionService(this);
            _lockReferenceIdGenerator = new ClientLockReferenceIdGenerator();
            _statistics         = new Statistics(this);
            _nearCacheManager   = new NearCacheManager(this);
            _credentialsFactory = InitCredentialsFactory(config);
        }
        /// <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);
            }
        }
Exemplo n.º 3
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);
            }
        }
Exemplo n.º 4
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();

            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.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);
                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(string.Format(
                                    "Client connection ready. Encrypted:{0}, MutualAuthenticated:{1} using ssl protocol:{2}",
                                    sslStream.IsEncrypted, sslStream.IsMutuallyAuthenticated, 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);
            }
        }