com.rabbitmq.client.ShutdownSignalException Java Examples

The following examples show how to use com.rabbitmq.client.ShutdownSignalException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RabbitMetricsBinder.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void newChannel(final Channel channel) {
    try {
        channels.incrementAndGet();
        channel.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                closeChannel(channel);
            }
        });
        connectionState(channel.getConnection()).channelState.put(channel.getChannelNumber(),
            new RabbitMetricsBinder.ChannelState(channel));
    } catch (Exception e) {
        LOGGER.info("Error while computing metrics in newChannel: " + e.getMessage());
    }
}
 
Example #2
Source File: RabbitMqIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test(timeout = ONE_MINUTE_MS)
public void testDeclareIncompatibleExchangeFails() throws Exception {
  RabbitMqIO.Read read =
      RabbitMqIO.read().withExchange("IncompatibleExchange", "direct", "unused");
  try {
    doExchangeTest(new ExchangeTestPlan(read, 1), true);
    fail("Expected to have failed to declare an incompatible exchange");
  } catch (Exception e) {
    Throwable cause = Throwables.getRootCause(e);
    if (cause instanceof ShutdownSignalException) {
      ShutdownSignalException sse = (ShutdownSignalException) cause;
      Method reason = sse.getReason();
      if (reason instanceof com.rabbitmq.client.AMQP.Connection.Close) {
        com.rabbitmq.client.AMQP.Connection.Close close =
            (com.rabbitmq.client.AMQP.Connection.Close) reason;
        assertEquals("Expected failure is 530: not-allowed", 530, close.getReplyCode());
      } else {
        fail(
            "Unexpected ShutdownSignalException reason. Expected Connection.Close. Got: "
                + reason);
      }
    } else {
      fail("Expected to fail with ShutdownSignalException. Instead failed with " + cause);
    }
  }
}
 
Example #3
Source File: ChannelHandler.java    From lyra with Apache License 2.0 6 votes vote down vote up
@Override
public void shutdownCompleted(ShutdownSignalException e) {
  channelShutdown();
  if (!e.isInitiatedByApplication()) {
    log.error("Channel {} was closed unexpectedly", ChannelHandler.this);
    lastShutdownSignal = e;
    if (!Exceptions.isConnectionClosure(e) && canRecover())
      ConnectionHandler.RECOVERY_EXECUTORS.execute(new Runnable() {
        @Override
        public void run() {
          try {
            recoveryPending.set(true);
            recoverChannel(false);
          } catch (Throwable ignore) {
          }
        }
      });
  }
}
 
Example #4
Source File: AbstractFunctionalTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an answer that fails n times for each thread, throwing t for the first n invocations
 * and returning {@code returnValue} thereafter. Prior to throwing t, the connection handler's
 * shutdown listener is completed if t is a connection shutdown signal.
 */
protected <T> Answer<T> failNTimes(final int n, final Throwable t, final T returnValue,
    final RetryableResource resource) {
  return new Answer<T>() {
    AtomicInteger failures = new AtomicInteger();

    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
      if (failures.getAndIncrement() >= n)
        return returnValue;

      if (t instanceof ShutdownSignalException)
        callShutdownListener(resource, (ShutdownSignalException) t);
      if (t instanceof ShutdownSignalException && !(t instanceof AlreadyClosedException))
        throw new IOException(t);
      else
        throw t;
    }
  };
}
 
Example #5
Source File: RabbitMQClientActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void handleShutdownSignal(final String consumerTag, final ShutdownSignalException sig) {
    super.handleShutdownSignal(consumerTag, sig);
    ConnectionLogUtil.enhanceLogWithConnectionId(log, connectionId());

    final String consumingQueueByTag = consumedTagsToAddresses.get(consumerTag);
    if (null != consumingQueueByTag) {
        connectionLogger.failure(
                "Consumer with queue <{}> shutdown as the channel or the underlying connection has " +
                        "been shut down.", consumingQueueByTag);
        log.warning("Consumer with queue <{}> shutdown as the channel or the underlying connection has " +
                "been shut down on connection <{}>.", consumingQueueByTag, connectionId());
    }

    updateSourceStatus(ConnectivityStatus.FAILED,
            "Channel or the underlying connection has been shut down at " + Instant.now());
}
 
