예제 #1
0
  void listenMembershipEvents(Address ownerConnectionAddress) {
    initialListFetchedLatch = new CountDownLatch(1);
    try {
      ClientMessage clientMessage = RegisterMembershipListenerParameters.encode();

      Connection connection = connectionManager.getConnection(ownerConnectionAddress);
      if (connection == null) {
        System.out.println("FATAL connection null " + ownerConnectionAddress);
        throw new IllegalStateException(
            "Can not load initial members list because owner connection is null. "
                + "Address "
                + ownerConnectionAddress);
      }
      ClientInvocation invocation = new ClientInvocation(client, this, clientMessage, connection);
      invocation.invoke().get();
      waitInitialMemberListFetched();

    } 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.toString());
        }
      }
    }
  }
    private void handleClientMessage(ClientMessage clientMessage)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
            InvocationTargetException, InstantiationException {
      int correlationId = clientMessage.getCorrelationId();

      final ClientInvocation future = deRegisterCallId(correlationId);
      if (future == null) {
        logger.warning("No call for callId: " + correlationId + ", response: " + clientMessage);
        return;
      }

      if (ErrorCodec.TYPE == clientMessage.getMessageType()) {
        ErrorCodec exParameters = ErrorCodec.decode(clientMessage);
        Throwable exception =
            clientExceptionFactory.createException(
                exParameters.errorCode,
                exParameters.className,
                exParameters.message,
                exParameters.stackTrace,
                exParameters.causeErrorCode,
                exParameters.causeClassName);
        future.notifyException(exception);
      } else {
        future.notify(clientMessage);
      }
    }
