コード例 #1
0
        public Address GetPartitionOwner(int partitionId)
        {
            Address partitionOwner = null;

            while (_live.Get() && !_partitions.TryGetValue(partitionId, out partitionOwner))
            {
                if (Logger.IsFinestEnabled())
                {
                    Logger.Finest("Address of a partition cannot be null. Retrying to get it...");
                }
                Thread.Sleep(100);
            }
            if (!_live.Get())
            {
                throw new HazelcastException("Client is shut down.");
            }

            var member = _client.GetClientClusterService().GetMember(partitionOwner);

            if (member == null)
            {
                throw new TargetNotMemberException("Invalid Member address");
            }
            return(partitionOwner);
        }
コード例 #2
0
        public string AddDistributedObjectListener(IDistributedObjectListener listener)
        {
            var isSmart = _client.GetClientConfig().GetNetworkConfig().IsSmartRouting();
            var request = ClientAddDistributedObjectListenerCodec.EncodeRequest(isSmart);
            var context = new ClientContext(_client.GetSerializationService(), _client.GetClientClusterService(),
                                            _client.GetClientPartitionService(), _client.GetInvocationService(), _client.GetClientExecutionService(),
                                            _client.GetListenerService(), _client.GetNearCacheManager(), this, _client.GetClientConfig());
            DistributedEventHandler eventHandler = delegate(IClientMessage message)
            {
                ClientAddDistributedObjectListenerCodec.EventHandler.HandleEvent(message, (name, serviceName, eventType) =>
                {
                    var _event = new LazyDistributedObjectEvent(eventType, serviceName, name, this);
                    switch (eventType)
                    {
                    case DistributedObjectEvent.EventType.Created:
                        listener.DistributedObjectCreated(_event);
                        break;

                    case DistributedObjectEvent.EventType.Destroyed:
                        listener.DistributedObjectDestroyed(_event);
                        break;

                    default:
                        Logger.Warning(string.Format("Undefined DistributedObjectListener event type received: {0} !!!",
                                                     eventType));
                        break;
                    }
                });
            };

            return(context.GetListenerService().RegisterListener(request,
                                                                 m => ClientAddDistributedObjectListenerCodec.DecodeResponse(m).response,
                                                                 ClientRemoveDistributedObjectListenerCodec.EncodeRequest, eventHandler));
        }
コード例 #3
0
        private void FetchMetadataInternal(IList <string> names,
                                           Action <MapFetchNearCacheInvalidationMetadataCodec.ResponseParameters> process)
        {
            var dataMembers = _client.GetClientClusterService().GetMemberList().Where(member => !member.IsLiteMember);

            foreach (var member in dataMembers)
            {
                var address = member.GetAddress();
                var request = MapFetchNearCacheInvalidationMetadataCodec.EncodeRequest(names, address);
                try
                {
                    var future = _client.GetInvocationService().InvokeOnTarget(request, address);
                    var task   = future.ToTask();

                    task.ContinueWith(t =>
                    {
                        if (t.IsFaulted)
                        {
                            // ReSharper disable once PossibleNullReferenceException
                            throw t.Exception.Flatten().InnerExceptions.First();
                        }
                        var responseMessage   = ThreadUtil.GetResult(t, AsyncResultWaitTimeoutMillis);
                        var responseParameter =
                            MapFetchNearCacheInvalidationMetadataCodec.DecodeResponse(responseMessage);
                        process(responseParameter);
                    }).IgnoreExceptions();
                }
                catch (Exception e)
                {
                    Logger.Warning(string.Format("Cant fetch invalidation meta-data from address:{0} [{1}]", address,
                                                 e.Message));
                }
            }
        }
コード例 #4
0
        private void InvokeInternal(ClientInvocation invocation, Address address = null, ClientConnection connection = null)
        {
            try
            {
                if (connection == null)
                {
                    if (address == null)
                    {
                        address = GetRandomAddress();
                    }
                    connection = GetConnection(address);
                    if (connection == null)
                    {
                        if (address != null && _client.GetClientClusterService().GetMember(address) == null)
                        {
                            throw new TargetNotMemberException(string.Format("Target {0} is not a member.", address));
                        }

                        //Create an async connection and send the invocation afterward.
                        _clientConnectionManager.GetOrConnectAsync(address).ContinueWith(t =>
                        {
                            if (t.IsFaulted)
                            {
                                HandleInvocationException(invocation, t.Exception.Flatten().InnerExceptions.First());
                            }
                            else
                            {
                                InvokeInternal(invocation, address, t.Result);
                            }
                        })
                        .ContinueWith(t =>
                        {
                            HandleInvocationException(invocation, t.Exception.Flatten().InnerExceptions.First());
                        }, TaskContinuationOptions.OnlyOnFaulted |
                                      TaskContinuationOptions.ExecuteSynchronously);
                        return;
                    }
                }
                //Sending Invocation via connection
                UpdateInvocation(invocation, connection);
                ValidateInvocation(invocation, connection);

                if (!TrySend(invocation, connection))
                {
                    //Sending failed.
                    if (_client.GetConnectionManager().Live)
                    {
                        throw new TargetDisconnectedException(connection.GetAddress(), "Error writing to socket.");
                    }
                    throw new HazelcastException("Client is shut down.");
                }
                //Successfully sent.
            }
            catch (Exception e)
            {
                HandleInvocationException(invocation, e);
            }
        }
