Search in sources :

Example 16 with ServerSession

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

the class StompPluginTest method createServer.

@Override
protected JMSServerManager createServer() throws Exception {
    JMSServerManager server = super.createServer();
    server.getActiveMQServer().registerBrokerPlugin(verifier);
    server.getActiveMQServer().registerBrokerPlugin(new ActiveMQServerPlugin() {

        @Override
        public void beforeCreateSession(String name, String username, int minLargeMessageSize, RemotingConnection connection, boolean autoCommitSends, boolean autoCommitAcks, boolean preAcknowledge, boolean xa, String defaultAddress, SessionCallback callback, boolean autoCreateQueues, OperationContext context, Map<SimpleString, RoutingType> prefixes) throws ActiveMQException {
            if (connection instanceof StompConnection) {
                stompBeforeCreateSession.set(true);
            }
        }

        @Override
        public void beforeCloseSession(ServerSession session, boolean failed) throws ActiveMQException {
            if (session.getRemotingConnection() instanceof StompConnection) {
                stompBeforeRemoveSession.set(true);
            }
        }
    });
    return server;
}
Also used : OperationContext(org.apache.activemq.artemis.core.persistence.OperationContext) JMSServerManager(org.apache.activemq.artemis.jms.server.JMSServerManager) 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) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) SessionCallback(org.apache.activemq.artemis.spi.core.protocol.SessionCallback) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ActiveMQServerPlugin(org.apache.activemq.artemis.core.server.plugin.ActiveMQServerPlugin) StompConnection(org.apache.activemq.artemis.core.protocol.stomp.StompConnection) RoutingType(org.apache.activemq.artemis.api.core.RoutingType)

Example 17 with ServerSession

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

the class ReconnectTest method internalMetadataAfterRetry.

public void internalMetadataAfterRetry(final boolean isNetty) throws Exception {
    final int pingPeriod = 1000;
    ActiveMQServer server = createServer(false, isNetty);
    server.start();
    ClientSessionInternal session = null;
    try {
        for (int i = 0; i < 100; i++) {
            ServerLocator locator = createFactory(isNetty);
            locator.setClientFailureCheckPeriod(pingPeriod);
            locator.setRetryInterval(1);
            locator.setRetryIntervalMultiplier(1d);
            locator.setReconnectAttempts(-1);
            locator.setConfirmationWindowSize(-1);
            ClientSessionFactory factory = createSessionFactory(locator);
            session = (ClientSessionInternal) factory.createSession();
            session.addMetaData("meta1", "meta1");
            ServerSession[] sessions = countMetadata(server, "meta1", 1);
            Assert.assertEquals(1, sessions.length);
            final AtomicInteger count = new AtomicInteger(0);
            final CountDownLatch latch = new CountDownLatch(1);
            session.addFailoverListener(new FailoverEventListener() {

                @Override
                public void failoverEvent(FailoverEventType eventType) {
                    if (eventType == FailoverEventType.FAILOVER_COMPLETED) {
                        latch.countDown();
                    }
                }
            });
            sessions[0].getRemotingConnection().fail(new ActiveMQException("failure!"));
            Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
            sessions = countMetadata(server, "meta1", 1);
            Assert.assertEquals(1, sessions.length);
            locator.close();
        }
    } finally {
        try {
            session.close();
        } catch (Throwable e) {
        }
        server.stop();
    }
}
Also used : ClientSessionInternal(org.apache.activemq.artemis.core.client.impl.ClientSessionInternal) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) CountDownLatch(java.util.concurrent.CountDownLatch) ActiveMQServer(org.apache.activemq.artemis.core.server.ActiveMQServer) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FailoverEventType(org.apache.activemq.artemis.api.core.client.FailoverEventType) ClientSessionFactory(org.apache.activemq.artemis.api.core.client.ClientSessionFactory) FailoverEventListener(org.apache.activemq.artemis.api.core.client.FailoverEventListener) ServerLocator(org.apache.activemq.artemis.api.core.client.ServerLocator)

Example 18 with ServerSession

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

the class ActiveMQPacketHandler method handleCreateSession.

