Search in sources :

Example 11 with ServerSession

use of org.apache.activemq.artemis.core.server.ServerSession in project activemq-artemis by apache.

the class ActiveMQServerImpl method destroyConnectionWithSessionMetadata.

@Override
public String destroyConnectionWithSessionMetadata(String metaKey, String parameterValue) throws Exception {
    StringBuffer operationsExecuted = new StringBuffer();
    try {
        operationsExecuted.append("**************************************************************************************************\n");
        operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataHeader(metaKey, parameterValue) + "\n");
        Set<ServerSession> allSessions = getSessions();
        ServerSession sessionFound = null;
        for (ServerSession session : allSessions) {
            try {
                String value = session.getMetaData(metaKey);
                if (value != null && value.equals(parameterValue)) {
                    sessionFound = session;
                    operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataClosingConnection(sessionFound.toString()) + "\n");
                    RemotingConnection conn = session.getRemotingConnection();
                    if (conn != null) {
                        conn.fail(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataSendException(metaKey, parameterValue));
                    }
                    session.close(true);
                    sessions.remove(session.getName());
                }
            } catch (Throwable e) {
                ActiveMQServerLogger.LOGGER.unableDestroyConnectionWithSessionMetadata(e);
            }
        }
        if (sessionFound == null) {
            operationsExecuted.append(ActiveMQMessageBundle.BUNDLE.destroyConnectionWithSessionMetadataNoSessionFound(metaKey, parameterValue) + "\n");
        }
        operationsExecuted.append("**************************************************************************************************");
        return operationsExecuted.toString();
    } finally {
        // This operation is critical for the knowledge of the admin, so we need to add info logs for later knowledge
        ActiveMQServerLogger.LOGGER.onDestroyConnectionWithSessionMetadata(operationsExecuted.toString());
    }
}
Also used : ServerSession(org.apache.activemq.artemis.core.server.ServerSession) RemotingConnection(org.apache.activemq.artemis.spi.core.protocol.RemotingConnection) SimpleString(org.apache.activemq.artemis.api.core.SimpleString)

Example 12 with ServerSession

use of org.apache.activemq.artemis.core.server.ServerSession in project activemq-artemis by apache.

the class ConcurrentDeliveryCancelTest method testConcurrentCancels.