예제 #3
0
 protected void updateCacheListenerConfigOnOtherNodes(
     CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration, boolean isRegister) {
   final Collection<Member> members = clientContext.getClusterService().getMemberList();
   final HazelcastClientInstanceImpl client =
       (HazelcastClientInstanceImpl) clientContext.getHazelcastInstance();
   final Collection<Future> futures = new ArrayList<Future>();
   for (Member member : members) {
     try {
       final Address address = member.getAddress();
       Data configData = toData(cacheEntryListenerConfiguration);
       final ClientMessage request =
           CacheListenerRegistrationCodec.encodeRequest(
               nameWithPrefix, configData, isRegister, address.getHost(), address.getPort());
       final ClientInvocation invocation = new ClientInvocation(client, request, address);
       final Future future = invocation.invoke();
       futures.add(future);
     } catch (Exception e) {
       ExceptionUtil.sneakyThrow(e);
     }
   }
   // make sure all configs are created
   // TODO do we need this ???s
   //        try {
   //            FutureUtil.waitWithDeadline(futures,
   // CacheProxyUtil.AWAIT_COMPLETION_TIMEOUT_SECONDS, TimeUnit.SECONDS);
   //        } catch (TimeoutException e) {
   //            logger.warning(e);
   //        }
 }
  protected Object getInternal(K key, ExpiryPolicy expiryPolicy, boolean async) {
    ensureOpen();
    validateNotNull(key);
    final Data keyData = toData(key);
    Object cached = getFromNearCache(keyData, async);
    if (cached != null) {
      return cached;
    }
    final Data expiryPolicyData = toData(expiryPolicy);
    ClientMessage request = CacheGetCodec.encodeRequest(nameWithPrefix, keyData, expiryPolicyData);
    ClientInvocationFuture future;
    try {
      final int partitionId = clientContext.getPartitionService().getPartitionId(key);
      final HazelcastClientInstanceImpl client =
          (HazelcastClientInstanceImpl) clientContext.getHazelcastInstance();
      final ClientInvocation clientInvocation = new ClientInvocation(client, request, partitionId);
      future = clientInvocation.invoke();
    } catch (Exception e) {
      throw ExceptionUtil.rethrow(e);
    }
    SerializationService serializationService = clientContext.getSerializationService();
    ClientDelegatingFuture<V> delegatingFuture =
        new ClientDelegatingFuture<V>(future, serializationService, cacheGetResponseDecoder);
    if (async) {
      if (nearCache != null) {
        delegatingFuture.andThenInternal(
            new ExecutionCallback<Data>() {
              public void onResponse(Data valueData) {
                storeInNearCache(keyData, valueData, null);
              }

              public void onFailure(Throwable t) {}
            });
      }
      return delegatingFuture;
    } else {
      try {
        Object value = delegatingFuture.get();
        if (nearCache != null) {
          storeInNearCache(keyData, (Data) delegatingFuture.getResponse(), null);
        }
        if (!(value instanceof Data)) {
          return value;
        } else {
          return serializationService.toObject(value);
        }
      } catch (Throwable e) {
        throw ExceptionUtil.rethrowAllowedTypeFirst(e, CacheException.class);
      }
    }
  }
  private boolean isAllowedToSendRequest(ClientConnection connection, ClientInvocation invocation) {
    if (!connection.isHeartBeating()) {
      if (invocation.shouldBypassHeartbeatCheck()) {
        // ping and removeAllListeners should be send even though heart is not beating
        return true;
      }

      if (logger.isFinestEnabled()) {
        logger.warning(
            "Connection is not heart-beating, won't write client message -> "
                + invocation.getClientMessage());
      }
      return false;
    }
    return true;
  }
  protected void send(ClientInvocation invocation, ClientConnection connection) throws IOException {
    if (isShutdown) {
      throw new HazelcastClientNotActiveException("Client is shut down");
    }
    registerInvocation(invocation);

    ClientMessage clientMessage = invocation.getClientMessage();
    if (!isAllowedToSendRequest(connection, invocation)
        || !writeToConnection(connection, clientMessage)) {
      final int callId = clientMessage.getCorrelationId();
      deRegisterCallId(callId);
      deRegisterEventHandler(callId);
      throw new IOException("Packet not send to " + connection.getRemoteEndpoint());
    }
    invocation.setSendConnection(connection);
  }
  private void invoke(ClientRegistrationKey registrationKey, Address address) throws Exception {
    ListenerMessageCodec codec = registrationKey.getCodec();
    ClientMessage request = codec.encodeAddRequest(true);
    EventHandler handler = registrationKey.getHandler();
    handler.beforeListenerRegister();

    ClientInvocation invocation = new ClientInvocation(client, request, address);
    invocation.setEventHandler(handler);
    String serverRegistrationId = codec.decodeAddResponse(invocation.invoke().get());

    handler.onListenerRegister();
    int correlationId = request.getCorrelationId();
    ClientEventRegistration registration =
        new ClientEventRegistration(serverRegistrationId, correlationId, address, codec);

    Map<Address, ClientEventRegistration> registrationMap = registrations.get(registrationKey);
    registrationMap.put(address, registration);
  }
 private void registerInvocation(ClientInvocation clientInvocation) {
   short protocolVersion = client.getProtocolVersion();
   final int correlationId = newCorrelationId();
   clientInvocation.getClientMessage().setCorrelationId(correlationId).setVersion(protocolVersion);
   callIdMap.put(correlationId, clientInvocation);
   if (clientInvocation instanceof ClientListenerInvocation) {
     eventHandlerMap.put(correlationId, (ClientListenerInvocation) clientInvocation);
   }
 }
  void listenMembershipEvents(Address ownerConnectionAddress) {
    initialListFetchedLatch = new CountDownLatch(1);
    try {
      ClientMessage clientMessage = ClientMembershipListenerCodec.encodeRequest();

      Connection connection = connectionManager.getConnection(ownerConnectionAddress);
      if (connection == null) {
        throw new IllegalStateException(
            "Can not load initial members list because owner connection is null. "
                + "Address "
                + ownerConnectionAddress);
      }
      ClientInvocation invocation =
          new ClientListenerInvocation(
              client,
              this,
              clientMessage,
              connection,
              new ClientMessageDecoder() {
                @Override
                public <T> T decodeClientMessage(ClientMessage clientMessage) {
                  return (T) ClientMembershipListenerCodec.decodeResponse(clientMessage).response;
                }
              });
      invocation.invoke().get();
      waitInitialMemberListFetched();

    } 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.toString());
        }
      }
    }
  }
    private void handleClientMessage(ClientMessage clientMessage)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
            InvocationTargetException, InstantiationException {
      int correlationId = clientMessage.getCorrelationId();

      final ClientInvocation future = deRegisterCallId(correlationId);
      if (future == null) {
        logger.warning("No call for callId: " + correlationId + ", response: " + clientMessage);
        return;
      }

      if (ExceptionResultParameters.TYPE == clientMessage.getMessageType()) {
        ExceptionResultParameters exceptionResultParameters =
            ExceptionResultParameters.decode(clientMessage);
        Throwable exception;
        if (exceptionResultParameters.causeClassName != null) {
          Class<?> causeClazz = Class.forName(exceptionResultParameters.causeClassName);
          Constructor<?> causeConstructor =
              causeClazz.getDeclaredConstructor(new Class[] {String.class});
          causeConstructor.setAccessible(true);
          Throwable cause =
              (Throwable) causeConstructor.newInstance(exceptionResultParameters.message);

          Class<?> clazz = Class.forName(exceptionResultParameters.className);
          Constructor<?> constructor =
              clazz.getDeclaredConstructor(new Class[] {String.class, Throwable.class});
          constructor.setAccessible(true);
          exception = (Throwable) constructor.newInstance(exceptionResultParameters.message, cause);
        } else {
          Class<?> clazz = Class.forName(exceptionResultParameters.className);
          Constructor<?> constructor = clazz.getDeclaredConstructor(new Class[] {String.class});
          constructor.setAccessible(true);
          exception = (Throwable) constructor.newInstance(exceptionResultParameters.message);
        }
        future.notifyException(exception);
      } else {
        future.notify(clientMessage);
      }
    }
  protected void send(ClientInvocation invocation, ClientConnection connection) throws IOException {
    if (isShutdown) {
      throw new HazelcastClientNotActiveException("Client is shut down");
    }
    registerInvocation(invocation);

    ClientMessage clientMessage = invocation.getClientMessage();
    if (!isAllowedToSendRequest(connection, invocation)
        || !writeToConnection(connection, clientMessage)) {
      final int callId = clientMessage.getCorrelationId();
      ClientInvocation clientInvocation = deRegisterCallId(callId);
      deRegisterEventHandler(callId);
      if (clientInvocation != null) {
        throw new IOException("Packet not send to " + connection.getRemoteEndpoint());
      } else {
        if (logger.isFinestEnabled()) {
          logger.finest("Invocation not found to deregister for call id " + callId);
        }
      }
    }

    invocation.setSendConnection(connection);
  }
 protected ClientInvocationFuture invoke(ClientMessage req, int partitionId, int completionId) {
   final boolean completionOperation = completionId != -1;
   if (completionOperation) {
     registerCompletionLatch(completionId, 1);
   }
   try {
     HazelcastClientInstanceImpl client =
         (HazelcastClientInstanceImpl) clientContext.getHazelcastInstance();
     final ClientInvocation clientInvocation = new ClientInvocation(client, req, partitionId);
     ClientInvocationFuture f = clientInvocation.invoke();
     if (completionOperation) {
       waitCompletionLatch(completionId, f);
     }
     return f;
   } catch (Throwable e) {
     if (e instanceof IllegalStateException) {
       close();
     }
     if (completionOperation) {
       deregisterCompletionLatch(completionId);
     }
     throw ExceptionUtil.rethrowAllowedTypeFirst(e, CacheException.class);
   }
 }
  @Override
  public void heartBeatStopped(Connection connection) {
    ClientMessage request = ClientRemoveAllListenersCodec.encodeRequest();
    ClientInvocation removeListenerInvocation = new ClientInvocation(client, request, connection);
    removeListenerInvocation.setBypassHeartbeatCheck(true);
    removeListenerInvocation.invoke();

    final Address remoteEndpoint = connection.getEndPoint();
    final Iterator<ClientListenerInvocation> iterator = eventHandlerMap.values().iterator();
    final TargetDisconnectedException response = new TargetDisconnectedException(remoteEndpoint);

    while (iterator.hasNext()) {
      final ClientInvocation clientInvocation = iterator.next();
      if (clientInvocation.getSendConnection().equals(connection)) {
        iterator.remove();
        clientInvocation.notifyException(response);
      }
    }
  }
 public void cleanResources(
     ConstructorFunction<Object, Throwable> responseCtor, ClientConnection connection) {
   final Iterator<Map.Entry<Integer, ClientInvocation>> iter = callIdMap.entrySet().iterator();
   while (iter.hasNext()) {
     final Map.Entry<Integer, ClientInvocation> entry = iter.next();
     final ClientInvocation invocation = entry.getValue();
     if (connection.equals(invocation.getSendConnection())) {
       iter.remove();
       invocation.notifyException(responseCtor.createNew(null));
       eventHandlerMap.remove(entry.getKey());
     }
   }
   final Iterator<ClientListenerInvocation> iterator = eventHandlerMap.values().iterator();
   while (iterator.hasNext()) {
     final ClientInvocation invocation = iterator.next();
     if (connection.equals(invocation.getSendConnection())) {
       iterator.remove();
       invocation.notifyException(responseCtor.createNew(null));
     }
   }
 }
예제 #15
0
 private boolean isRetryable(final Throwable t) {
   return t instanceof RetryableException || ClientInvocation.isRetryable(t);
 }