protected virtual void GetAllInternal(ICollection <IData> keyDatas, List <object> resultingKeyValuePairs) { var partitionToKeyData = GetPartitionKeyData(keyDatas); var invocationService = GetContext().GetInvocationService(); var futures = new List <IFuture <IClientMessage> >(partitionToKeyData.Count); foreach (var kvp in partitionToKeyData) { var partitionId = kvp.Key; var keyList = kvp.Value; if (keyList.Count > 0) { var request = MapGetAllCodec.EncodeRequest(GetName(), keyList); futures.Add(invocationService.InvokeOnPartition(request, partitionId)); } } var messages = ThreadUtil.GetResult(futures); foreach (var clientMessage in messages) { var items = MapGetAllCodec.DecodeResponse(clientMessage).response; foreach (var entry in items) { resultingKeyValuePairs.Add(entry.Key); resultingKeyValuePairs.Add(entry.Value); } } }
public void PutAll(IDictionary <K, V> m) { var partitionService = GetContext().GetPartitionService(); var partitions = new Dictionary <int, IDictionary <IData, IData> >(partitionService.GetPartitionCount()); foreach (var kvp in m) { var keyData = ToData(kvp.Key); InvalidateNearCacheEntry(keyData); var partitionId = partitionService.GetPartitionId(keyData); IDictionary <IData, IData> partition = null; if (!partitions.TryGetValue(partitionId, out partition)) { partition = new Dictionary <IData, IData>(); partitions[partitionId] = partition; } partition[keyData] = ToData(kvp.Value); } var futures = new List <IFuture <IClientMessage> >(partitions.Count); foreach (var kvp in partitions) { var request = MapPutAllCodec.EncodeRequest(GetName(), kvp.Value); var future = GetContext().GetInvocationService().InvokeOnPartition(request, kvp.Key); futures.Add(future); } ThreadUtil.GetResult(futures); }
private void RegisterListenerOnConnection(ListenerRegistrationKey registrationKey, ClientConnection connection) { //This method should only be called from registrationExecutor Debug.Assert(!Thread.CurrentThread.Name.Contains("eventRegistration")); ConcurrentDictionary <ClientConnection, EventRegistration> registrationMap; if (_registrations.TryGetValue(registrationKey, out registrationMap) && registrationMap.ContainsKey(connection)) { return; } var future = ((ClientInvocationService)_client.GetInvocationService()) .InvokeListenerOnConnection(registrationKey.RegistrationRequest, registrationKey.EventHandler, connection); IClientMessage clientMessage; try { clientMessage = ThreadUtil.GetResult(future); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } var serverRegistrationId = registrationKey.ResponseDecoder(clientMessage); var correlationId = registrationKey.RegistrationRequest.GetCorrelationId(); var registration = new EventRegistration(serverRegistrationId, correlationId, connection); Debug.Assert(registrationMap != null, "registrationMap should be created!"); registrationMap[connection] = registration; }
private void HearthBeatLoop() { while (_live) { foreach (var clientConnection in _addresses.Values) { var request = ClientPingCodec.EncodeRequest(); var task = ((ClientInvocationService)_client.GetInvocationService()).InvokeOnConnection(request, clientConnection); Logger.Finest("Sending heartbeat request to " + clientConnection.GetAddress()); try { var response = ThreadUtil.GetResult(task, _heartBeatTimeout); var result = ClientPingCodec.DecodeResponse(response); Logger.Finest("Got heartbeat response from " + clientConnection.GetAddress()); } catch (Exception e) { Logger.Warning(string.Format("Error getting heartbeat from {0}: {1}", clientConnection.GetAddress(), e)); var connection = clientConnection; FireHeartBeatEvent((listener) => listener.HeartBeatStopped(connection)); } } try { Thread.Sleep(_heartBeatInterval); } catch (Exception) { break; } } }
public string StartListening(IClientMessage request, DistributedEventHandler handler, DecodeStartListenerResponse responseDecoder, object key = null) { try { IFuture <IClientMessage> task; if (key == null) { task = _client.GetInvocationService() .InvokeListenerOnRandomTarget(request, handler, responseDecoder); } else { task = _client.GetInvocationService() .InvokeListenerOnKeyOwner(request, key, handler, responseDecoder); } var clientMessage = ThreadUtil.GetResult(task); var registrationId = responseDecoder(clientMessage); RegisterListener(registrationId, request.GetCorrelationId()); return(registrationId); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
public bool StopListening(EncodeStopListenerRequest requestEncoder, DecodeStopListenerResponse responseDecoder, string registrationId) { try { var realRegistrationId = UnregisterListener(registrationId); if (realRegistrationId == null) { Logger.Warning("Could not find the registration id alias for " + registrationId); return(false); } var request = requestEncoder(realRegistrationId); var task = _client.GetInvocationService().InvokeOnRandomTarget(request); var actualResult = responseDecoder(ThreadUtil.GetResult(task)); if (Logger.IsFinestEnabled() && !actualResult) { Logger.Finest("Remove listener response returned false from server for registration id " + registrationId); } return(true); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private void FetchMetadataInternal(IList <string> names, Action <MapFetchNearCacheInvalidationMetadataCodec.ResponseParameters> process) { var dataMembers = _client.ClusterService.DataMemberList; foreach (var member in dataMembers) { var request = MapFetchNearCacheInvalidationMetadataCodec.EncodeRequest(names, member.Uuid); try { var future = _client.InvocationService.InvokeOnTarget(request, member.Uuid); 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($"Cant fetch invalidation meta-data from address:{member.Address} [{e.Message}]"); } } }
private void RegisterListenerOnConnection(ListenerRegistration listenerRegistration, ClientConnection connection) { //This method should only be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.Contains("eventRegistration")); if (listenerRegistration.ConnectionRegistrations.ContainsKey(connection)) { return; } var future = ((ClientInvocationService)_client.GetInvocationService()).InvokeListenerOnConnection( listenerRegistration.RegistrationRequest, listenerRegistration.EventHandler, connection); IClientMessage clientMessage; try { clientMessage = ThreadUtil.GetResult(future); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } var serverRegistrationId = listenerRegistration.DecodeRegisterResponse(clientMessage); var correlationId = listenerRegistration.RegistrationRequest.GetCorrelationId(); var registration = new EventRegistration(serverRegistrationId, correlationId, connection); Debug.Assert(listenerRegistration.ConnectionRegistrations != null, "registrationMap should be created!"); listenerRegistration.ConnectionRegistrations[connection] = registration; }
public ICollection <IDistributedObject> GetDistributedObjects() { try { var request = ClientGetDistributedObjectsCodec.EncodeRequest(); var task = _client.InvocationService.InvokeOnRandomTarget(request); var localDistributedObjects = new HashSet <DistributedObjectInfo>(); var distributedObjects = GetLocalDistributedObjects(); foreach (var localInfo in distributedObjects) { localDistributedObjects.Add(new DistributedObjectInfo(localInfo.ServiceName, localInfo.Name)); } var response = ThreadUtil.GetResult(task); var newDistributedObjectInfo = ClientGetDistributedObjectsCodec.DecodeResponse(response).Response; foreach (var distributedObjectInfo in newDistributedObjectInfo) { localDistributedObjects.Remove(distributedObjectInfo); GetOrCreateLocalProxy <IDistributedObject>(distributedObjectInfo.ServiceName, distributedObjectInfo.Name); } foreach (var distributedObjectInfo in localDistributedObjects) { DestroyProxyLocally(distributedObjectInfo.ServiceName, distributedObjectInfo.Name); } return(GetLocalDistributedObjects()); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private void InitializeOnServer(ClientProxy clientProxy) { var initializationTarget = FindNextAddressToCreateARequest(); var invocationTarget = initializationTarget; if (initializationTarget != null && _client.GetConnectionManager().GetConnection(initializationTarget) == null) { invocationTarget = _client.GetClientClusterService().GetOwnerConnectionAddress(); } if (invocationTarget == null) { throw new IOException("Not able to setup owner connection!"); } var request = ClientCreateProxyCodec.EncodeRequest(clientProxy.GetName(), clientProxy.GetServiceName(), initializationTarget); try { ThreadUtil.GetResult(_client.GetInvocationService().InvokeOnTarget(request, invocationTarget)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private ClientGetPartitionsCodec.ResponseParameters GetPartitionsFrom(ClientConnection connection) { var request = ClientGetPartitionsCodec.EncodeRequest(); var task = ((ClientInvocationService)_client.GetInvocationService()).InvokeOnConnection(request, connection); var result = ThreadUtil.GetResult(task, PartitionTimeout); return(ClientGetPartitionsCodec.DecodeResponse(result)); }
protected virtual IClientMessage Invoke(IClientMessage request) { try { var task = GetContext().GetInvocationService().InvokeOnRandomTarget(request); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private void ManagerAuthenticator(ClientConnection connection) { Logger.Finest("Authenticating against the owner node"); var ss = _client.GetSerializationService(); string uuid = null; string ownerUuid = null; if (_principal != null) { uuid = _principal.GetUuid(); ownerUuid = _principal.GetOwnerUuid(); } ClientMessage request; if (_credentials is UsernamePasswordCredentials) { var usernamePasswordCr = (UsernamePasswordCredentials)_credentials; request = ClientAuthenticationCodec.EncodeRequest(usernamePasswordCr.GetUsername(), usernamePasswordCr.GetPassword(), uuid, ownerUuid, true, 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 invocationService = (ClientInvocationService)_client.GetInvocationService(); response = ThreadUtil.GetResult(invocationService.InvokeOnConnection(request, connection)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } var result = ClientAuthenticationCodec.DecodeResponse(response); if (result.address == null) { throw new HazelcastException("Could not resolve address for owner node."); } var member = new Member(result.address, result.ownerUuid); _principal = new ClientPrincipal(result.uuid, result.ownerUuid); connection.Member = member; connection.SetOwner(); connection.ConnectedServerVersionStr = result.serverHazelcastVersion; }
protected virtual IClientMessage Invoke(IClientMessage request, object key) { try { var task = GetContext().GetInvocationService().InvokeOnKeyOwner(request, key); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
public IDictionary <TKey, TValue> GetAll(ICollection <TKey> keys) { var partitionToKeyData = GetPartitionKeyData(keys); var result = new Dictionary <TKey, TValue>(); if (_nearCache != null) { // remove items from list which are already found in the cache foreach (var kvp in partitionToKeyData) { var list = kvp.Value; for (var i = list.Count - 1; i >= 0; i--) { var keyData = kvp.Value[i]; var cached = _nearCache.Get(keyData); if (cached != null && cached != ClientNearCache.NullObject) { list.RemoveAt(i); result.Add(ToObject <TKey>(keyData), (TValue)cached); } } } } var invocationService = GetContext().GetInvocationService(); var futures = new List <IFuture <IClientMessage> >(partitionToKeyData.Count); foreach (var kvp in partitionToKeyData) { if (kvp.Value.Count > 0) { var request = MapGetAllCodec.EncodeRequest(GetName(), kvp.Value); futures.Add(invocationService.InvokeOnPartition(request, kvp.Key)); } } var messages = ThreadUtil.GetResult(futures); foreach (var clientMessage in messages) { var items = MapGetAllCodec.DecodeResponse(clientMessage).entrySet; foreach (var entry in items) { var key = ToObject <TKey>(entry.Key); var value = ToObject <TValue>(entry.Value); result.Add(key, value); if (_nearCache != null) { _nearCache.Put(entry.Key, value); } } } return(result); }
protected ClientMessage InvokeOnTarget(ClientMessage request, Guid target) { try { var task = Client.InvocationService.InvokeOnTarget(request, target); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
protected ClientMessage InvokeOnPartition(ClientMessage request, int partitionId) { try { var task = Client.InvocationService.InvokeOnPartitionOwner(request, partitionId); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
protected IClientMessage InvokeOnPartition(IClientMessage request, int partitionId) { try { var task = GetContext().GetInvocationService().InvokeOnPartition(request, partitionId); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
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; }
protected virtual void PutAllInternal(IDictionary <TKey, TValue> map, Dictionary <int, IDictionary <IData, IData> > partitions) { var futures = new List <IFuture <IClientMessage> >(partitions.Count); foreach (var kvp in partitions) { var request = MapPutAllCodec.EncodeRequest(GetName(), kvp.Value.ToList()); var future = GetContext().GetInvocationService().InvokeOnPartition(request, kvp.Key); futures.Add(future); } ThreadUtil.GetResult(futures); }
protected virtual IClientMessage Invoke(IClientMessage request) { var rpc = Proxy.GetClient().GetInvocationService(); try { var task = rpc.InvokeOnMember(request, Proxy.TxnOwnerNode); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private ClientMessage Invoke(ClientMessage request) { var invocationService = _client.InvocationService; try { var task = invocationService.InvokeOnConnection(request, _txConnection); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e, exception => new TransactionException(exception)); } }
protected virtual ClientMessage Invoke(ClientMessage request) { var rpc = Proxy.GetClient().InvocationService; try { var task = rpc.InvokeOnConnection(request, Proxy.TxnConnection); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e, exception => new TransactionException(exception)); } }
internal void ListenMembershipEvents(Address ownerConnectionAddress) { if (Logger.IsFinestEnabled()) { Logger.Finest("Starting to listen for membership events from " + ownerConnectionAddress); } _initialListFetched = new ManualResetEventSlim(); try { var clientMessage = ClientAddMembershipListenerCodec.EncodeRequest(false); DistributedEventHandler handler = m => ClientAddMembershipListenerCodec.EventHandler .HandleEvent(m, HandleMember, HandleMemberCollection, HandleMemberAttributeChange); try { var connection = _connectionManager.GetConnection(ownerConnectionAddress); if (connection == null) { throw new InvalidOperationException( "Can not load initial members list because owner connection is null. Address " + ownerConnectionAddress); } var invocationService = (ClientInvocationService)_client.GetInvocationService(); var future = invocationService.InvokeListenerOnConnection(clientMessage, handler, connection); var response = ThreadUtil.GetResult(future); //registration id is ignored as this listener will never be removed var registirationId = ClientAddMembershipListenerCodec.DecodeResponse(response).response; WaitInitialMemberListFetched(); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } } catch (Exception e) { if (_client.GetLifecycleService().IsRunning()) { if (Logger.IsFinestEnabled()) { Logger.Warning("Error while registering to cluster events! -> " + ownerConnectionAddress, e); } else { Logger.Warning("Error while registering to cluster events! -> " + ownerConnectionAddress + ", Error: " + e); } } } }
private IClientMessage Invoke(IClientMessage request) { var rpc = _client.GetInvocationService(); try { var task = rpc.InvokeOnMember(request, _txOwner); return(ThreadUtil.GetResult(task)); } catch (Exception e) { throw ExceptionUtil.Rethrow(e); } }
private void AuthenticateOnCluster(Connection connection) { var request = EncodeAuthenticationRequest(); var future = _client.InvocationService.InvokeOnConnection(request, connection); ClientAuthenticationCodec.ResponseParameters response; try { var responseMsg = ThreadUtil.GetResult(future, _authenticationTimeout); response = ClientAuthenticationCodec.DecodeResponse(responseMsg); } catch (Exception e) { connection.Close("Failed to authenticate connection", e); throw Rethrow(e); } var authenticationStatus = (AuthenticationStatus)response.Status; switch (authenticationStatus) { case AuthenticationStatus.Authenticated: HandleSuccessfulAuth(connection, response); break; case AuthenticationStatus.CredentialsFailed: var authException = new AuthenticationException("Invalid credentials!"); connection.Close("Failed to authenticate connection", authException); throw authException; case AuthenticationStatus.NotAllowedInCluster: var notAllowedException = new ClientNotAllowedInClusterException("Client is not allowed in the cluster"); connection.Close("Failed to authenticate connection", notAllowedException); throw notAllowedException; case AuthenticationStatus.SerializationVersionMismatch: var operationException = new InvalidOperationException("Server serialization version does not match to client"); connection.Close("Failed to authenticate connection", operationException); throw operationException; default: var exception = new AuthenticationException("Authentication status code not supported. status: " + authenticationStatus); connection.Close("Failed to authenticate connection", exception); throw exception; } }
protected virtual Task <T> InvokeAsync <T>(ClientMessage request, object key, Func <ClientMessage, T> decodeResponse) { var future = Client.InvocationService.InvokeOnKeyOwner(request, key); var continueTask = future.ToTask().ContinueWith(t => { if (t.IsFaulted) { // ReSharper disable once PossibleNullReferenceException throw t.Exception.Flatten().InnerExceptions.First(); } var clientMessage = ThreadUtil.GetResult(t); return(decodeResponse(clientMessage)); }); return(continueTask); }
protected virtual void PutAllInternal(IDictionary <TKey, TValue> map, ArrayList partitions) { var futures = new ConcurrentQueue <IFuture <IClientMessage> >(); Parallel.For(0, partitions.Count, i => { var entries = (ArrayList)partitions[i]; if (entries.Count > 0) { var request = MapPutAllCodec.EncodeRequest(GetName(), entries); var future = GetContext().GetInvocationService().InvokeOnPartition(request, i); futures.Enqueue(future); } }); ThreadUtil.GetResult(futures); }
private bool DeregisterListenerInternal(string userRegistrationId, EncodeDeregisterListenerRequest encodeDeregisterListenerRequest) { Debug.Assert(!Thread.CurrentThread.Name.Contains("eventRegistration")); var key = new ListenerRegistrationKey(userRegistrationId); ConcurrentDictionary <ClientConnection, EventRegistration> registrationMap; if (!_registrations.TryGetValue(key, out registrationMap)) { return(false); } var successful = true; foreach (var registration in registrationMap.Values) { var connection = registration.ClientConnection; try { var serverRegistrationId = registration.ServerRegistrationId; var request = encodeDeregisterListenerRequest(serverRegistrationId); var future = ((ClientInvocationService)_client.GetInvocationService()) .InvokeOnConnection(request, connection); ThreadUtil.GetResult(future); DistributedEventHandler removed; _eventHandlers.TryRemove(registration.CorrelationId, out removed); EventRegistration reg; registrationMap.TryRemove(connection, out reg); } catch (Exception e) { if (connection.Live) { successful = false; Logger.Warning( string.Format("Deregistration of listener with ID {0} has failed to address {1}", userRegistrationId, connection.GetLocalSocketAddress()), e); } } } if (successful) { _registrations.TryRemove(key, out registrationMap); } return(successful); }
private bool DeregisterListenerInternal(string userRegistrationId) { //This method should only be called from registrationExecutor Debug.Assert(Thread.CurrentThread.Name != null && Thread.CurrentThread.Name.Contains("eventRegistration")); ListenerRegistration listenerRegistration; if (!_registrations.TryGetValue(userRegistrationId, out listenerRegistration)) { return(false); } var successful = true; foreach (var connectionRegistration in listenerRegistration.ConnectionRegistrations.Values) { var connection = connectionRegistration.ClientConnection; try { var serverRegistrationId = connectionRegistration.ServerRegistrationId; var request = listenerRegistration.EncodeDeregisterRequest(serverRegistrationId); var future = ((ClientInvocationService)_client.GetInvocationService()).InvokeOnConnection(request, connection); ThreadUtil.GetResult(future); DistributedEventHandler removed; _eventHandlers.TryRemove(connectionRegistration.CorrelationId, out removed); EventRegistration reg; listenerRegistration.ConnectionRegistrations.TryRemove(connection, out reg); } catch (Exception e) { if (connection.Live) { successful = false; Logger.Warning( string.Format("Deregistration of listener with ID {0} has failed to address {1}", userRegistrationId, connection.GetLocalSocketAddress()), e); } } } if (successful) { _registrations.TryRemove(userRegistrationId, out listenerRegistration); } return(successful); }