@Test
@BMRules(rules = { @BMRule(name = "enterCancel-holdThere", targetClass = "org.apache.activemq.artemis.core.server.impl.ServerConsumerImpl", targetMethod = "close", targetLocation = "ENTRY", action = "org.apache.activemq.artemis.tests.extras.byteman.ConcurrentDeliveryCancelTest.enterCancel();") })
public void testConcurrentCancels() throws Exception {
    System.out.println(server.getConfiguration().getJournalLocation().toString());
    server.getAddressSettingsRepository().clear();
    AddressSettings settings = new AddressSettings();
    settings.setMaxDeliveryAttempts(-1);
    server.getAddressSettingsRepository().addMatch("#", settings);
    ActiveMQConnectionFactory cf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test");
    cf.setReconnectAttempts(0);
    cf.setRetryInterval(10);
    System.out.println(".....");
    for (ServerSession srvSess : server.getSessions()) {
        System.out.println(srvSess);
    }
    String queueName = RandomUtil.randomString();
    Queue queue = createQueue(queueName);
    int numberOfMessages = 10000;
    {
        Connection connection = cf.createConnection();
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(queue);
        for (int i = 0; i < numberOfMessages; i++) {
            TextMessage msg = session.createTextMessage("message " + i);
            msg.setIntProperty("i", i);
            producer.send(msg);
        }
        session.commit();
        connection.close();
    }
    for (int i = 0; i < 100; i++) {
        XAConnectionFactory xacf = ActiveMQJMSClient.createConnectionFactory("tcp://localhost:61616", "test");
        final XAConnection connection = xacf.createXAConnection();
        final XASession theSession = connection.createXASession();
        ((ActiveMQSession) theSession).getCoreSession().addMetaData("theSession", "true");
        connection.start();
        final MessageConsumer consumer = theSession.createConsumer(queue);
        XidImpl xid = newXID();
        theSession.getXAResource().start(xid, XAResource.TMNOFLAGS);
        // I'm setting a small timeout just because I'm lazy to call end myself
        theSession.getXAResource().setTransactionTimeout(1);
        for (int msg = 0; msg < 11; msg++) {
            Assert.assertNotNull(consumer.receiveNoWait());
        }
        System.out.println(".....");
        final List<ServerSession> serverSessions = new LinkedList<>();
        // We will force now the failure simultaneously from several places
        for (ServerSession srvSess : server.getSessions()) {
            if (srvSess.getMetaData("theSession") != null) {
                System.out.println(srvSess);
                serverSessions.add(srvSess);
            }
        }
        // from Transactional reaper
        resetLatches(2);
        List<Thread> threads = new LinkedList<>();
        threads.add(new Thread("ConsumerCloser") {

            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + " closing consumer");
                    consumer.close();
                    System.out.println(Thread.currentThread().getName() + " closed consumer");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        threads.add(new Thread("SessionCloser") {

            @Override
            public void run() {
                for (ServerSession sess : serverSessions) {
                    System.out.println("Thread " + Thread.currentThread().getName() + " starting");
                    try {
                        // A session.close could sneak in through failover or some other scenarios.
                        // a call to RemotingConnection.fail wasn't replicating the issue.
                        // I needed to call Session.close() directly to replicate what was happening in production
                        sess.close(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread " + Thread.currentThread().getName() + " done");
                }
            }
        });
        for (Thread t : threads) {
            t.start();
        }
        Assert.assertTrue(latchEnter.await(10, TimeUnit.MINUTES));
        latchFlag.countDown();
        for (Thread t : threads) {
            t.join(5000);
            Assert.assertFalse(t.isAlive());
        }
        connection.close();
    }
    Connection connection = cf.createConnection();
    try {
        connection.setClientID("myID");
        // I am too lazy to call end on all the transactions
        Thread.sleep(5000);
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(queue);
        HashMap<Integer, AtomicInteger> mapCount = new HashMap<>();
        while (true) {
            TextMessage message = (TextMessage) consumer.receiveNoWait();
            if (message == null) {
                break;
            }
            Integer value = message.getIntProperty("i");
            AtomicInteger count = mapCount.get(value);
            if (count == null) {
                count = new AtomicInteger(0);
                mapCount.put(message.getIntProperty("i"), count);
            }
            count.incrementAndGet();
        }
        boolean failed = false;
        for (int i = 0; i < numberOfMessages; i++) {
            AtomicInteger count = mapCount.get(i);
            if (count == null) {
                System.out.println("Message " + i + " not received");
                failed = true;
            } else if (count.get() > 1) {
                System.out.println("Message " + i + " received " + count.get() + " times");
                failed = true;
            }
        }
        Assert.assertFalse("test failed, look at the system.out of the test for more information", failed);
    } finally {
        connection.close();
    }
}
Also used : HashMap(java.util.HashMap) XidImpl(org.apache.activemq.artemis.core.transaction.impl.XidImpl) ActiveMQConnectionFactory(org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory) XASession(javax.jms.XASession) Queue(javax.jms.Queue) XAConnection(javax.jms.XAConnection) AddressSettings(org.apache.activemq.artemis.core.settings.impl.AddressSettings) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) MessageConsumer(javax.jms.MessageConsumer) XAConnection(javax.jms.XAConnection) Connection(javax.jms.Connection) LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) XAConnectionFactory(javax.jms.XAConnectionFactory) MessageProducer(javax.jms.MessageProducer) TextMessage(javax.jms.TextMessage) XASession(javax.jms.XASession) Session(javax.jms.Session) ActiveMQSession(org.apache.activemq.artemis.jms.client.ActiveMQSession) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) Test(org.junit.Test) BMRules(org.jboss.byteman.contrib.bmunit.BMRules)

Example 13 with ServerSession

use of org.apache.activemq.artemis.core.server.ServerSession in project activemq-artemis by apache.

the class ActiveMQServerControlTest method testCloseJMSclient.

