public synchronized void pause() {
    if (paused) {
      return;
    }

    if (channelClazz == null) {
      return;
    }

    // We *pause* the acceptor so no new connections are made
    if (serverChannelGroup != null) {
      ChannelGroupFuture future = serverChannelGroup.close().awaitUninterruptibly();
      if (!future.isSuccess()) {
        ActiveMQServerLogger.LOGGER.nettyChannelGroupBindError();
        Iterator<Channel> iterator = future.group().iterator();
        while (iterator.hasNext()) {
          Channel channel = iterator.next();
          if (channel.isActive()) {
            ActiveMQServerLogger.LOGGER.nettyChannelStillBound(channel, channel.remoteAddress());
          }
        }
      }
    }
    paused = true;
  }
예제 #2
0
  @Override
  public Connection createConnection() {
    if (InVMConnector.failOnCreateConnection) {
      InVMConnector.incFailures();

      ActiveMQServerLogger.LOGGER.debug("Returning null on InVMConnector for tests");
      // For testing only
      return null;
    }

    if (acceptor == null) {
      return null;
    }

    if (acceptor.getConnectionsAllowed() == -1
        || acceptor.getConnectionCount() < acceptor.getConnectionsAllowed()) {
      Connection conn =
          internalCreateConnection(
              acceptor.getHandler(), new Listener(), acceptor.getExecutorFactory().getExecutor());

      acceptor.connect((String) conn.getID(), handler, this, executorFactory.getExecutor());
      return conn;
    } else {
      if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
        ActiveMQServerLogger.LOGGER.debug(
            new StringBuilder()
                .append("Connection limit of ")
                .append(acceptor.getConnectionsAllowed())
                .append(" reached. Refusing connection."));
      }
      return null;
    }
  }
 public void beginTransaction(StompConnection connection, String txID) throws Exception {
   ActiveMQServerLogger.LOGGER.stompBeginTX(txID);
   if (transactedSessions.containsKey(txID)) {
     ActiveMQServerLogger.LOGGER.stompErrorTXExists(txID);
     throw new ActiveMQStompException(connection, "Transaction already started: " + txID);
   }
   // create the transacted session
   getTransactedSession(connection, txID);
 }
예제 #4
0
    @Override
    public void run() {
      try {
        logger.debug("stopping bridge " + BridgeImpl.this);
        queue.removeConsumer(BridgeImpl.this);

        if (!pendingAcks.await(10, TimeUnit.SECONDS)) {
          ActiveMQServerLogger.LOGGER.timedOutWaitingCompletions(
              BridgeImpl.this.toString(), pendingAcks.getCount());
        }

        synchronized (BridgeImpl.this) {
          logger.debug("Closing Session for bridge " + BridgeImpl.this.name);

          started = false;

          active = false;
        }

        if (session != null) {
          logger.debug("Cleaning up session " + session);
          session.removeFailureListener(BridgeImpl.this);
          try {
            session.close();
            session = null;
          } catch (ActiveMQException dontcare) {
          }
        }

        if (sessionConsumer != null) {
          logger.debug("Cleaning up session " + session);
          try {
            sessionConsumer.close();
            sessionConsumer = null;
          } catch (ActiveMQException dontcare) {
          }
        }

        internalCancelReferences();

        if (csf != null) {
          csf.cleanup();
        }

        synchronized (connectionGuard) {
          keepConnecting = true;
        }

        if (logger.isTraceEnabled()) {
          logger.trace("Removing consumer on stopRunnable " + this + " from queue " + queue);
        }
        ActiveMQServerLogger.LOGGER.bridgeStopped(name);
      } catch (InterruptedException | RuntimeException e) {
        ActiveMQServerLogger.LOGGER.error("Failed to stop bridge", e);
      }
    }