Example #6
Source File: RabbitMqReceiver.java    From tangyuan2 with GNU General Public License v3.0 6 votes vote down vote up
private void startSyncReceiveThread(final QueueingConsumer consumer, final boolean autoAck, final BindingVo binding) {
	syncReceiveThread = new SyncReceiveThread() {
		@Override
		public void run() {
			log.info("start listen to the " + typeStr + "[" + queue.getName() + "].");
			while (running) {
				try {
					QueueingConsumer.Delivery delivery = consumer.nextDelivery();
					XCO xcoMessage = getMessage(delivery.getBody());
					log.info("received a message from " + typeStr + "[" + queue.getName() + "]: " + xcoMessage);
					boolean result = exec(service, xcoMessage, binding);
					if (!autoAck && result) {
						channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
					}
				} catch (ShutdownSignalException e) {
					// TODO 可能会出现断链的问题
					e.printStackTrace();
				} catch (Throwable e) {
					log.error("listen to the [" + queue.getName() + "] error.", e);
				}
			}
			closed = true;
		}
	};
	syncReceiveThread.start();
}
 
Example #7
Source File: ConnectionClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeConnectionAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        connectionProxy.createChannel();
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception actual) {
        if (!actual.equals(e))
          actual.printStackTrace();
        waiter.assertEquals(actual, e);
        waiter.resume();
      }
    }
  });

  waiter.await(10000);
}
 
Example #8
Source File: RabbitMQEventBus.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public void shutdownCompleted(ShutdownSignalException shutdownSignalException) {
    if (!shutdownSignalException.isInitiatedByApplication()) {

        for (String subscriberId : s_subscribers.keySet()) {
            Ternary<String, Channel, EventSubscriber> subscriberDetails = s_subscribers.get(subscriberId);
            subscriberDetails.second(null);
            s_subscribers.put(subscriberId, subscriberDetails);
        }

        abortConnection(); // disconnected to AMQP server, so abort the connection and channels
        s_logger.warn("Connection has been shutdown by AMQP server. Attempting to reconnect.");

        // initiate re-connect process
        ReconnectionTask reconnect = new ReconnectionTask();
        executorService.submit(reconnect);
    }
}
 
Example #9
Source File: ChannelClosureTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
private void performInvocation(final ShutdownSignalException e, final Waiter waiter)
    throws Throwable {
  mockConnection();
  mockInvocation(e);
  closeChannelAfterDelay();

  runInThread(new Runnable() {
    public void run() {
      try {
        mockChannel(1).proxy.basicCancel("foo-tag");
        waiter.fail("Invocation should have thrown an exception");
      } catch (Exception expected) {
        waiter.assertEquals(e, expected);
        waiter.resume();
      }
    }
  });

  waiter.await(100000);
}
 
Example #10
Source File: AbstractInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
void performInvocation(ShutdownSignalException invocationFailure, Exception recoveryFailure)
    throws Throwable {
  mockConnection();
  mockInvocation(invocationFailure);
  if (recoveryFailure != null)
    mockRecovery(recoveryFailure);

  final Waiter waiter = new Waiter();
  runInThread(new Runnable() {
    public void run() {
      try {
        performInvocation();
        waiter.resume();
      } catch (Throwable t) {
        waiter.fail(t);
      }
    }
  });

  waiter.await(1000);
}
 
Example #11
Source File: AbstractInvocationTest.java    From lyra with Apache License 2.0 6 votes vote down vote up
void performThrowableInvocation(ShutdownSignalException invocationFailure,
    Exception recoveryFailure) throws Throwable {
  mockConnection();
  mockInvocation(invocationFailure);
  if (recoveryFailure != null)
    mockRecovery(recoveryFailure);

  try {
    performInvocation();
    fail("Invocation should have thrown an exception");
  } catch (IOException expected) {
    assertEquals(invocationFailure, expected.getCause());
  }

  Thread.sleep(100);
}
 
Example #12
Source File: ChannelTest.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
@Test
void exchangeDeclare_twice_with_a_different_type_throws() throws IOException, TimeoutException {
    try (Connection conn = new MockConnectionFactory().newConnection()) {
        try (Channel channel = conn.createChannel()) {
            String exchangeName = "test1";
            channel.exchangeDeclare(exchangeName, "fanout");
            String queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, exchangeName, "unused");

            assertThatExceptionOfType(IOException.class)
                .isThrownBy(() -> channel.exchangeDeclare(exchangeName, "topic"))
                .withCauseInstanceOf(ShutdownSignalException.class)
                .withMessageContaining("channel error; protocol method: #method<channel.close>" +
                    "(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'type' " +
                    "for exchange 'test1' in vhost '/' received 'topic' but current is 'fanout', class-id=40, method-id=10)");
        }
    }
}
 