@Test
public void testCloseJMSclient() throws Exception {
    ActiveMQServerControl serverControl = createManagementControl();
    ConnectionFactory cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
    Connection conn = cf.createConnection();
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    javax.jms.Topic topic = ActiveMQJMSClient.createTopic("ConsumerTestTopic");
    MessageConsumer JMSclient = session.createConsumer(topic, "test1");
    long clientID = -1;
    String sessionID = ((ClientSessionImpl) (((ActiveMQSession) session).getCoreSession())).getName();
    Set<ServerSession> sessions = server.getSessions();
    for (ServerSession sess : sessions) {
        if (sess.getName().equals(sessionID.toString())) {
            Set<ServerConsumer> serverConsumers = sess.getServerConsumers();
            for (ServerConsumer serverConsumer : serverConsumers) {
                clientID = serverConsumer.sequentialID();
            }
        }
    }
    Assert.assertFalse(((org.apache.activemq.artemis.jms.client.ActiveMQMessageConsumer) JMSclient).isClosed());
    serverControl.closeConsumerWithID(sessionID, Long.toString(clientID));
    Wait.waitFor(() -> ((org.apache.activemq.artemis.jms.client.ActiveMQMessageConsumer) JMSclient).isClosed());
    Assert.assertTrue(((org.apache.activemq.artemis.jms.client.ActiveMQMessageConsumer) JMSclient).isClosed());
}
Also used : MessageConsumer(javax.jms.MessageConsumer) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) ActiveMQServerControl(org.apache.activemq.artemis.api.core.management.ActiveMQServerControl) Connection(javax.jms.Connection) TransportConfiguration(org.apache.activemq.artemis.api.core.TransportConfiguration) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) ServerConsumer(org.apache.activemq.artemis.core.server.ServerConsumer) ConnectionFactory(javax.jms.ConnectionFactory) ActiveMQSession(org.apache.activemq.artemis.jms.client.ActiveMQSession) ClientSessionImpl(org.apache.activemq.artemis.core.client.impl.ClientSessionImpl) Session(javax.jms.Session) ActiveMQSession(org.apache.activemq.artemis.jms.client.ActiveMQSession) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) ClientSession(org.apache.activemq.artemis.api.core.client.ClientSession) Test(org.junit.Test)

Example 14 with ServerSession

use of org.apache.activemq.artemis.core.server.ServerSession in project activemq-artemis by apache.

the class TemporaryQueueTest method testBlockingWithTemporaryQueue.

@Test
public void testBlockingWithTemporaryQueue() throws Exception {
    AddressSettings setting = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.BLOCK).setMaxSizeBytes(1024 * 1024);
    server.getAddressSettingsRepository().addMatch("TestAD", setting);
    ClientSessionFactory consumerCF = createSessionFactory(locator);
    ClientSession consumerSession = consumerCF.createSession(true, true);
    consumerSession.addMetaData("consumer", "consumer");
    consumerSession.createTemporaryQueue("TestAD", "Q1");
    consumerSession.createConsumer("Q1");
    consumerSession.start();
    final ClientProducerImpl prod = (ClientProducerImpl) session.createProducer("TestAD");
    final AtomicInteger errors = new AtomicInteger(0);
    final AtomicInteger msgs = new AtomicInteger(0);
    final int TOTAL_MSG = 1000;
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                for (int i = 0; i < TOTAL_MSG; i++) {
                    ClientMessage msg = session.createMessage(false);
                    msg.getBodyBuffer().writeBytes(new byte[1024]);
                    prod.send(msg);
                    msgs.incrementAndGet();
                }
            } catch (Throwable e) {
                e.printStackTrace();
                errors.incrementAndGet();
            }
            System.out.println("done");
        }
    };
    t.start();
    while (msgs.get() == 0) {
        Thread.sleep(100);
    }
    int blockedTime = 0;
    // https://issues.apache.org/jira/browse/ARTEMIS-368
    while (t.isAlive() && errors.get() == 0 && (!prod.getProducerCredits().isBlocked() || blockedTime < 60)) {
        if (prod.getProducerCredits().isBlocked()) {
            blockedTime++;
        } else {
            blockedTime = 0;
        }
        Thread.sleep(100);
    }
    assertEquals(0, errors.get());
    ClientSessionFactory newConsumerCF = createSessionFactory(locator);
    ClientSession newConsumerSession = newConsumerCF.createSession(true, true);
    newConsumerSession.createTemporaryQueue("TestAD", "Q2");
    ClientConsumer newConsumer = newConsumerSession.createConsumer("Q2");
    newConsumerSession.start();
    int toReceive = TOTAL_MSG - msgs.get();
    for (ServerSession sessionIterator : server.getSessions()) {
        if (sessionIterator.getMetaData("consumer") != null) {
            System.out.println("Failing session");
            ServerSessionImpl impl = (ServerSessionImpl) sessionIterator;
            impl.getRemotingConnection().fail(new ActiveMQDisconnectedException("failure e"));
        }
    }
    int secondReceive = 0;
    ClientMessage msg = null;
    while (secondReceive < toReceive && (msg = newConsumer.receive(5000)) != null) {
        msg.acknowledge();
        secondReceive++;
    }
    assertNull(newConsumer.receiveImmediate());
    assertEquals(toReceive, secondReceive);
    t.join();
}
Also used : AddressSettings(org.apache.activemq.artemis.core.settings.impl.AddressSettings) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) ActiveMQDisconnectedException(org.apache.activemq.artemis.api.core.ActiveMQDisconnectedException) ClientMessage(org.apache.activemq.artemis.api.core.client.ClientMessage) ClientProducerImpl(org.apache.activemq.artemis.core.client.impl.ClientProducerImpl) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientSession(org.apache.activemq.artemis.api.core.client.ClientSession) ServerSessionImpl(org.apache.activemq.artemis.core.server.impl.ServerSessionImpl) ClientSessionFactory(org.apache.activemq.artemis.api.core.client.ClientSessionFactory) ClientConsumer(org.apache.activemq.artemis.api.core.client.ClientConsumer) Test(org.junit.Test)