예제 #5
0
  @Override
  public void connectionFailed(
      final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) {
    ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(failedOver);

    synchronized (connectionGuard) {
      keepConnecting = true;
    }

    try {
      if (producer != null) {
        producer.close();
      }

      cleanUpSessionFactory(csf);
    } catch (Throwable dontCare) {
    }

    try {
      session.cleanUp(false);
    } catch (Throwable dontCare) {
    }

    if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID.toString())) {
      synchronized (this) {
        try {
          logger.debug(
              "Moving "
                  + queue.getMessageCount()
                  + " messages from "
                  + queue.getName()
                  + " to "
                  + scaleDownTargetNodeID);
          ((QueueImpl) queue)
              .moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID));

          // stop the bridge from trying to reconnect and clean up all the bindings
          fail(true);
        } catch (Exception e) {
          ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e);
        }
      }
    } else if (scaleDownTargetNodeID != null) {
      // the disconnected node is scaling down to me, no need to reconnect to it
      logger.debug(
          "Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect.");
      fail(true);
    } else {
      logger.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID);

      fail(me.getType() == ActiveMQExceptionType.DISCONNECTED);
    }

    tryScheduleRetryReconnect(me.getType());
  }
  @Override
  public void handlePacket(final Packet packet) {
    PacketImpl response = new ReplicationResponseMessage();
    final byte type = packet.getType();

    try {
      if (!started) {
        return;
      }

      if (type == PacketImpl.REPLICATION_APPEND) {
        handleAppendAddRecord((ReplicationAddMessage) packet);
      } else if (type == PacketImpl.REPLICATION_APPEND_TX) {
        handleAppendAddTXRecord((ReplicationAddTXMessage) packet);
      } else if (type == PacketImpl.REPLICATION_DELETE) {
        handleAppendDelete((ReplicationDeleteMessage) packet);
      } else if (type == PacketImpl.REPLICATION_DELETE_TX) {
        handleAppendDeleteTX((ReplicationDeleteTXMessage) packet);
      } else if (type == PacketImpl.REPLICATION_PREPARE) {
        handlePrepare((ReplicationPrepareMessage) packet);
      } else if (type == PacketImpl.REPLICATION_COMMIT_ROLLBACK) {
        handleCommitRollback((ReplicationCommitMessage) packet);
      } else if (type == PacketImpl.REPLICATION_PAGE_WRITE) {
        handlePageWrite((ReplicationPageWriteMessage) packet);
      } else if (type == PacketImpl.REPLICATION_PAGE_EVENT) {
        handlePageEvent((ReplicationPageEventMessage) packet);
      } else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_BEGIN) {
        handleLargeMessageBegin((ReplicationLargeMessageBeginMessage) packet);
      } else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_WRITE) {
        handleLargeMessageWrite((ReplicationLargeMessageWriteMessage) packet);
      } else if (type == PacketImpl.REPLICATION_LARGE_MESSAGE_END) {
        handleLargeMessageEnd((ReplicationLargeMessageEndMessage) packet);
      } else if (type == PacketImpl.REPLICATION_START_FINISH_SYNC) {
        response = handleStartReplicationSynchronization((ReplicationStartSyncMessage) packet);
      } else if (type == PacketImpl.REPLICATION_SYNC_FILE) {
        handleReplicationSynchronization((ReplicationSyncFileMessage) packet);
      } else if (type == PacketImpl.REPLICATION_SCHEDULED_FAILOVER) {
        handleLiveStopping((ReplicationLiveIsStoppingMessage) packet);
      } else if (type == PacketImpl.BACKUP_REGISTRATION_FAILED) {
        handleFatalError((BackupReplicationStartFailedMessage) packet);
      } else {
        ActiveMQServerLogger.LOGGER.invalidPacketForReplication(packet);
      }
    } catch (ActiveMQException e) {
      ActiveMQServerLogger.LOGGER.errorHandlingReplicationPacket(e, packet);
      response = new ActiveMQExceptionMessage(e);
    } catch (Exception e) {
      ActiveMQServerLogger.LOGGER.errorHandlingReplicationPacket(e, packet);
      response =
          new ActiveMQExceptionMessage(ActiveMQMessageBundle.BUNDLE.replicationUnhandledError(e));
    }
    channel.send(response);
  }
 @Override
 public void handleNoMessageReferences(Map<Long, ServerMessage> messages) {
   for (ServerMessage msg : messages.values()) {
     if (msg.getRefCount() == 0) {
       ActiveMQServerLogger.LOGGER.journalUnreferencedMessage(msg.getMessageID());
       try {
         storageManager.deleteMessage(msg.getMessageID());
       } catch (Exception ignored) {
         ActiveMQServerLogger.LOGGER.journalErrorDeletingMessage(ignored, msg.getMessageID());
       }
     }
   }
 }
  @Override
  public boolean validateUserAndRole(
      final String user,
      final String password,
      final Set<Role> roles,
      final CheckType checkType,
      final String address,
      final RemotingConnection connection) {
    X509Certificate[] certificates = null;
    if (connection.getTransportConnection() instanceof NettyConnection) {
      certificates =
          CertificateUtil.getCertsFromChannel(
              ((NettyConnection) connection.getTransportConnection()).getChannel());
    }
    Subject localSubject;
    try {
      localSubject = getAuthenticatedSubject(user, password, certificates);
    } catch (LoginException e) {
      ActiveMQServerLogger.LOGGER.debug("Couldn't validate user", e);
      return false;
    }

    boolean authorized = false;

    if (localSubject != null) {
      Set<RolePrincipal> rolesWithPermission = getPrincipalsInRole(checkType, roles);

      // Check the caller's roles
      Set<RolePrincipal> rolesForSubject = localSubject.getPrincipals(RolePrincipal.class);
      if (rolesForSubject.size() > 0 && rolesWithPermission.size() > 0) {
        Iterator<RolePrincipal> rolesForSubjectIter = rolesForSubject.iterator();
        while (!authorized && rolesForSubjectIter.hasNext()) {
          Iterator<RolePrincipal> rolesWithPermissionIter = rolesWithPermission.iterator();
          while (!authorized && rolesWithPermissionIter.hasNext()) {
            Principal role = rolesWithPermissionIter.next();
            authorized = rolesForSubjectIter.next().equals(role);
          }
        }
      }

      if (trace) {
        ActiveMQServerLogger.LOGGER.trace(
            "user " + (authorized ? " is " : " is NOT ") + "authorized");
      }
    }

    return authorized;
  }
 /**
  * @param packet
  * @throws Exception
  */
 private void handleAppendAddRecord(final ReplicationAddMessage packet) throws Exception {
   Journal journalToUse = getJournal(packet.getJournalID());
   if (packet.getRecord() == ADD_OPERATION_TYPE.UPDATE) {
     if (ReplicationEndpoint.trace) {
       ActiveMQServerLogger.LOGGER.trace("Endpoint appendUpdate id = " + packet.getId());
     }
     journalToUse.appendUpdateRecord(
         packet.getId(), packet.getJournalRecordType(), packet.getRecordData(), noSync);
   } else {
     if (ReplicationEndpoint.trace) {
       ActiveMQServerLogger.LOGGER.trace("Endpoint append id = " + packet.getId());
     }
     journalToUse.appendAddRecord(
         packet.getId(), packet.getJournalRecordType(), packet.getRecordData(), noSync);
   }
 }
  private void finishSynchronization(String liveID) throws Exception {
    for (JournalContent jc : EnumSet.allOf(JournalContent.class)) {
      Journal journal = journalsHolder.remove(jc);
      journal.synchronizationLock();
      try {
        // files should be already in place.
        filesReservedForSync.remove(jc);
        registerJournal(jc.typeByte, journal);
        journal.stop();
        journal.start();
        journal.loadSyncOnly(JournalState.SYNCING_UP_TO_DATE);
      } finally {
        journal.synchronizationUnlock();
      }
    }
    ByteBuffer buffer = ByteBuffer.allocate(4 * 1024);
    for (Entry<Long, ReplicatedLargeMessage> entry : largeMessages.entrySet()) {
      ReplicatedLargeMessage lm = entry.getValue();
      if (lm instanceof LargeServerMessageInSync) {
        LargeServerMessageInSync lmSync = (LargeServerMessageInSync) lm;
        lmSync.joinSyncedData(buffer);
      }
    }

    journalsHolder = null;
    backupQuorum.liveIDSet(liveID);
    activation.setRemoteBackupUpToDate();
    ActiveMQServerLogger.LOGGER.backupServerSynched(server);
    return;
  }