Example #13
Source File: RabbitMetricsBinder.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void newConnection(final Connection connection) {
    try {
        if (connection.getId() == null) {
            connection.setId(UUID.randomUUID().toString());
        }
        connections.incrementAndGet();
        connectionState.put(connection.getId(), new RabbitMetricsBinder.ConnectionState(connection));
        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                closeConnection(connection);
            }
        });
    } catch (Exception e) {
        LOGGER.info("Error while computing metrics in newConnection: " + e.getMessage());
    }
}
 
Example #14
Source File: AmqpExceptions.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
public static IOException inequivalentExchangeRedeclare(Channel ref,
                                                        String vhost,
                                                        String exchangeName,
                                                        String currentType,
                                                        String receivedType) {
    StringBuilder replyText = new StringBuilder("PRECONDITION_FAILED - inequivalent arg 'type' ")
        .append("for exchange '").append(exchangeName).append("' ")
        .append("in vhost '").append(vhost).append("' ")
        .append("received '").append(receivedType).append("' ")
        .append("but current is '").append(currentType).append("'");

    AMQImpl.Channel.Close reason = new AMQImpl.Channel.Close(
        406,
        replyText.toString(),
        AMQImpl.Exchange.INDEX,
        AMQImpl.Exchange.Declare.INDEX);
    ShutdownSignalException sse = new ShutdownSignalException(
        false,
        false,
        reason,
        ref);
    return new IOException(sse.sensibleClone());
}
 
Example #15
Source File: AmqpExceptions.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
public static IOException exchangeNotFound(Channel ref,
                                           String vhost,
                                           String exchangeName) {
    StringBuilder replyText = new StringBuilder("NOT_FOUND - no exchange '").append(exchangeName).append("' ")
        .append("in vhost '").append(vhost).append("'");

    ShutdownSignalException reason = new ShutdownSignalException(
        false,
        false,
        new AMQImpl.Channel.Close(
            404,
            replyText.toString(),
            AMQImpl.Exchange.INDEX,
            AMQImpl.Exchange.Declare.INDEX),
        ref);
    return new IOException(reason.sensibleClone());
}
 
Example #16
Source File: AmqpExceptions.java    From rabbitmq-mock with Apache License 2.0 6 votes vote down vote up
public static IOException queueNotFound(Channel ref,
                                           String vhost,
                                           String queueName) {
    StringBuilder replyText = new StringBuilder("NOT_FOUND - no queue '").append(queueName).append("' ")
        .append("in vhost '").append(vhost).append("'");

    ShutdownSignalException reason = new ShutdownSignalException(
        false,
        false,
        new AMQImpl.Channel.Close(
            404,
            replyText.toString(),
            AMQImpl.Queue.INDEX,
            AMQImpl.Queue.Declare.INDEX),
        ref);
    return new IOException(reason.sensibleClone());
}
 
Example #17
Source File: ConnectionShutdownListener.java    From rabbitmq-cdi with MIT License 6 votes vote down vote up
@Override
public void shutdownCompleted(ShutdownSignalException cause) {
  LOGGER.debug("connection shutdown detected", cause);
  // Only hard error means loss of connection
  if (unrecoverableErrorDetector.isUnrecoverableError(cause)) {
    try {
      connectionManagerLock.lock();
      // No action to be taken if factory is already closed
      // or already connecting
      if (connectionManager.getState() == ConnectionState.CLOSED
          || connectionManager.getState() == ConnectionState.CONNECTING) {
        return;
      }
      connectionManager.changeState(ConnectionState.CONNECTING);
      LOGGER.error("Connection lost by unrecoverable error reconnecting");
    } finally {
      connectionManagerLock.unlock();
    }
  }
}
 
Example #18
Source File: RabbitMQConsumer.java    From storm-rabbitmq with MIT License 6 votes vote down vote up
public Message nextMessage() {
  reinitIfNecessary();
  if (consumerTag == null || consumer == null) return Message.NONE;
  try {
    return Message.forDelivery(consumer.nextDelivery(MS_WAIT_FOR_MESSAGE));
  } catch (ShutdownSignalException sse) {
    reset();
    logger.error("shutdown signal received while attempting to get next message", sse);
    reporter.reportError(sse);
    return Message.NONE;
  } catch (InterruptedException ie) {
    /* nothing to do. timed out waiting for message */
    logger.debug("interruepted while waiting for message", ie);
    return Message.NONE;
  } catch (ConsumerCancelledException cce) {
    /* if the queue on the broker was deleted or node in the cluster containing the queue failed */
    reset();
    logger.error("consumer got cancelled while attempting to get next message", cce);
    reporter.reportError(cce);
    return Message.NONE;
  }
}
 