private void handleCreateSession(final CreateSessionMessage request) {
    boolean incompatibleVersion = false;
    Packet response;
    try {
        Version version = server.getVersion();
        if (!version.isCompatible(request.getVersion())) {
            throw ActiveMQMessageBundle.BUNDLE.incompatibleClientServer();
        }
        if (!server.isStarted()) {
            throw ActiveMQMessageBundle.BUNDLE.serverNotStarted();
        }
        if (connection.getChannelVersion() == 0) {
            connection.setChannelVersion(request.getVersion());
        } else if (connection.getChannelVersion() != request.getVersion()) {
            ActiveMQServerLogger.LOGGER.incompatibleVersionAfterConnect(request.getVersion(), connection.getChannelVersion());
        }
        Channel channel = connection.getChannel(request.getSessionChannelID(), request.getWindowSize());
        ActiveMQPrincipal activeMQPrincipal = null;
        if (request.getUsername() == null) {
            activeMQPrincipal = connection.getDefaultActiveMQPrincipal();
        }
        OperationContext sessionOperationContext = server.newOperationContext();
        Map<SimpleString, RoutingType> routingTypeMap = protocolManager.getPrefixes();
        CoreSessionCallback sessionCallback = new CoreSessionCallback(request.getName(), protocolManager, channel, connection);
        ServerSession session = server.createSession(request.getName(), activeMQPrincipal == null ? request.getUsername() : activeMQPrincipal.getUserName(), activeMQPrincipal == null ? request.getPassword() : activeMQPrincipal.getPassword(), request.getMinLargeMessageSize(), connection, request.isAutoCommitSends(), request.isAutoCommitAcks(), request.isPreAcknowledge(), request.isXA(), request.getDefaultAddress(), sessionCallback, true, sessionOperationContext, routingTypeMap);
        ServerProducer serverProducer = new ServerProducerImpl(session.getName(), "CORE", request.getDefaultAddress());
        session.addProducer(serverProducer);
        ServerSessionPacketHandler handler = new ServerSessionPacketHandler(server, protocolManager, session, server.getStorageManager(), channel);
        channel.setHandler(handler);
        sessionCallback.setSessionHandler(handler);
        // TODO - where is this removed?
        protocolManager.addSessionHandler(request.getName(), handler);
        response = new CreateSessionResponseMessage(server.getVersion().getIncrementingVersion());
    } catch (ActiveMQClusterSecurityException | ActiveMQSecurityException e) {
        ActiveMQServerLogger.LOGGER.securityProblemWhileCreatingSession(e.getMessage());
        response = new ActiveMQExceptionMessage(e);
    } catch (ActiveMQException e) {
        if (e.getType() == ActiveMQExceptionType.INCOMPATIBLE_CLIENT_SERVER_VERSIONS) {
            incompatibleVersion = true;
            logger.debug("Sending ActiveMQException after Incompatible client", e);
        } else {
            ActiveMQServerLogger.LOGGER.failedToCreateSession(e);
        }
        response = new ActiveMQExceptionMessage(e);
    } catch (Exception e) {
        ActiveMQServerLogger.LOGGER.failedToCreateSession(e);
        response = new ActiveMQExceptionMessage(new ActiveMQInternalErrorException());
    }
    // are not compatible
    if (incompatibleVersion) {
        channel1.sendAndFlush(response);
    } else {
        channel1.send(response);
    }
}
Also used : OperationContext(org.apache.activemq.artemis.core.persistence.OperationContext) ServerSessionPacketHandler(org.apache.activemq.artemis.core.protocol.core.ServerSessionPacketHandler) Packet(org.apache.activemq.artemis.core.protocol.core.Packet) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) ActiveMQPrincipal(org.apache.activemq.artemis.core.security.ActiveMQPrincipal) CreateSessionResponseMessage(org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionResponseMessage) Channel(org.apache.activemq.artemis.core.protocol.core.Channel) ActiveMQExceptionMessage(org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage) ActiveMQClusterSecurityException(org.apache.activemq.artemis.api.core.ActiveMQClusterSecurityException) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) ActiveMQInternalErrorException(org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException) ServerProducer(org.apache.activemq.artemis.core.server.ServerProducer) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ActiveMQClusterSecurityException(org.apache.activemq.artemis.api.core.ActiveMQClusterSecurityException) ActiveMQInternalErrorException(org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException) ActiveMQSecurityException(org.apache.activemq.artemis.api.core.ActiveMQSecurityException) ServerProducerImpl(org.apache.activemq.artemis.core.server.impl.ServerProducerImpl) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) Version(org.apache.activemq.artemis.core.version.Version) ActiveMQSecurityException(org.apache.activemq.artemis.api.core.ActiveMQSecurityException) RoutingType(org.apache.activemq.artemis.api.core.RoutingType)

Example 19 with ServerSession

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

the class MDBMultipleHandlersServerDisconnectTest method testReconnectMDBNoMessageLoss.