예제 #11
0
  @Override
  public synchronized void addHead(final MessageReference ref) {
    SimpleString prop = ref.getMessage().getSimpleStringProperty(Message.HDR_LAST_VALUE_NAME);

    if (prop != null) {
      HolderReference hr = map.get(prop);

      if (hr != null) {
        // We keep the current ref and ack the one we are returning

        super.referenceHandled();

        try {
          super.acknowledge(ref);
        } catch (Exception e) {
          ActiveMQServerLogger.LOGGER.errorAckingOldReference(e);
        }
      } else {
        map.put(prop, (HolderReference) ref);

        super.addHead(ref);
      }
    } else {
      super.addHead(ref);
    }
  }
예제 #12
0
 protected void close(DirContext context) {
   try {
     context.close();
   } catch (Exception e) {
     ActiveMQServerLogger.LOGGER.error(e.toString());
   }
 }
예제 #13
0
  @Override
  public void stop() throws Exception {
    if (stopping) {
      return;
    }

    stopping = true;

    if (logger.isDebugEnabled()) {
      logger.debug("Bridge " + this.name + " being stopped");
    }

    if (futureScheduledReconnection != null) {
      futureScheduledReconnection.cancel(true);
    }

    executor.execute(new StopRunnable());

    if (notificationService != null) {
      TypedProperties props = new TypedProperties();
      props.putSimpleStringProperty(new SimpleString("name"), name);
      Notification notification =
          new Notification(nodeUUID.toString(), CoreNotificationType.BRIDGE_STOPPED, props);
      try {
        notificationService.sendNotification(notification);
      } catch (Exception e) {
        ActiveMQServerLogger.LOGGER.broadcastBridgeStoppedError(e);
      }
    }
  }