コード例 #5
0
        private void ClusterAuthenticator(ClientConnection connection)
        {
            var ss             = _client.GetSerializationService();
            var clusterService = (ClientClusterService)_client.GetClientClusterService();
            var principal      = clusterService.GetPrincipal();

            var           uuid      = principal.GetUuid();
            var           ownerUuid = principal.GetOwnerUuid();
            ClientMessage request;

            var usernamePasswordCr = _credentials as UsernamePasswordCredentials;

            if (usernamePasswordCr != null)
            {
                request = ClientAuthenticationCodec.EncodeRequest(usernamePasswordCr.GetUsername(),
                                                                  usernamePasswordCr.GetPassword(), uuid, ownerUuid, false,
                                                                  ClientTypes.Csharp, _client.GetSerializationService().GetVersion(), VersionUtil.GetDllVersion());
            }
            else
            {
                var data = ss.ToData(_credentials);
                request = ClientAuthenticationCustomCodec.EncodeRequest(data, uuid, ownerUuid, false,
                                                                        ClientTypes.Csharp, _client.GetSerializationService().GetVersion(), VersionUtil.GetDllVersion());
            }

            IClientMessage response;

            try
            {
                var future = ((ClientInvocationService)_client.GetInvocationService()).InvokeOnConnection(request,
                                                                                                          connection);
                response = ThreadUtil.GetResult(future);
            }
            catch (Exception e)
            {
                throw ExceptionUtil.Rethrow(e);
            }
            var rp = ClientAuthenticationCodec.DecodeResponse(response);

            if (rp.address == null)
            {
                throw new HazelcastException("Could not resolve address for member.");
            }

            var member = _client.GetClientClusterService().GetMember(rp.address);

            if (member == null)
            {
                throw new HazelcastException("Node with address '" + rp.address + "' was not found in the member list");
            }
            connection.Member = member;
        }
コード例 #6
0
 public ClientMembershipListener(HazelcastClient client)
 {
     _client = client;
     _connectionManager = (ClientConnectionManager) client.GetConnectionManager();
     _partitionService = (ClientPartitionService) client.GetClientPartitionService();
     _clusterService = (ClientClusterService) client.GetClientClusterService();
 }
コード例 #7
0
        private IList <Address> GetPossibleMemberAddresses()
        {
            var memberList = _client.GetClientClusterService().GetMemberList();
            var addresses  = memberList.Select(member => member.GetAddress()).ToList();

            if (_shuffleMemberList)
            {
                addresses = Shuffle(addresses);
            }

            var configAddresses = GetConfigAddresses();

            if (_shuffleMemberList)
            {
                configAddresses = Shuffle(configAddresses);
            }

            addresses.AddRange(configAddresses);
            if (_prevOwnerConnectionAddress != null)
            {
                /*
                 * Previous owner address is moved to last item in set so that client will not try to connect to same one immediately.
                 * It could be the case that address is removed because it is healthy(it not responding to heartbeat/pings)
                 * In that case, trying other addresses first to upgrade make more sense.
                 */
                addresses.Remove(_prevOwnerConnectionAddress);
                addresses.Add(_prevOwnerConnectionAddress);
            }
            return(addresses);
        }
コード例 #8
0
 private bool GetPartitions()
 {
     if (_updating.CompareAndSet(false, true))
     {
         try
         {
             Logger.Finest("Updating partition list.");
             var clusterService = _client.GetClientClusterService();
             var ownerAddress   = clusterService.GetOwnerConnectionAddress();
             var connection     = _client.GetConnectionManager().GetConnection(ownerAddress);
             if (connection == null)
             {
                 throw new InvalidOperationException(
                           "Owner connection is not available, could not get partitions.");
             }
             var response = GetPartitionsFrom(connection);
             var result   = ProcessPartitionResponse(response);
             Logger.Finest("Partition list updated");
             return(result);
         }
         catch (HazelcastInstanceNotActiveException ignored)
         {
         }
         catch (Exception e)
         {
             Logger.Warning("Error when getting list of partitions", e);
         }
         finally
         {
             _updating.Set(false);
         }
     }
     return(false);
 }