Example #19
Source File: RabbitMQConsumer.java    From storm-rabbitmq with MIT License 5 votes vote down vote up
private Connection createConnection() throws IOException, TimeoutException {
  Connection connection = highAvailabilityHosts == null || highAvailabilityHosts.length == 0 
        ? connectionFactory.newConnection() 
        : connectionFactory.newConnection(highAvailabilityHosts);
  connection.addShutdownListener(new ShutdownListener() {
    @Override
    public void shutdownCompleted(ShutdownSignalException cause) {
      logger.error("shutdown signal received", cause);
      reporter.reportError(cause);
      reset();
    }
  });
  logger.info("connected to rabbitmq: " + connection + " for " + queueName);
  return connection;
}
 
Example #20
Source File: MQServer.java    From zxl with Apache License 2.0 5 votes vote down vote up
protected void handleReceiveError(Exception warnException, RabbitAdmin mqAdmin) {
	Throwable throwable = warnException;
	while ((throwable = throwable.getCause()) != null) {
		if (throwable instanceof ShutdownSignalException && throwable.getMessage().contains(NOT_FOUND_MESSAGE)) {
			try {
				mqAdmin.declareQueue(new Queue(queueName, queueDurable, queueExclusive, queueAutoDelete, queueArguments));
				mqAdmin.declareBinding(new Binding(queueName, DestinationType.QUEUE, MQClient.DEFAULT_EXCHANGE, queueName, bindingArguments));
			} catch (Exception e) {
			}
			break;
		}
	}
}
 
Example #21
Source File: RoboconfConsumer.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void handleShutdownSignal( String consumerTag, ShutdownSignalException sig ) {

	if( sig.isInitiatedByApplication()) {
		this.logger.fine( this.sourceName + ": the connection to the messaging server was shut down." + id( consumerTag ));

	} else if( sig.getReference() instanceof Channel ) {
		int nb = ((Channel) sig.getReference()).getChannelNumber();
		this.logger.fine( "A RabbitMQ consumer was shut down. Channel #" + nb + ", " + id( consumerTag ));

	} else {
		this.logger.fine( "A RabbitMQ consumer was shut down." + id( consumerTag ));
	}
}
 
Example #22
Source File: AmqpForwardAttributeTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void serviceShouldNotFailWhenAlreadyClosedException() throws Exception {
    mailet.init(mailetConfig);
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    ShutdownSignalException shutdownSignalException = new ShutdownSignalException(false, false, new Close.Builder().build(), "reference");
    when(connectionFactory.newConnection()).thenThrow(new AlreadyClosedException(shutdownSignalException));
    mailet.setConnectionFactory(connectionFactory);

    mailet.service(mail);
}
 
Example #23
Source File: Exceptions.java    From lyra with Apache License 2.0 5 votes vote down vote up
public static boolean isRetryable(Set<Class<? extends Exception>> retryableExceptions,
    Exception e, ShutdownSignalException sse) {
  for (Class<? extends Exception> retryable : retryableExceptions)
    if (retryable.isAssignableFrom(e.getClass()))
      return true;
  if (retryableExceptions.contains(e) || e.getCause() instanceof EOFException)
    return true;
  if (e instanceof PossibleAuthenticationFailureException)
    return false;
  return sse != null && isRetryable(sse);
}
 
Example #24
Source File: RabbitMQConsumer.java    From storm-rabbitmq with MIT License 5 votes vote down vote up
public void ack(Long msgId) {
  reinitIfNecessary();
  try {
    channel.basicAck(msgId, false);
  } catch (ShutdownSignalException sse) {
    reset();
    logger.error("shutdown signal received while attempting to ack message", sse);
    reporter.reportError(sse);
  } catch (Exception e) {
    logger.error("could not ack for msgId: " + msgId, e);
    reporter.reportError(e);
  }
}
 