예제 #14
0
  protected DirContext open() throws NamingException {
    try {
      Hashtable<String, String> env = new Hashtable<String, String>();
      env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
      if (isLoginPropertySet(CONNECTION_USERNAME)) {
        env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
      } else {
        throw new NamingException("Empty username is not allowed");
      }

      if (isLoginPropertySet(CONNECTION_PASSWORD)) {
        env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
      } else {
        throw new NamingException("Empty password is not allowed");
      }
      env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
      env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
      env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
      context = new InitialDirContext(env);

    } catch (NamingException e) {
      ActiveMQServerLogger.LOGGER.error(e.toString());
      throw e;
    }
    return context;
  }
  public void handleBuffer(final RemotingConnection connection, final ActiveMQBuffer buffer) {
    StompConnection conn = (StompConnection) connection;

    conn.setDataReceived();

    do {
      StompFrame request;
      try {
        request = conn.decode(buffer);
      } catch (Exception e) {
        ActiveMQServerLogger.LOGGER.errorDecodingPacket(e);
        return;
      }

      if (request == null) {
        break;
      }

      try {
        invokeInterceptors(this.incomingInterceptors, request, conn);
        conn.handleFrame(request);
      } finally {
        server.getStorageManager().clearContext();
      }
    } while (conn.hasBytes());
  }
예제 #16
0
  @Override
  public boolean checkMemory(final Runnable runWhenAvailable) {
    if (addressFullMessagePolicy == AddressFullMessagePolicy.BLOCK && maxSize != -1) {
      if (sizeInBytes.get() > maxSize) {
        OurRunnable ourRunnable = new OurRunnable(runWhenAvailable);

        onMemoryFreedRunnables.add(ourRunnable);

        // We check again to avoid a race condition where the size can come down just after the
        // element
        // has been added, but the check to execute was done before the element was added
        // NOTE! We do not fix this race by locking the whole thing, doing this check provides
        // MUCH better performance in a highly concurrent environment
        if (sizeInBytes.get() <= maxSize) {
          // run it now
          ourRunnable.run();
        } else if (!blocking.get()) {
          ActiveMQServerLogger.LOGGER.blockingMessageProduction(
              address, sizeInBytes.get(), maxSize);
          blocking.set(true);
        }

        return true;
      }
    } else if (addressFullMessagePolicy == AddressFullMessagePolicy.FAIL && maxSize != -1) {
      if (sizeInBytes.get() > maxSize) {
        return false;
      }
    }

    runWhenAvailable.run();

    return true;
  }
예제 #17
0
  @Override
  public synchronized void addTail(final MessageReference ref, final boolean direct) {
    SimpleString prop = ref.getMessage().getSimpleStringProperty(Message.HDR_LAST_VALUE_NAME);

    if (prop != null) {
      HolderReference hr = map.get(prop);

      if (hr != null) {
        // We need to overwrite the old ref with the new one and ack the old one

        MessageReference oldRef = hr.getReference();

        referenceHandled();

        try {
          oldRef.acknowledge();
        } catch (Exception e) {
          ActiveMQServerLogger.LOGGER.errorAckingOldReference(e);
        }

        hr.setReference(ref);

      } else {
        hr = new HolderReference(prop, ref);

        map.put(prop, hr);

        super.addTail(hr, direct);
      }
    } else {
      super.addTail(ref, direct);
    }
  }