コード例 #9
0
 public ClientMembershipListener(HazelcastClient client)
 {
     _client            = client;
     _connectionManager = (ClientConnectionManager)client.GetConnectionManager();
     _partitionService  = (ClientPartitionService)client.GetClientPartitionService();
     _clusterService    = (ClientClusterService)client.GetClientClusterService();
 }
コード例 #10
0
        private void EnsureOwnerConnectionAvailable()
        {
            var clientClusterService   = _client.GetClientClusterService();
            var ownerConnectionAddress = clientClusterService.GetOwnerConnectionAddress();

            var isOwnerConnectionAvailable = ownerConnectionAddress != null &&
                                             _clientConnectionManager.GetConnection(ownerConnectionAddress) != null;

            if (!isOwnerConnectionAvailable)
            {
                if (_isShutDown)
                {
                    throw new HazelcastException("Client is shut down.");
                }
                throw new IOException("Owner connection was not live.");
            }
        }
コード例 #11
0
        internal void TrySyncConnectToAllConnections()
        {
            if (!IsSmart)
            {
                return;
            }
            long timeLeftMillis = ((ClientInvocationService)_client.GetInvocationService()).InvocationTimeoutMillis;

            do
            {
                // Define the cancellation token.
                using (var source = new CancellationTokenSource())
                {
                    var token = source.Token;
                    var clientClusterService = _client.GetClientClusterService();
                    var tasks = clientClusterService.GetMemberList().Select(member => Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            _connectionManager.GetOrConnectAsync(member.GetAddress()).Wait(token);
                        }
                        catch (Exception)
                        {
                            // if an exception occur cancel the process
                            source.Cancel();
                        }
                    }, token)).ToArray();

                    var start = Clock.CurrentTimeMillis();
                    try
                    {
                        if (Task.WaitAll(tasks, (int)timeLeftMillis, token))
                        {
                            //All succeed
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        //waitAll did not completed
                    }
                    timeLeftMillis -= Clock.CurrentTimeMillis() - start;
                }
            } while (_client.GetLifecycleService().IsRunning() && timeLeftMillis > 0);
            throw new TimeoutException("Registering listeners is timed out.");
        }
コード例 #12
0
        public string AddDistributedObjectListener(IDistributedObjectListener listener)
        {
            var isSmart = _client.GetClientConfig().GetNetworkConfig().IsSmartRouting();
            var request = ClientAddDistributedObjectListenerCodec.EncodeRequest(isSmart);
            var context = new ClientContext(_client.GetSerializationService(), _client.GetClientClusterService(),
                                            _client.GetClientPartitionService(), _client.GetInvocationService(), _client.GetClientExecutionService(),
                                            _client.GetListenerService(),
                                            this, _client.GetClientConfig());
            //EventHandler<PortableDistributedObjectEvent> eventHandler = new _EventHandler_211(this, listener);

            DistributedEventHandler eventHandler = delegate(IClientMessage message)
            {
                ClientAddDistributedObjectListenerCodec.AbstractEventHandler.Handle(message,
                                                                                    (name, serviceName, type) =>
                {
                    var ns = new ObjectNamespace(serviceName, name);
                    ClientProxy proxy;
                    _proxies.TryGetValue(ns, out proxy);
                    if (proxy == null)
                    {
                        proxy = GetProxy(serviceName, name);
                    }
                    var _event = new DistributedObjectEvent(type, serviceName, proxy);
                    if (DistributedObjectEvent.EventType.Created.Equals(type))
                    {
                        listener.DistributedObjectCreated(_event);
                    }
                    else
                    {
                        if (DistributedObjectEvent.EventType.Destroyed.Equals(type))
                        {
                            listener.DistributedObjectDestroyed(_event);
                        }
                    }
                });
            };

            //PortableDistributedObjectEvent
            return(context.GetListenerService().RegisterListener(request,
                                                                 m => ClientAddDistributedObjectListenerCodec.DecodeResponse(m).response,
                                                                 ClientRemoveDistributedObjectListenerCodec.EncodeRequest,
                                                                 eventHandler));
        }
コード例 #13
0
        private IList <IPEndPoint> GetEndpoints()
        {
            var memberList = _client.GetClientClusterService().GetMemberList();
            var endpoints  = memberList.Select(member => member.GetSocketAddress());

            endpoints = endpoints.Union(GetConfigAddresses());

            var r = new Random();

            return(endpoints.OrderBy(x => r.Next()).ToList());
        }
コード例 #14
0
        public TransactionContextProxy(HazelcastClient client, TransactionOptions options)
        {
            Client = client;

            var clusterService = (ClientClusterService)client.GetClientClusterService();

            TxnOwnerNode = clusterService.GetRandomMember();
            if (TxnOwnerNode == null)
            {
                throw new HazelcastException("Could not find matching member");
            }
            Transaction = new TransactionProxy(client, options, TxnOwnerNode);
        }