Example 15 with ServerSession

use of org.apache.activemq.artemis.core.server.ServerSession in project activemq-artemis by apache.

the class MDBMultipleHandlersServerDisconnectTest method lookupServerSessions.

private List<ServerSession> lookupServerSessions(String parameter, int numberOfSessions) {
    long timeout = System.currentTimeMillis() + 50000;
    List<ServerSession> serverSessions = new LinkedList<>();
    do {
        if (!serverSessions.isEmpty()) {
            System.err.println("Retry on serverSessions!!! currently with " + serverSessions.size());
            serverSessions.clear();
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                break;
            }
        }
        serverSessions.clear();
        for (ServerSession session : server.getSessions()) {
            if (session.getMetaData(parameter) != null) {
                serverSessions.add(session);
            }
        }
    } while (running.get() && serverSessions.size() != numberOfSessions && timeout > System.currentTimeMillis());
    System.err.println("Returning " + serverSessions.size() + " sessions");
    return serverSessions;
}
Also used : ServerSession(org.apache.activemq.artemis.core.server.ServerSession) LinkedList(java.util.LinkedList) ResourceException(javax.resource.ResourceException) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) LocalTransactionException(javax.resource.spi.LocalTransactionException) RollbackException(javax.transaction.RollbackException) UnavailableException(javax.resource.spi.UnavailableException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) SystemException(javax.transaction.SystemException) HeuristicMixedException(javax.transaction.HeuristicMixedException)

Aggregations

ServerSession (org.apache.activemq.artemis.core.server.ServerSession)32 SimpleString (org.apache.activemq.artemis.api.core.SimpleString)11 ActiveMQException (org.apache.activemq.artemis.api.core.ActiveMQException)8 ServerConsumer (org.apache.activemq.artemis.core.server.ServerConsumer)7 HashSet (java.util.HashSet)6 RemotingConnection (org.apache.activemq.artemis.spi.core.protocol.RemotingConnection)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 AddressSettings (org.apache.activemq.artemis.core.settings.impl.AddressSettings)5 Test (org.junit.Test)5 Date (java.util.Date)4 JsonArrayBuilder (javax.json.JsonArrayBuilder)4 JsonObjectBuilder (javax.json.JsonObjectBuilder)4 RoutingType (org.apache.activemq.artemis.api.core.RoutingType)4 ClientSession (org.apache.activemq.artemis.api.core.client.ClientSession)4 ClientSessionFactory (org.apache.activemq.artemis.api.core.client.ClientSessionFactory)4 LinkedList (java.util.LinkedList)3 ActiveMQServer (org.apache.activemq.artemis.core.server.ActiveMQServer)3 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 ArrayList (java.util.ArrayList)2