예제 #18
0
  /**
   * @param ref
   * @param message
   * @return
   */
  private HandleStatus deliverStandardMessage(
      SimpleString dest, final MessageReference ref, ServerMessage message) {
    // if we failover during send then there is a chance that the
    // that this will throw a disconnect, we need to remove the message
    // from the acks so it will get resent, duplicate detection will cope
    // with any messages resent

    if (logger.isTraceEnabled()) {
      logger.trace("going to send message: " + message + " from " + this.getQueue());
    }

    try {
      producer.send(dest, message);
    } catch (final ActiveMQException e) {
      ActiveMQServerLogger.LOGGER.bridgeUnableToSendMessage(e, ref);

      synchronized (refs) {
        // We remove this reference as we are returning busy which means the reference will never
        // leave the Queue.
        // because of this we have to remove the reference here
        refs.remove(message.getMessageID());

        // The delivering count should also be decreased as to avoid inconsistencies
        ((QueueImpl) ref.getQueue()).decDelivering();
      }

      connectionFailed(e, false);

      return HandleStatus.BUSY;
    }

    return HandleStatus.HANDLED;
  }
    public NettyServerConnection createConnection(
        final ChannelHandlerContext ctx, String protocol, boolean httpEnabled) throws Exception {
      if (connectionsAllowed == -1 || connections.size() < connectionsAllowed) {
        super.channelActive(ctx);
        Listener connectionListener = new Listener();

        NettyServerConnection nc =
            new NettyServerConnection(
                configuration,
                ctx.channel(),
                connectionListener,
                !httpEnabled && batchDelay > 0,
                directDeliver);

        connectionListener.connectionCreated(NettyAcceptor.this, nc, protocol);

        SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
        if (sslHandler != null) {
          sslHandler
              .handshakeFuture()
              .addListener(
                  new GenericFutureListener<io.netty.util.concurrent.Future<Channel>>() {
                    public void operationComplete(
                        final io.netty.util.concurrent.Future<Channel> future) throws Exception {
                      if (future.isSuccess()) {
                        active = true;
                      } else {
                        future.getNow().close();
                      }
                    }
                  });
        } else {
          active = true;
        }
        return nc;
      } else {
        if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
          ActiveMQServerLogger.LOGGER.debug(
              new StringBuilder()
                  .append("Connection limit of ")
                  .append(connectionsAllowed)
                  .append(" reached. Refusing connection from ")
                  .append(ctx.channel().remoteAddress()));
        }
        throw new Exception();
      }
    }
  @Override
  public synchronized void stop() throws Exception {
    if (!started) {
      return;
    }

    // Channel may be null if there isn't a connection to a live server
    if (channel != null) {
      channel.close();
    }

    for (ReplicatedLargeMessage largeMessage : largeMessages.values()) {
      largeMessage.releaseResources();
    }
    largeMessages.clear();

    for (Entry<JournalContent, Map<Long, JournalSyncFile>> entry :
        filesReservedForSync.entrySet()) {
      for (JournalSyncFile filesReserved : entry.getValue().values()) {
        filesReserved.close();
      }
    }

    filesReservedForSync.clear();
    if (journals != null) {
      for (Journal j : journals) {
        if (j instanceof FileWrapperJournal) j.stop();
      }
    }

    for (ConcurrentMap<Integer, Page> map : pageIndex.values()) {
      for (Page page : map.values()) {
        try {
          page.sync();
          page.close();
        } catch (Exception e) {
          ActiveMQServerLogger.LOGGER.errorClosingPageOnReplication(e);
        }
      }
    }
    pageManager.stop();

    pageIndex.clear();
    final CountDownLatch latch = new CountDownLatch(1);
    executor.execute(
        new Runnable() {

          @Override
          public void run() {
            latch.countDown();
          }
        });
    latch.await(30, TimeUnit.SECONDS);

    // Storage needs to be the last to stop
    storageManager.stop();

    started = false;
  }
  public void write(
      final ActiveMQBuffer buffer,
      final boolean flush,
      final boolean batch,
      final ChannelFutureListener futureListener) {
    final ActiveMQBuffer copied = buffer.copy(0, buffer.capacity());

    copied.setIndex(buffer.readerIndex(), buffer.writerIndex());

    try {
      executor.execute(
          new Runnable() {
            public void run() {
              try {
                if (!closed) {
                  copied.readInt(); // read and discard
                  if (isTrace) {
                    ActiveMQServerLogger.LOGGER.trace(
                        InVMConnection.this + "::Sending inVM packet");
                  }
                  handler.bufferReceived(id, copied);
                  if (futureListener != null) {
                    // TODO BEFORE MERGE: (is null a good option here?)
                    futureListener.operationComplete(null);
                  }
                }
              } catch (Exception e) {
                final String msg = "Failed to write to handler on connector " + this;
                ActiveMQServerLogger.LOGGER.errorWritingToInvmConnector(e, this);
                throw new IllegalStateException(msg, e);
              } finally {
                if (isTrace) {
                  ActiveMQServerLogger.LOGGER.trace(InVMConnection.this + "::packet sent done");
                }
              }
            }
          });

      if (flush && flushEnabled) {
        final CountDownLatch latch = new CountDownLatch(1);
        executor.execute(
            new Runnable() {
              public void run() {
                latch.countDown();
              }
            });

        try {
          if (!latch.await(10, TimeUnit.SECONDS)) {
            ActiveMQServerLogger.LOGGER.timedOutFlushingInvmChannel();
          }
        } catch (InterruptedException e) {
          throw new ActiveMQInterruptedException(e);
        }
      }
    } catch (RejectedExecutionException e) {
      // Ignore - this can happen if server/client is shutdown and another request comes in
    }
  }
  @Override
  public List<PagingStore> reloadStores(
      final HierarchicalRepository<AddressSettings> addressSettingsRepository) throws Exception {
    File[] files = directory.listFiles();

    if (files == null) {
      return Collections.<PagingStore>emptyList();
    } else {
      ArrayList<PagingStore> storesReturn = new ArrayList<>(files.length);

      for (File file : files) {

        final String guid = file.getName();

        final File addressFile = new File(file, PagingStoreFactoryNIO.ADDRESS_FILE);

        if (!addressFile.exists()) {
          ActiveMQServerLogger.LOGGER.pageStoreFactoryNoIdFile(
              file.toString(), PagingStoreFactoryNIO.ADDRESS_FILE);
          continue;
        }

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(new FileInputStream(addressFile)));

        String addressString;

        try {
          addressString = reader.readLine();
        } finally {
          reader.close();
        }

        SimpleString address = new SimpleString(addressString);

        SequentialFileFactory factory = newFileFactory(guid);

        AddressSettings settings = addressSettingsRepository.getMatch(address.toString());

        PagingStore store =
            new PagingStoreImpl(
                address,
                scheduledExecutor,
                syncTimeout,
                pagingManager,
                storageManager,
                factory,
                this,
                address,
                settings,
                executorFactory.getExecutor(),
                syncNonTransactional);

        storesReturn.add(store);
      }

      return storesReturn;
    }
  }
  private void handleReattachSession(final ReattachSessionMessage request) {
    Packet response = null;

    try {

      if (!server.isStarted()) {
        response = new ReattachSessionResponseMessage(-1, false);
      }

      logger.debug("Reattaching request from " + connection.getRemoteAddress());

      ServerSessionPacketHandler sessionHandler =
          protocolManager.getSessionHandler(request.getName());

      // HORNETQ-720 XXX ataylor?
      if (
      /*!server.checkActivate() || */ sessionHandler == null) {
        response = new ReattachSessionResponseMessage(-1, false);
      } else {
        if (sessionHandler.getChannel().getConfirmationWindowSize() == -1) {
          // Even though session exists, we can't reattach since confi window size == -1,
          // i.e. we don't have a resend cache for commands, so we just close the old session
          // and let the client recreate

          ActiveMQServerLogger.LOGGER.reattachRequestFailed(connection.getRemoteAddress());

          sessionHandler.closeListeners();
          sessionHandler.close();

          response = new ReattachSessionResponseMessage(-1, false);
        } else {
          // Reconnect the channel to the new connection
          int serverLastConfirmedCommandID =
              sessionHandler.transferConnection(connection, request.getLastConfirmedCommandID());

          response = new ReattachSessionResponseMessage(serverLastConfirmedCommandID, true);
        }
      }
    } catch (Exception e) {
      ActiveMQServerLogger.LOGGER.failedToReattachSession(e);

      response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException());
    }

    channel1.send(response);
  }
  /**
   * Reserves files (with the given fileID) in the specified journal, and places a {@link
   * FileWrapperJournal} in place to store messages while synchronization is going on.
   *
   * @param packet
   * @throws Exception
   * @return if the incoming packet indicates the synchronization is finished then return an
   *     acknowledgement otherwise return an empty response
   */
  private ReplicationResponseMessageV2 handleStartReplicationSynchronization(
      final ReplicationStartSyncMessage packet) throws Exception {
    ReplicationResponseMessageV2 replicationResponseMessage = new ReplicationResponseMessageV2();
    if (activation.isRemoteBackupUpToDate()) {
      throw ActiveMQMessageBundle.BUNDLE.replicationBackupUpToDate();
    }

    synchronized (this) {
      if (!started) return replicationResponseMessage;

      if (packet.isSynchronizationFinished()) {
        finishSynchronization(packet.getNodeID());
        replicationResponseMessage.setSynchronizationIsFinishedAcknowledgement(true);
        return replicationResponseMessage;
      }

      switch (packet.getDataType()) {
        case LargeMessages:
          for (long msgID : packet.getFileIds()) {
            createLargeMessage(msgID, true);
          }
          break;
        case JournalBindings:
        case JournalMessages:
          if (wantedFailBack && !packet.isServerToFailBack()) {
            ActiveMQServerLogger.LOGGER.autoFailBackDenied();
          }

          final JournalContent journalContent =
              SyncDataType.getJournalContentType(packet.getDataType());
          final Journal journal = journalsHolder.get(journalContent);

          if (packet.getNodeID() != null) {
            // At the start of replication, we still do not know which is the nodeID that the live
            // uses.
            // This is the point where the backup gets this information.
            backupQuorum.liveIDSet(packet.getNodeID());
          }
          Map<Long, JournalSyncFile> mapToFill = filesReservedForSync.get(journalContent);

          for (Entry<Long, JournalFile> entry :
              journal.createFilesForBackupSync(packet.getFileIds()).entrySet()) {
            mapToFill.put(entry.getKey(), new JournalSyncFile(entry.getValue()));
          }
          FileWrapperJournal syncJournal = new FileWrapperJournal(journal);
          registerJournal(journalContent.typeByte, syncJournal);
          break;
        default:
          throw ActiveMQMessageBundle.BUNDLE.replicationUnhandledDataType();
      }
    }

    return replicationResponseMessage;
  }
  @Override
  public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID)
      throws Exception {
    Queue queue = queues.get(queueID);

    if (queue == null) {
      ActiveMQServerLogger.LOGGER.journalMessageInPreparedTX(queueID);
      return;
    }
    postOffice.reroute(message, queue, tx);
  }
 @Override
 public boolean validateUser(
     final String user, final String password, X509Certificate[] certificates) {
   try {
     getAuthenticatedSubject(user, password, certificates);
     return true;
   } catch (LoginException e) {
     ActiveMQServerLogger.LOGGER.debug("Couldn't validate user", e);
     return false;
   }
 }
 private void handleCreateQueue(final CreateQueueMessage request) {
   try {
     server.createQueue(
         request.getAddress(),
         request.getQueueName(),
         request.getFilterString(),
         request.isDurable(),
         request.isTemporary());
   } catch (Exception e) {
     ActiveMQServerLogger.LOGGER.failedToHandleCreateQueue(e);
   }
 }