@Test
public void testReconnectMDBNoMessageLoss() throws Exception {
    AddressSettings settings = new AddressSettings();
    settings.setRedeliveryDelay(100);
    settings.setMaxDeliveryAttempts(-1);
    server.getAddressSettingsRepository().clear();
    server.getAddressSettingsRepository().addMatch("#", settings);
    ActiveMQResourceAdapter qResourceAdapter = newResourceAdapter();
    resourceAdapter = qResourceAdapter;
    resourceAdapter.setConfirmationWindowSize(-1);
    resourceAdapter.setCallTimeout(1000L);
    resourceAdapter.setConsumerWindowSize(1024 * 1024);
    resourceAdapter.setReconnectAttempts(-1);
    resourceAdapter.setRetryInterval(100L);
    // qResourceAdapter.setTransactionManagerLocatorClass(DummyTMLocator.class.getName());
    // qResourceAdapter.setTransactionManagerLocatorMethod("getTM");
    MyBootstrapContext ctx = new MyBootstrapContext();
    qResourceAdapter.setConnectorClassName(NETTY_CONNECTOR_FACTORY);
    qResourceAdapter.start(ctx);
    final int NUMBER_OF_SESSIONS = 10;
    ActiveMQActivationSpec spec = new ActiveMQActivationSpec();
    spec.setTransactionTimeout(1);
    spec.setMaxSession(NUMBER_OF_SESSIONS);
    spec.setSetupAttempts(-1);
    spec.setSetupInterval(100L);
    spec.setResourceAdapter(qResourceAdapter);
    spec.setUseJNDI(false);
    spec.setDestinationType("javax.jms.Queue");
    spec.setDestination(MDBQUEUE);
    // Some the routines would be screwed up if using the default one
    Assert.assertFalse(spec.isHasBeenUpdated());
    TestEndpointFactory endpointFactory = new TestEndpointFactory(true);
    qResourceAdapter.endpointActivation(endpointFactory, spec);
    Assert.assertEquals(1, resourceAdapter.getActivations().values().size());
    ActiveMQActivation activation = resourceAdapter.getActivations().values().toArray(new ActiveMQActivation[1])[0];
    final int NUMBER_OF_MESSAGES = 1000;
    Thread producer = new Thread() {

        @Override
        public void run() {
            try {
                ServerLocator locator = createInVMLocator(0);
                ClientSessionFactory factory = locator.createSessionFactory();
                ClientSession session = factory.createSession(false, false);
                ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
                StringBuffer buffer = new StringBuffer();
                for (int b = 0; b < 500; b++) {
                    buffer.append("ab");
                }
                for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
                    ClientMessage message = session.createMessage(true);
                    message.getBodyBuffer().writeString(buffer.toString() + i);
                    message.putIntProperty("i", i);
                    clientProducer.send(message);
                    if (i % 100 == 0) {
                        session.commit();
                    }
                }
                session.commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    producer.start();
    final AtomicBoolean metaDataFailed = new AtomicBoolean(false);
    Thread buggerThread = new Thread() {

        @Override
        public void run() {
            while (running.get()) {
                try {
                    Thread.sleep(RandomUtil.randomInterval(100, 200));
                } catch (InterruptedException intex) {
                    intex.printStackTrace();
                    return;
                }
                List<ServerSession> serverSessions = lookupServerSessions("resource-adapter", NUMBER_OF_SESSIONS);
                System.err.println("Contains " + serverSessions.size() + " RA sessions");
                if (serverSessions.size() != NUMBER_OF_SESSIONS) {
                    System.err.println("the server was supposed to have " + NUMBER_OF_MESSAGES + " RA Sessions but it only contained accordingly to the meta-data");
                    metaDataFailed.set(true);
                } else if (serverSessions.size() == NUMBER_OF_SESSIONS) {
                    // it became the same after some reconnect? which would be acceptable
                    metaDataFailed.set(false);
                }
                if (playServerClosingSession && serverSessions.size() > 0) {
                    int randomBother = RandomUtil.randomInterval(0, serverSessions.size() - 1);
                    System.out.println("bugging session " + randomBother);
                    ServerSession serverSession = serverSessions.get(randomBother);
                    if (playServerClosingConsumer && RandomUtil.randomBoolean()) {
                        // will play this randomly, only half of the times
                        for (ServerConsumer consumer : serverSession.getServerConsumers()) {
                            try {
                                // Simulating a rare race that could happen in production
                                // where the consumer is closed while things are still happening
                                consumer.close(true);
                                Thread.sleep(100);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    RemotingConnection connection = serverSession.getRemotingConnection();
                    connection.fail(new ActiveMQException("failed at random " + randomBother));
                }
            }
        }
    };
    buggerThread.start();
    ServerLocator locator = createInVMLocator(0);
    ClientSessionFactory factory = locator.createSessionFactory();
    ClientSession session = factory.createSession(false, false);
    session.start();
    ClientConsumer consumer = session.createConsumer("outQueue");
    for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
        ClientMessage message = consumer.receive(60000);
        if (message == null) {
            break;
        }
        if (i == NUMBER_OF_MESSAGES * 0.50) {
            // This is to make sure the MDBs will survive a reboot
            // and no duplications or message loss will happen because of this
            System.err.println("Rebooting the MDBs at least once!");
            activation.startReconnectThread("I");
        }
        if (i == NUMBER_OF_MESSAGES * 0.90) {
            System.out.println("Disabled failures at " + i);
            playTXTimeouts = false;
            playServerClosingSession = false;
            playServerClosingConsumer = false;
        }
        System.out.println("Received " + i + " messages");
        doReceiveMessage(message);
        if (i % 200 == 0) {
            System.out.println("received " + i);
            session.commit();
        }
    }
    session.commit();
    while (true) {
        ClientMessage message = consumer.receiveImmediate();
        if (message == null) {
            break;
        }
        System.out.println("Received extra message " + message);
        doReceiveMessage(message);
    }
    session.commit();
    Assert.assertNull(consumer.receiveImmediate());
    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    boolean failed = false;
    for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
        AtomicInteger atomicInteger = mapCounter.get(Integer.valueOf(i));
        if (atomicInteger == null) {
            out.println("didn't receive message with i=" + i);
            failed = true;
        } else if (atomicInteger.get() > 1) {
            out.println("message with i=" + i + " received " + atomicInteger.get() + " times");
            failed = true;
        }
    }
    running.set(false);
    buggerThread.join();
    producer.join();
    qResourceAdapter.stop();
    session.close();
    if (failed) {
        for (int i = 0; i < 10; i++) {
            System.out.println("----------------------------------------------------");
        }
        System.out.println(writer.toString());
    }
    Assert.assertFalse(writer.toString(), failed);
    System.out.println("Received " + NUMBER_OF_MESSAGES + " messages");
    Assert.assertFalse("There was meta-data failures, some sessions didn't reconnect properly", metaDataFailed.get());
}
Also used : ActiveMQActivation(org.apache.activemq.artemis.ra.inflow.ActiveMQActivation) RemotingConnection(org.apache.activemq.artemis.spi.core.protocol.RemotingConnection) ClientMessage(org.apache.activemq.artemis.api.core.client.ClientMessage) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) StringWriter(java.io.StringWriter) ClientSession(org.apache.activemq.artemis.api.core.client.ClientSession) ActiveMQResourceAdapter(org.apache.activemq.artemis.ra.ActiveMQResourceAdapter) ClientSessionFactory(org.apache.activemq.artemis.api.core.client.ClientSessionFactory) ActiveMQActivationSpec(org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec) ClientProducer(org.apache.activemq.artemis.api.core.client.ClientProducer) ServerLocator(org.apache.activemq.artemis.api.core.client.ServerLocator) PrintWriter(java.io.PrintWriter) AddressSettings(org.apache.activemq.artemis.core.settings.impl.AddressSettings) ServerSession(org.apache.activemq.artemis.core.server.ServerSession) ServerConsumer(org.apache.activemq.artemis.core.server.ServerConsumer) MessageEndpoint(javax.resource.spi.endpoint.MessageEndpoint) 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) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientConsumer(org.apache.activemq.artemis.api.core.client.ClientConsumer) Test(org.junit.Test)

Example 20 with ServerSession

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

the class ActiveMQServerControlImpl method listAllConsumersAsJSON.

@Override
public String listAllConsumersAsJSON() throws Exception {
    checkStarted();
    clearIO();
    try {
        JsonArrayBuilder array = JsonLoader.createArrayBuilder();
        Set<ServerSession> sessions = server.getSessions();
        for (ServerSession session : sessions) {
            Set<ServerConsumer> consumers = session.getServerConsumers();
            for (ServerConsumer consumer : consumers) {
                JsonObject obj = toJSONObject(consumer);
                if (obj != null) {
                    array.add(obj);
                }
            }
        }
        return array.build().toString();
    } finally {
        blockOnIO();
    }
}
Also used : ServerSession(org.apache.activemq.artemis.core.server.ServerSession) JsonObject(javax.json.JsonObject) JsonArrayBuilder(javax.json.JsonArrayBuilder) ServerConsumer(org.apache.activemq.artemis.core.server.ServerConsumer)

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