Example #25
Source File: RabbitMQConsumer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Called when either the channel or the underlying connection has been shut down.
 *
 * @param consumerTag the consumer tag associated with the consumer
 * @param signal      a {@link ShutdownSignalException} indicating the reason for the shut down
 */
@Override
public void handleShutdownSignal(String consumerTag, ShutdownSignalException signal) {
    if (signal.isInitiatedByApplication()) {
        log.info("The connection to the messaging server was shut down. Consumer tag: " + consumerTag);

    } else if (signal.getReference() instanceof Channel) {
        int channelNumber = ((Channel) signal.getReference()).getChannelNumber();
        log.info("The consumer on channel number: " + channelNumber + " with consumer tag: " + consumerTag
                + " was shut down.");

    } else {
        log.info("The consumer with consumer tag: " + consumerTag + " was shut down.");
    }
}
 
Example #26
Source File: RabbitMQConsumer.java    From storm-rabbitmq with MIT License 5 votes vote down vote up
public void deadLetter(Long msgId) {
  reinitIfNecessary();
  try {
    channel.basicReject(msgId, false);
  } catch (ShutdownSignalException sse) {
    reset();
    logger.error("shutdown signal received while attempting to fail with no redelivery", sse);
    reporter.reportError(sse);
  } catch (Exception e) {
    logger.error("could not fail with dead-lettering (when configured) for msgId: " + msgId, e);
    reporter.reportError(e);
  }
}
 
Example #27
Source File: RabbitMQConsumer.java    From storm-rabbitmq with MIT License 5 votes vote down vote up
public void failWithRedelivery(Long msgId) {
  reinitIfNecessary();
  try {
    channel.basicReject(msgId, true);
  } catch (ShutdownSignalException sse) {
    reset();
    logger.error("shutdown signal received while attempting to fail with redelivery", sse);
    reporter.reportError(sse);
  } catch (Exception e) {
    logger.error("could not fail with redelivery for msgId: " + msgId, e);
    reporter.reportError(e);
  }
}
 
Example #28
Source File: Exceptions.java    From lyra with Apache License 2.0 5 votes vote down vote up
private static boolean isRetryable(ShutdownSignalException e) {
  if (e.isInitiatedByApplication())
    return false;
  Method method = e.getReason();
  if (method instanceof AMQP.Connection.Close)
    return isRetryable(((AMQP.Connection.Close) method).getReplyCode());
  if (method instanceof AMQP.Channel.Close)
    return isRetryable(((AMQP.Channel.Close) method).getReplyCode());
  return false;
}
 
Example #29
Source File: ChannelRecoveryTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that a failure from a channel listener during recovery results in the channel being
 * recovered.
 */
public void shouldHandleRecoveryFailureFromChannelListener() throws Throwable {
  final AtomicBoolean shutdownCalled = new AtomicBoolean();
  config = new Config().withRetryPolicy(
      RetryPolicies.retryAlways().withInterval(Duration.millis(10)))
      .withRecoveryPolicy(RecoveryPolicies.recoverAlways())
      .withChannelListeners(new DefaultChannelListener() {
        @Override
        public void onRecovery(Channel channel) {
          if (!shutdownCalled.get() && channel == mockChannel(2).proxy) {
            ShutdownSignalException e = nonRetryableChannelShutdownSignal();
            shutdownCalled.set(true);
            callShutdownListener(mockChannel(2).channelHandler, e);
            throw e;
          }
        }
      });

  performRecovery(mockChannel(2).channelHandler, mockChannel(2).channelHandler, 0, 0);
  verifyCxnCreations(1);
  verifyChannelCreations(1, 1);
  verifyConsumerCreations(1, 1, 1);
  verifyConsumerCreations(1, 2, 1);

  verifyChannelCreations(2, 3);
  verifyConsumerCreations(2, 5, 2); // Only attempted once since first attempt fails
  verifyConsumerCreations(2, 6, 2);
}
 
Example #30
Source File: AbstractFunctionalTest.java    From lyra with Apache License 2.0 5 votes vote down vote up
protected void callShutdownListener(RetryableResource resource, ShutdownSignalException e) {
  Method method = e.getReason();
  if (method instanceof AMQP.Connection.Close) {
    if (recoveryChannel != null)
      when(recoveryChannel.isOpen()).thenReturn(false);
    connectionHandler.shutdownListeners.get(0).shutdownCompleted(e);
  } else if (method instanceof AMQP.Channel.Close)
    resource.shutdownListeners.get(0).shutdownCompleted(e);
}