예제 #28
0
  @Override
  public void flushExecutors() {
    cursorProvider.flushExecutors();

    FutureLatch future = new FutureLatch();

    executor.execute(future);

    if (!future.await(60000)) {
      ActiveMQServerLogger.LOGGER.pageStoreTimeout(address);
    }
  }
  public boolean send(final StompConnection connection, final StompFrame frame) {
    if (ActiveMQServerLogger.LOGGER.isTraceEnabled()) {
      ActiveMQServerLogger.LOGGER.trace("sent " + frame);
    }

    invokeInterceptors(this.outgoingInterceptors, frame, connection);

    synchronized (connection) {
      if (connection.isDestroyed()) {
        ActiveMQStompProtocolLogger.LOGGER.connectionClosed(connection);
        return false;
      }

      try {
        connection.physicalSend(frame);
      } catch (Exception e) {
        ActiveMQStompProtocolLogger.LOGGER.errorSendingFrame(e, frame);
        return false;
      }
      return true;
    }
  }
예제 #30
0
  @Override
  public void flushExecutor() {
    // Wait for any create objects runnable to complete
    FutureLatch future = new FutureLatch();

    executor.execute(future);

    boolean ok = future.await(10000);

    if (!ok) {
      ActiveMQServerLogger.LOGGER.timedOutWaitingToStopBridge();
    }
  }