コード例 #15
0
        public TransactionContextProxy(HazelcastClient client, TransactionOptions options)
        {
            _client = client;
            var clusterService = (ClientClusterService)client.GetClientClusterService();

            TxnOwnerNode = client.GetClientConfig().GetNetworkConfig().IsSmartRouting() ?
                           client.GetLoadBalancer().Next():
                           clusterService.GetMember(clusterService.GetOwnerConnectionAddress());

            if (TxnOwnerNode == null)
            {
                throw new HazelcastException("Could not find matching member");
            }
            _transaction = new TransactionProxy(client, options, TxnOwnerNode);
        }
コード例 #16
0
        private Address GetNewInvocationAddress(ClientInvocation invocation)
        {
            Address newAddress = null;

            if (invocation.Address != null)
            {
                newAddress = invocation.Address;
            }
            else if (invocation.MemberUuid != null)
            {
                var member = _client.GetClientClusterService().GetMember(invocation.MemberUuid);
                if (member == null)
                {
                    Logger.Finest("Could not find a member with UUID " + invocation.MemberUuid);
                    throw new InvalidOperationException("Could not find a member with UUID " + invocation.MemberUuid);
                }
                newAddress = member.GetAddress();
            }
            else if (invocation.PartitionId != -1)
            {
                newAddress = _client.GetClientPartitionService().GetPartitionOwner(invocation.PartitionId);
            }
            return(newAddress);
        }
コード例 #17
0
        private void Authenticate(ClientConnection connection, bool isOwnerConnection)
        {
            if (Logger.IsFinestEnabled())
            {
                Logger.Finest(string.Format("Authenticating against the {0} node", isOwnerConnection?"owner":"non-owner"));
            }
            string uuid      = null;
            string ownerUuid = null;

            if (ClientPrincipal != null)
            {
                uuid      = ClientPrincipal.GetUuid();
                ownerUuid = ClientPrincipal.GetOwnerUuid();
            }

            var           ss = _client.GetSerializationService();
            ClientMessage request;
            var           credentials = _credentialsFactory.NewCredentials();

            LastCredentials = credentials;
            if (credentials.GetType() == typeof(UsernamePasswordCredentials))
            {
                var usernamePasswordCr = (UsernamePasswordCredentials)credentials;
                request = ClientAuthenticationCodec.EncodeRequest(usernamePasswordCr.Username, usernamePasswordCr.Password, uuid,
                                                                  ownerUuid, isOwnerConnection, ClientTypes.Csharp, ss.GetVersion(), VersionUtil.GetDllVersion());
            }
            else
            {
                var data = ss.ToData(credentials);
                request = ClientAuthenticationCustomCodec.EncodeRequest(data, uuid, ownerUuid, isOwnerConnection,
                                                                        ClientTypes.Csharp, ss.GetVersion(), VersionUtil.GetDllVersion());
            }

            IClientMessage response;

            try
            {
                var invocationService = (ClientInvocationService)_client.GetInvocationService();
                response = ThreadUtil.GetResult(invocationService.InvokeOnConnection(request, connection), _heartbeatTimeout);
            }
            catch (Exception e)
            {
                var ue = ExceptionUtil.Rethrow(e);
                Logger.Finest("Member returned an exception during authentication.", ue);
                throw ue;
            }
            var result = ClientAuthenticationCodec.DecodeResponse(response);

            if (result.address == null)
            {
                throw new HazelcastException("Could not resolve address for member.");
            }
            switch (result.status)
            {
            case AuthenticationStatus.Authenticated:
                if (isOwnerConnection)
                {
                    var member = new Member(result.address, result.ownerUuid);
                    ClientPrincipal   = new ClientPrincipal(result.uuid, result.ownerUuid);
                    connection.Member = member;
                    connection.SetOwner();
                    connection.ConnectedServerVersionStr = result.serverHazelcastVersion;
                }
                else
                {
                    var member = _client.GetClientClusterService().GetMember(result.address);
                    if (member == null)
                    {
                        throw new HazelcastException(string.Format("Node with address '{0}' was not found in the member list",
                                                                   result.address));
                    }
                    connection.Member = member;
                }
                break;

            case AuthenticationStatus.CredentialsFailed:
                throw new AuthenticationException("Invalid credentials! Principal: " + ClientPrincipal);

            case AuthenticationStatus.SerializationVersionMismatch:
                throw new InvalidOperationException("Server serialization version does not match to client");

            default:
                throw new AuthenticationException("Authentication status code not supported. status: " + result.status);
            }
        }