You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@activemq.apache.org by GitBox <gi...@apache.org> on 2021/06/23 15:09:46 UTC

[GitHub] [activemq-artemis] brusdev opened a new pull request #3634: ARTEMIS-3365 Broker Balancers

brusdev opened a new pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634


   This feature adds broker balancers to distribute the incoming client connections across multiple brokers. It provides a native redirection for supported clients and a new management API for other clients. The native redirection can be enabled per acceptor and is supported only for CORE and AMQP clients. See [ARTEMIS-3365](https://issues.apache.org/jira/browse/ARTEMIS-3365)[1] and the [draft documentation ](https://github.com/brusdev/activemq-artemis/blob/broker_balancers/docs/user-manual/en/broker-balancers.md)[2] for further details. 
   
   [1] https://issues.apache.org/jira/browse/ARTEMIS-3365
   [2] https://github.com/brusdev/activemq-artemis/blob/broker_balancers/docs/user-manual/en/broker-balancers.md
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683292258



##########
File path: examples/features/broker-balancer/pom.xml
##########
@@ -0,0 +1,62 @@
+<?xml version='1.0'?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.apache.activemq.examples.clustered</groupId>
+      <artifactId>broker-features</artifactId>
+      <version>2.18.0-SNAPSHOT</version>
+   </parent>
+
+   <groupId>org.apache.activemq.examples</groupId>
+   <artifactId>broker-balancer</artifactId>
+   <packaging>pom</packaging>
+   <name>ActiveMQ Artemis Broker Balancer Examples</name>
+
+   <!-- Properties -->
+   <properties>
+      <!--
+      Explicitly declaring the source encoding eliminates the following
+      message: [WARNING] Using platform encoding (UTF-8 actually) to copy
+      filtered resources, i.e. build is platform dependent!
+      -->
+      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

Review comment:
       removed




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867012012


   Is it possible that this can be used to shard an address across brokers and have clients send to different brokers based on mgroups via a consistent hash? E.g. client has smarts to send mgroup A to broker 1 mgroup B to broker 3 and mgroup C to broker 2 for example where the mgroup to broker is by consistent hash
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683543702



##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# Evenly Redirect Example
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how incoming client connections are evenly redirected across two brokers
+using a third broker with a broker balancer to redirect incoming client connections.

Review comment:
       yes I would need a persistent cache to get Durable Subscription after a restart

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");

Review comment:
       updated

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryProducer0.createConnection();
+         connectionProducer1 = connectionFactoryProducer1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID prefix.

Review comment:
       updated

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryProducer0.createConnection();
+         connectionProducer1 = connectionFactoryProducer1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID prefix.
+       */
+      ConnectionFactory connectionFactoryConsumer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_CONSUMER");
+      ConnectionFactory connectionFactoryConsumer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");

Review comment:
       updated

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are distributed across two brokers
+ * using a symmetric architecture.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactory0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactory1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");

Review comment:
       updated

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are distributed across two brokers
+ * using a symmetric architecture.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactory0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactory1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactory0Server0.createConnection();
+         connectionProducer1 = connectionFactory1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID().substring(0, 3));
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID().substring(0, 3));
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server1 will redirect the connection to the same target broker of the respective producer
+       * from earlier as the new consumer connection uses the same ClientID prefix.
+       */
+      ConnectionFactory connectionFactory0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=TOO_CONSUMER");
+      ConnectionFactory connectionFactory1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");

Review comment:
       updated




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683612112



##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# Evenly Redirect Example
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how incoming client connections are evenly redirected across two brokers
+using a third broker with a broker balancer to redirect incoming client connections.

Review comment:
       Yep, and I think its fine not having that, just thought it might be worth noting (maybe in the code comment instead) as the caching may catch some folks out if they dont consider that.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r660443602



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +474,46 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         BrokerBalancer brokerBalancer = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo());
+         Target target = brokerBalancer.getTarget(transportConnection,
+            connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(String.format("Connection redirected to %s by broker balancer %s", brokerBalancer.getName(), target));

Review comment:
       yes the args are reversed. I'll replace the target.toString() with host:port




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-893873713


   @clebertsuconic I have regenerated security resources after adding other server names to the `build.sh` script. I have just pushed a commit to avoid creating new redirect objects if not required.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] asfgit closed pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
asfgit closed pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gtully commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gtully commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867514767


   having a key-filter or target-key-filter applied to the raw key would be a nice addition. Even for the client-IP policy, being able to shard on just some of the components of an IP is powerful when IP ranges are carefully managed.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683267498



##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       Oh I see, it caches the results and sends things to the same place next time, even if that isnt the one with least connections? That isnt at all what I had expected from it on initial reading (I thought the clientid would only be getting used for the defined local target filter in that case).
   
   Its unclear to me where any of it is looking at ClientID prefixes, seems more like it looking at the whole value, where does the prefix consideration happen? (E.g would looking at only a prefix need to use the filtering stuff? Or is there a specific syntax to use?) The example seems to use ones that are exact matches across the sets of connections. 




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682718787



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       Using "localhost.localdomain" can sometimes be problematic in some environments. I'd consider just using localhost for the connections. 
   
   For the Core client, I think you can specify the SNI value explicitly, so you could still set it to something entirely different in that case if wanting to verify a non-localhost SNI value is picked up by the policy at the server.

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how you can distribute incoming client connections across two brokers using a symmetric architecture.

Review comment:
       Perhaps expand on what the 'symmetric architecture' is? I honestly have no clear idea from the description at this point what the example is about to show.
   
   (EDIT: so its showing that both brokers are set up to do a consistent hash of ClientID, such that each will direct the same ClientIDs to the same place, perhaps itself...which per the other comments, isnt actually great for matching specific producers to specific consumers as different connections arent allowed to use the same ClientID at the same time....but it will be consistent in what goes where)

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.

Review comment:
       ```suggestion
   By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
   ```
   Moving 'target' for clarity, as it isnt a 'target broker' yet if it isnt in the pool, which is whats explained next.

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing to have 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.

Review comment:
       ```suggestion
   * the `target-key` element defines what key to select a target broker, the supported values are: `SNI_HOST`, `SOURCE_IP`, `USER_NAME`, `CLIENT_ID`.
   ```
   Missing CLIENT_ID
   

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");

Review comment:
       The verified-localdomain-keystore.jks doesnt seem to have instructions for creation. Small tidyup to bring into place with your other recent PR?

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers

Review comment:
       Incorrect title

##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# AMQP Broker Connection with Receivers

Review comment:
       Title needs fixed

##########
File path: examples/features/broker-balancer/pom.xml
##########
@@ -0,0 +1,62 @@
+<?xml version='1.0'?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.apache.activemq.examples.clustered</groupId>
+      <artifactId>broker-features</artifactId>
+      <version>2.18.0-SNAPSHOT</version>
+   </parent>
+
+   <groupId>org.apache.activemq.examples</groupId>
+   <artifactId>broker-balancer</artifactId>
+   <packaging>pom</packaging>
+   <name>ActiveMQ Artemis Broker Balancer Examples</name>
+
+   <!-- Properties -->
+   <properties>
+      <!--
+      Explicitly declaring the source encoding eliminates the following
+      message: [WARNING] Using platform encoding (UTF-8 actually) to copy
+      filtered resources, i.e. build is platform dependent!
+      -->
+      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

Review comment:
       Dont think this is needed, the apache and artemis parent poms both look to be setting it already. Certainly the comment can go.

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.

Review comment:
       Doesnt seem to match with the readme.

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+      ConnectionFactory connectionFactoryClient0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0Server0.createConnection();
+         connectionProducer1 = connectionFactoryClient1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID());
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID());
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       ```suggestion
          * the server1 will redirect the connection to the same target broker of the respective producer
          * from earlier as the new consumer connection uses the same ClientID.
   ```
   The server is wrong, they connect to server 1 this time.
   
   Avoiding saying 'share the same ClientID' since only one connection at a time can use a ClientID (so a real application probably couldnt use this precise example setup of matching-clientid, but some other setup...unless they could coordinate when the producer and consumer connections would be around, at which point they dont really need a broker)

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing to have 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.

Review comment:
       ```suggestion
   * `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
     according to the priority defined with their sequence order, ie supposing there are 2 target brokers
     this policy selects the second target broker only when the first target broker isn't ready.
   ```

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       Actually, as this uses 2 different ClientIDs but is doing 'least connections', is the ClientID relevant? When the second set of connections happens...what guarantee is it that they go to the same place as the producer if it is only doing 'least connections' balance and both servers have 0? Would it work as described if I changed the order of connection creation on the second round?

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       ```suggestion
          * the server0 will redirect the connection to the same target broker of the respective producer
          * from earlier as the new consumer connection uses the same ClientID.
   ```
   
   Avoiding saying 'share the same ClientID' since only one connection at a time can use a ClientID 

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       You cant for Qpid JMS, dont know for openwire.

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       Oh I see, it caches the results and sends things to the same place next time, even if that isnt the one with least connections? That isnt at all what I had expected from it on initial reading (I thought the clientid would only be getting used for the defined local target filter in that case).
   
   Its unclear to me where any of it is looking at ClientID prefixes, seems more like it looking at the whole value, where does the prefix consideration happen? (E.g would looking at only a prefix need to use the filtering stuff? Or is there a specific syntax to use?) The example seems to use ones that are exact matches across the sets of connections. 

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.

Review comment:
       ```suggestion
   Including the local broker in the target pool allows broker hosting the balancer to accept incoming client connections as well.
   ```
   Similar change for 'target' as before (not sure how I missed it first time). Also drops the 'broker' before 'balancer' as the context is already extremely clear already and there are 3 uses of 'broker' within 9 words which is excessive.

##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# Evenly Redirect Example
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how incoming client connections are evenly redirected across two brokers
+using a third broker with a broker balancer to redirect incoming client connections.

Review comment:
       ```suggestion
   using a third broker as a balancer to redirect incoming client connections, based on a least-connections policy and caching on a filtered prefix of the connection ClientID.
   ```
   or 
   ```suggestion
   using a third broker with a balancer to redirect incoming client connections, based on a least-connections policy and caching on a filtered prefix of the connection ClientID.
   ```
   Expand on how it balances, and that there is caching involved. Drops a 'broker' mention to very slightly ease the presence overload.
   
   Possibly also worth noting that this isnt particularly suitable for Durable Subscription usage as the selected target could change after restart for example?

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");

Review comment:
       ```suggestion
          * Step 1. Create a connection for producer0 and producer1, and send a few messages.
          * the server0 will redirect the connection of each producer to a different target broker.
          */
         ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
         ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=BAR_PRODUCER");
   ```
   FOO and TOO are pretty close and dont jump out as being different as easily as using something further afield like BAR would. Making it do so helps makes the example more obvious.

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryProducer0.createConnection();
+         connectionProducer1 = connectionFactoryProducer1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID prefix.

Review comment:
       ```suggestion
          * because the consumer and the producer connections have the same clientID prefix, which
          * the balancer configuration filters the target key on and caches the target broker the policy selects.
   ```
   Expand on how it is used and why it matters

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>
+</broker-balancers>

Review comment:
       No example of CLIENTID target key use. I think its important to talk about the 'filtering' usage along with that, which will likely be critical to many use cases.

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>

Review comment:
       Seems odd in a way that the example of 'least connections' here is totally different than the one then given in the examples. I presume this one would behaves more like how I thought the other one might, since it has no target key to cache on?

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are evenly redirected across two brokers
+ * using a third broker with a broker balancer to redirect incoming client connections.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactoryProducer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactoryProducer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryProducer0.createConnection();
+         connectionProducer1 = connectionFactoryProducer1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID prefix.
+       */
+      ConnectionFactory connectionFactoryConsumer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_CONSUMER");
+      ConnectionFactory connectionFactoryConsumer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");

Review comment:
       ```suggestion
         ConnectionFactory connectionFactoryConsumer0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=BAR_CONSUMER");
         ConnectionFactory connectionFactoryConsumer1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");
   ```

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are distributed across two brokers
+ * using a symmetric architecture.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactory0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactory1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");
+
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactory0Server0.createConnection();
+         connectionProducer1 = connectionFactory1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID().substring(0, 3));
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID().substring(0, 3));
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server1 will redirect the connection to the same target broker of the respective producer
+       * from earlier as the new consumer connection uses the same ClientID prefix.
+       */
+      ConnectionFactory connectionFactory0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=TOO_CONSUMER");
+      ConnectionFactory connectionFactory1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");

Review comment:
       ```suggestion
         ConnectionFactory connectionFactory0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=BAR_CONSUMER");
         ConnectionFactory connectionFactory1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=FOO_CONSUMER");
   ```

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example demonstrates how incoming client connections are distributed across two brokers
+ * using a symmetric architecture.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      ConnectionFactory connectionFactory0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
+      ConnectionFactory connectionFactory1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=TOO_PRODUCER");

Review comment:
       ```suggestion
          * the server0 will redirect the connection of each producer to a different target broker.
          */
         ConnectionFactory connectionFactory0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=FOO_PRODUCER");
         ConnectionFactory connectionFactory1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=BAR_PRODUCER");
   ```




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-869718754


   I have just pushed a commit to add the `CLIENT_ID` target key. Now the broker balancer can use the jms client ID to distribute the incoming client connections across multiple brokers.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r660006283



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       @gemmellr yes, the redirect to the local target is a pass through. Indeed if target.isLocal() then redirected = false and the connection is managed like any old connection would without the balancer, ie the `RedirectTest#testSymmetricRedirect` test uses the local targets:
   https://github.com/brusdev/activemq-artemis/blob/broker_balancers/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/RedirectTest.java#L221




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-868710253


   @gtully not really. The keys are business keys, akin to why you may want to use kafka partition keys. Theres actually a nice implementation in the old fabric8 that im looking at pulling across, update and enhance.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683290005



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       I have just pushed a commit to skip this test if `localhost.localdomain` is not valid.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894241552


   The redirect handler doesnt do the important check though (it did do it before your original comment), its now already done outside it before you even get it, the same way I was suggesting, which meant everything else changed was unnecessary complexity.
   
   Its basically still instantiating the same amount of stuff now (most of it its just not done unless there is a redirect-to), but just split it up into different places, making it a more complicated and verbose, and meaning a bunch of unrelated code needed updated.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894143709


   I dont think the keystore changes should using NO-JIRA in their log, at least some are being made directly for this JIRA so it makes sense for it to be reflected in the commit log.
   
   I think Clebert was looking to avoid creating the redirect handler objects entirely if not needed, which the updated version doesnt appear to. It still looks to affect every connection, but instead of with the throwaway handler, by adding a new field and creating the handler up front, then just possibly not using it. In some ways this is actually worse than previous version.
   
   I think there is a nicer route in-between, but nearer the earlier version 2212d02f206bbdf9916db225e876eef4583c1326 [1], where it simply checks the redirect-to value on the connection first, and only then proceeds to create and use the handler if there was a need. E.g changes from the previous version for AMQP could maybe have been something like this instead (+add similar for other protocols):
   
   ```
   @@ -528,6 +528,5 @@ public class AMQPConnectionContext extends ProtonInitializable implements EventH
    
   -      AMQPRedirectHandler redirectHandler = new AMQPRedirectHandler(protocolManager.getServer(),
   -         connectionCallback, connection, handler.getSASLResult() != null ? handler.getSASLResult().getUser() : null);
   +      final boolean tryRedirect = connectionCallback.getTransportConnection().getRedirectTo() != null;
    
   -      if (redirectHandler.redirect() || !validateConnection(connection)) {
   +      if (tryRedirect && redirect(connection) || !validateConnection(connection)) {
             connection.close();
   @@ -557,2 +556,9 @@ public class AMQPConnectionContext extends ProtonInitializable implements EventH
    
   +   private final boolean redirect(Connection connection) throws Exception {
   +      AMQPRedirectHandler redirectHandler = new AMQPRedirectHandler(protocolManager.getServer(),
   +            connectionCallback, connection, handler.getSASLResult() != null ? handler.getSASLResult().getUser() : null);
   +
   +      return redirectHandler.redirect();
   +   }
   +
       class ScheduleOperator implements UnaryOperator<Future<?>> {
   ```
   
   
   [1]  I still had the the 2212d02f206bbdf9916db225e876eef4583c1326 version locally, I put it at https://github.com/gemmellr/activemq-artemis/tree/balancer-pr3634-old1 in case you should want it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r660421342



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +474,46 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         BrokerBalancer brokerBalancer = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo());
+         Target target = brokerBalancer.getTarget(transportConnection,
+            connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(String.format("Connection redirected to %s by broker balancer %s", brokerBalancer.getName(), target));

Review comment:
       Are the args possibly reversed? Havent tried it, but the format string seems to read more like the balancer name is expected to be second/last?
   
   Either way, the toString() on Target seems like this might result in including a bunch of config/names some might consider 'internal' to the broker setup into the description. Or perhaps just not entirely relevant to an AMQP client/user that doesnt use them. 
   
   It might be simpler and clearer just to use the target host:port, which are already available here.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682840548



##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+      ConnectionFactory connectionFactoryClient0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0Server0.createConnection();
+         connectionProducer1 = connectionFactoryClient1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID());
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID());
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       I meant clientID prefix, I'll fix it.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683543041



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>
+</broker-balancers>

Review comment:
       CLIENT_ID target key added.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894247801


   @gemmellr I see your point, I'll try to reduce complexity (maybe not this release). Thanks a lot for your reviews and suggestions.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] clebertsuconic commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
clebertsuconic commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-893697648


   I only have two questions:
   
   I - I see a few trust stores changed as part of this PR? why?
   II - I didn't like the fact that you have to instantiate an AMQP Redirector for every connection created. even if there is no Load Balancer in place. Is there a way to pass the connection as an argument and do not instantiate it? Or check before you create the instance.. like only perform the check if a redirector is configured?   that will give it a hit on the regular path for AMQP Connections. It seems a small thing but I have seen perf issues associated with new instances in a lot of circunstances.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683542733



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>

Review comment:
       By default, the target key is SOURCE_IP and cache timeout is infinite.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682848946



##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       The broker balancer defined in the evenly-redirect example uses a cache based on the CLIENT_ID prefix key to provide affinity. I'll change the example to prove it.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657449528



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.

Review comment:
       I'll add further details to the redirection section




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gtully commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gtully commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867504123


   > Ok so thats a no then. ;) mgroups has to be flexible as typically grouping is done by a business key. Ill continue with the thing ive been working on then.
   
   If I understand correctly, that is about sharding producers that will set a groupId on messages? I guess this could be layered over a component of the clientId, using the group as a clientId prefix. Then sharding would be on some component of the clientID. key=clientId filter=<some regexp that extracts the groupd Id shard component>
   
   would that work for your use case?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867158673


   Ok so thats a no then. ;) needs to be mgroups has to be flexible as typically grouping is done by a business key. Ill continue with the thing ive been working on then.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-869718754


   I have just pushed a commit to add the `CLIENT_ID` target key. Now the broker balancer can use the jms client ID to distribute the incoming client connections across multiple brokers.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-893873713


   @clebertsuconic I have regenerate security resources after adding other server names to the `build.sh` script. I have just pushed a commit to avoid creating new redirect objects if not required.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683545202



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      final String localHostname = "localhost.localdomain";
+
+      assumeLocalHostname(localHostname);

Review comment:
       Now the test is executed at least with CORE protocol

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      final String localHostname = "localhost.localdomain";
+
+      assumeLocalHostname(localHostname);
+
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "server-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "securepass");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, localHostname,
+         TransportConstants.DEFAULT_PORT + 0, null, null, null);
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+
+         connection.setExceptionListener(exception -> {
+            return;

Review comment:
       removed




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682830416



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       I can set SNI value explicitly for CORE client. I'm not sure I can set SNI value explicitly for qpid jms client or openwire client.

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+      ConnectionFactory connectionFactoryClient0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0Server0.createConnection();
+         connectionProducer1 = connectionFactoryClient1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID());
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID());
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       I meant clientID prefix, I'll fix it.

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       The broker balancer defined int the evenly-redirect example uses a cache based on the CLIENT_ID key to provide affinity. I'll change the example to prove it.

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       The broker balancer defined in the evenly-redirect example uses a cache based on the CLIENT_ID prefix key to provide affinity. I'll change the example to prove it.

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       I have just pushed a commit to skip this test if `localhost.localdomain` is not valid.

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");

Review comment:
       keystore replaced

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers

Review comment:
       title fixed

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how you can distribute incoming client connections across two brokers using a symmetric architecture.

Review comment:
       I have added a few words about the 'symmetric architecture'

##########
File path: examples/features/broker-balancer/pom.xml
##########
@@ -0,0 +1,62 @@
+<?xml version='1.0'?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.apache.activemq.examples.clustered</groupId>
+      <artifactId>broker-features</artifactId>
+      <version>2.18.0-SNAPSHOT</version>
+   </parent>
+
+   <groupId>org.apache.activemq.examples</groupId>
+   <artifactId>broker-balancer</artifactId>
+   <packaging>pom</packaging>
+   <name>ActiveMQ Artemis Broker Balancer Examples</name>
+
+   <!-- Properties -->
+   <properties>
+      <!--
+      Explicitly declaring the source encoding eliminates the following
+      message: [WARNING] Using platform encoding (UTF-8 actually) to copy
+      filtered resources, i.e. build is platform dependent!
+      -->
+      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

Review comment:
       removed

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       I missed to commit the updated example. Now it is updated and it uses `<target-key-filter>^.{3}</target-key-filter>`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657451663



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum numbers of ready tagrets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <quorum-size>2</quorum-size>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool;

Review comment:
       I can't find a better name so I used `FIRST_ELEMENT` to be consistent with the similar client load balancing policy: org.apache.activemq.artemis.api.core.client.loadbalance.FirstElementConnectionLoadBalancingPolicy




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r659877781



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());

Review comment:
       Just adding the condition name again is a pretty unhelpful description. Clients will likely print both. Might be nicer to include something in the description giving context for the reason, aiding users to know whats going on, like 'Balancer is redirecting...'

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the description as the condition. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to be why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));

Review comment:
       Although the spec amusingly does not specify a specific type, I would probably default to sending a numeric type for 'port'. I'd just go with integer personally (or UnsignedInteger after that, but I tend to avoid the unsigned types personally)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683604937



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      final String localHostname = "localhost.localdomain";
+
+      assumeLocalHostname(localHostname);

Review comment:
       Not quite what I was suggesting but hopefully does the trick with the fallbacks :)
   
   (I was suggesting, have the core client connect to "localhost" but override the SNI to something else - like "localhost.localdomain" as the cert already matches that too)




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-892463379


   @clebertsuconic I have just rebased this PR but it depends on #3562 PR.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683294132



##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       I missed to commit the updated example. Now it is updated and it uses `<target-key-filter>^.{3}</target-key-filter>`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-868710253


   @gtully not really. The keys are business keys, we want to shard on that, akin to why you may want to use kafka partition keys not tied to the client at all. I can go over offline whats the requirements were trying to achieve if you wanted sometime . Theres actually a nice implementation in the old fabric8 that im looking at pulling across, update and enhance. Whats really nice is with the zk quorum stuff it means we can reuse on that too.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683290742



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");

Review comment:
       keystore replaced




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683366454



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      final String localHostname = "localhost.localdomain";
+
+      assumeLocalHostname(localHostname);

Review comment:
       Personally I'd still prefer a test that ran everywhere connecting to localhost (with non-localhost SNI with Core client possible), over a test that needs checking if it ran. A unit test could probably also be used to ensure the connection is passed to the validator, and that it sees non-"localhost" values pass through from the connection.

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      final String localHostname = "localhost.localdomain";
+
+      assumeLocalHostname(localHostname);
+
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "server-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "securepass");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, localHostname,
+         TransportConstants.DEFAULT_PORT + 0, null, null, null);
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+
+         connection.setExceptionListener(exception -> {
+            return;

Review comment:
       Why was this no-op just added? Did you mean to add a check it didnt fire?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683291747



##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how you can distribute incoming client connections across two brokers using a symmetric architecture.

Review comment:
       I have added a few words about the 'symmetric architecture'




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683611191



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>

Review comment:
       I don't recall seeing those values mentioned in the docs, might be worth adding, or making them more obvious if there.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gtully commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gtully commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657263437



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.

Review comment:
       it is just reachable. full stop. Does it really need to host a balancer?

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:

Review comment:
       client connection (not plural)

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.

Review comment:
       what happens when the quorum is set and not reached? Does the connection just get rejected? expecting a retry?

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.

Review comment:
       is it just quorum (the size is implicit, as in quorum is the minimum number of members that make the group valid.

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum numbers of ready tagrets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <quorum-size>2</quorum-size>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool;
+* `ROUND_ROBIN` to select a target sequentially from a pool.
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key until the target key is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `local-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>
+</broker-balancers>
+```
+
+## Broker Balancer Workflow
+The broker balancer workflow include the following steps:
+* Retrieve the target key from the incoming connection;
+* Return the local target broker if the target key matches the local filter;
+* Return the cached target broker if it is ready;
+* Get ready target brokers from the pool;
+* Select one target broker using the policy;
+* Add the selected broker in the cache;
+* Return the selected broker.
+
+Let's take a look at flowchart of the broker balancer workflow:
+![Broker Balancer Workflow](images/broker_balancer_workflow.png)
+
+
+## Redirection
+Apache ActiveMQ Artemis provides a native redirection for supported clients and a new management API for other clients.
+The native redirection can be enabled per acceptor and is supported only for CORE and AMQP clients.
+The acceptor with the `redirect-to` url parameter will redirect the incoming connections.
+The `redirect-to` url parameter specifies the name of the broker balancer to use,
+ie the following acceptor will redirect the incoming CORE client connections using the broker balancer with the name `bb1`:

Review comment:
       maybe it makes sense to reuse the name from above. in place of bb1 use 'consistent-hash-balancer' just to tie the url parameter to the name element of the xml. If I have that correct!

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum numbers of ready tagrets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <quorum-size>2</quorum-size>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool;
+* `ROUND_ROBIN` to select a target sequentially from a pool.
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key until the target key is present in the cache and is ready.

Review comment:
       until? should that be "as long as"

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum numbers of ready tagrets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <quorum-size>2</quorum-size>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool;

Review comment:
       the _ELEMENT seems odd? FIRST on it's own or HEAD (but that implies a list). Can you add a one liner when FIRST would make sense, ROUND_ROBIN with a single entry in a pool would behave the same.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r659892559



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the condition as the description. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to be why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r660030263



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Oops misread diff, that else bit is when target==null. General sentiment of 'give a more useful error description' still applies, i.e give some detail so poor user can perhaps understand and maybe help themselves if they did something wrong. As is a client is likely to just retry, possibly in a loop if this case repeats, with no real indication whats going on.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682718787



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       Using "localhost.localdomain" can sometimes be problematic in some environments. I'd consider just using localhost for the connections. 
   
   For the Core client, I think you can specify the SNI value explicitly, so you could still set it to something entirely different in that case if wanting to verify a non-localhost SNI value is picked up by the policy at the server.

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how you can distribute incoming client connections across two brokers using a symmetric architecture.

Review comment:
       Perhaps expand on what the 'symmetric architecture' is? I honestly have no clear idea from the description at this point what the example is about to show.
   
   (EDIT: so its showing that both brokers are set up to do a consistent hash of ClientID, such that each will direct the same ClientIDs to the same place, perhaps itself...which per the other comments, isnt actually great for matching specific producers to specific consumers as different connections arent allowed to use the same ClientID at the same time....but it will be consistent in what goes where)

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.

Review comment:
       ```suggestion
   By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
   ```
   Moving 'target' for clarity, as it isnt a 'target broker' yet if it isnt in the pool, which is whats explained next.

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing to have 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.

Review comment:
       ```suggestion
   * the `target-key` element defines what key to select a target broker, the supported values are: `SNI_HOST`, `SOURCE_IP`, `USER_NAME`, `CLIENT_ID`.
   ```
   Missing CLIENT_ID
   

##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");

Review comment:
       The verified-localdomain-keystore.jks doesnt seem to have instructions for creation. Small tidyup to bring into place with your other recent PR?

##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers

Review comment:
       Incorrect title

##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# AMQP Broker Connection with Receivers

Review comment:
       Title needs fixed

##########
File path: examples/features/broker-balancer/pom.xml
##########
@@ -0,0 +1,62 @@
+<?xml version='1.0'?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+   <modelVersion>4.0.0</modelVersion>
+
+   <parent>
+      <groupId>org.apache.activemq.examples.clustered</groupId>
+      <artifactId>broker-features</artifactId>
+      <version>2.18.0-SNAPSHOT</version>
+   </parent>
+
+   <groupId>org.apache.activemq.examples</groupId>
+   <artifactId>broker-balancer</artifactId>
+   <packaging>pom</packaging>
+   <name>ActiveMQ Artemis Broker Balancer Examples</name>
+
+   <!-- Properties -->
+   <properties>
+      <!--
+      Explicitly declaring the source encoding eliminates the following
+      message: [WARNING] Using platform encoding (UTF-8 actually) to copy
+      filtered resources, i.e. build is platform dependent!
+      -->
+      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

Review comment:
       Dont think this is needed, the apache and artemis parent poms both look to be setting it already. Certainly the comment can go.

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.

Review comment:
       Doesnt seem to match with the readme.

##########
File path: examples/features/broker-balancer/symmetric-redirect/src/main/java/org/apache/activemq/artemis/jms/example/SymmetricRedirectExample.java
##########
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class SymmetricRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+      ConnectionFactory connectionFactoryClient0Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1Server1 = new ActiveMQConnectionFactory("tcp://localhost:61617?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0Server0.createConnection();
+         connectionProducer1 = connectionFactoryClient1Server0.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue" + connectionProducer.getClientID());
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               TextMessage message = session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID());
+               System.out.println("Sending message " + message.getText() + "/" + connectionProducer.getClientID());
+               sender.send(message);
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       ```suggestion
          * the server1 will redirect the connection to the same target broker of the respective producer
          * from earlier as the new consumer connection uses the same ClientID.
   ```
   The server is wrong, they connect to server 1 this time.
   
   Avoiding saying 'share the same ClientID' since only one connection at a time can use a ClientID (so a real application probably couldnt use this precise example setup of matching-clientid, but some other setup...unless they could coordinate when the producer and consumer connections would be around, at which point they dont really need a broker)

##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from a pool. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing to have 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.

Review comment:
       ```suggestion
   * `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
     according to the priority defined with their sequence order, ie supposing there are 2 target brokers
     this policy selects the second target broker only when the first target broker isn't ready.
   ```

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       Actually, as this uses 2 different ClientIDs but is doing 'least connections', is the ClientID relevant? When the second set of connections happens...what guarantee is it that they go to the same place as the producer if it is only doing 'least connections' balance and both servers have 0? Would it work as described if I changed the order of connection creation on the second round?

##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       ```suggestion
          * the server0 will redirect the connection to the same target broker of the respective producer
          * from earlier as the new consumer connection uses the same ClientID.
   ```
   
   Avoiding saying 'share the same ClientID' since only one connection at a time can use a ClientID 




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867136603


   @michaelandrepearce 
   > Is it possible that this can be used to shard an address across brokers and have clients send to different brokers based on mgroups via a consistent hash? E.g. client has smarts to send mgroup A to broker 1 mgroup B to broker 3 and mgroup C to broker 2 for example where the mgroup to broker is by consistent hash
   
   The client connections can be distributed across brokers using a consistent hash based on USER_NAME. So supposed to match the client users with the mgroups then each client is redirected to the broker with the hash code closest to the hash code of client user/mgroup.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682830416



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       I can set SNI value explicitly for CORE client. I'm not sure I can set SNI value explicitly for qpid jms client or openwire client.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] clebertsuconic commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
clebertsuconic commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894226032


   @gemmellr I think it's pretty simple... the redirectHandler will do such check, and then create a new instance on the context when needed.
   
   You could make use of some static classes to avoid an initial creation, but it does not make a difference on this case since it's only one instance per acceptor.
   
   I will merge this now
   
   
   (However I will  amend the JIRA on the security artifacts change)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683291104



##########
File path: examples/features/broker-balancer/symmetric-redirect/readme.md
##########
@@ -0,0 +1,5 @@
+# AMQP Broker Connection with Receivers

Review comment:
       title fixed




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r660006283



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       @gemmellr yes, the redirect to the local target is a pass through. Indeed if target.isLocal() then redirected = false and the connection is managed like any old connection would without the balancer, ie the `RedirectTest#testSymmetricRedirect` test uses the local targets:
   https://github.com/brusdev/activemq-artemis/blob/broker_balancers/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/RedirectTest.java#L221

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +474,46 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         BrokerBalancer brokerBalancer = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo());
+         Target target = brokerBalancer.getTarget(transportConnection,
+            connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(String.format("Connection redirected to %s by broker balancer %s", brokerBalancer.getName(), target));

Review comment:
       yes the args are reversed. I'll replace the target.toString() with host:port




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683245043



##########
File path: tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/balancing/TargetKeyTest.java
##########
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.artemis.tests.integration.balancing;
+
+import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
+import org.apache.activemq.artemis.core.server.balancing.policies.FirstElementPolicy;
+import org.apache.activemq.artemis.core.server.balancing.policies.Policy;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactory;
+import org.apache.activemq.artemis.core.server.balancing.policies.PolicyFactoryResolver;
+import org.apache.activemq.artemis.core.server.balancing.targets.Target;
+import org.apache.activemq.artemis.core.server.balancing.targets.TargetKey;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+@RunWith(Parameterized.class)
+public class TargetKeyTest extends BalancingTestBase {
+
+   private static final String MOCK_POLICY_NAME = "MOCK_POLICY";
+
+   @Parameterized.Parameters(name = "protocol: {0}")
+   public static Collection<Object[]> data() {
+      Collection<Object[]> data = new ArrayList<>();
+
+      for (String protocol : Arrays.asList(new String[] {AMQP_PROTOCOL, CORE_PROTOCOL, OPENWIRE_PROTOCOL})) {
+         data.add(new Object[] {protocol});
+      }
+
+      return data;
+   }
+
+
+   private final String protocol;
+
+   private final List<String> keys = new ArrayList<>();
+
+
+   public TargetKeyTest(String protocol) {
+      this.protocol = protocol;
+   }
+
+   @Before
+   public void setup() throws Exception {
+      PolicyFactoryResolver.getInstance().registerPolicyFactory(
+         new PolicyFactory() {
+            @Override
+            public String[] getSupportedPolicies() {
+               return new String[] {MOCK_POLICY_NAME};
+            }
+
+            @Override
+            public Policy createPolicy(String policyName) {
+               return new FirstElementPolicy(MOCK_POLICY_NAME) {
+                  @Override
+                  public Target selectTarget(List<Target> targets, String key) {
+                     keys.add(key);
+                     return super.selectTarget(targets, key);
+                  }
+               };
+            }
+         });
+   }
+
+   @Test
+   public void testClientIDKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      setupBalancerServerWithDiscovery(0, TargetKey.CLIENT_ID, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, false, TransportConstants.DEFAULT_HOST,
+         TransportConstants.DEFAULT_PORT + 0, "test", null, null);
+
+      keys.clear();
+
+      try (Connection connection = connectionFactory.createConnection()) {
+         connection.start();
+      }
+
+      Assert.assertEquals(1, keys.size());
+      Assert.assertEquals("test", keys.get(0));
+   }
+
+   @Test
+   public void testSNIHostKey() throws Exception {
+      setupLiveServerWithDiscovery(0, GROUP_ADDRESS, GROUP_PORT, true, true, false);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PATH_PROP_NAME, "verified-localdomain-keystore.jks");
+      getDefaultServerAcceptor(0).getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "secureexample");
+
+      setupBalancerServerWithDiscovery(0, TargetKey.SNI_HOST, MOCK_POLICY_NAME, null, true, null, 1);
+      startServers(0);
+
+      ConnectionFactory connectionFactory = createFactory(protocol, true, "localhost.localdomain",

Review comment:
       You cant for Qpid JMS, dont know for openwire.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657449151



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.
+This behaviour avoids weird distribution at startup or after a restart.

Review comment:
       if the quorum is not reached and the target key is not present in the cache then the connection is rejected




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894143709


   I dont think the keystore changes should using NO-JIRA in their log, at least some are being made directly for this JIRA so it makes sense for it to be reflected in the commit log.
   
   I think Clebert was looking to avoid creating the redirect handler objects entirely, which the updated version doesnt appear to. It still looks to affect every connection, but instead of with the throwaway handler, by adding a new field and creating the handler up front, then just possibly not using it. In some ways this is actually worse than previous version.
   
   I think there is a nicer route in-between, but nearer the earlier version 2212d02f206bbdf9916db225e876eef4583c1326 [1], where it simply checks the redirect-to value on the connection first, and only then proceeds to create and use the handler if there was a need. E.g changes from the previous version for AMQP could maybe have been something like this instead (+add similar for other protocols):
   
   ```
   @@ -528,6 +528,5 @@ public class AMQPConnectionContext extends ProtonInitializable implements EventH
    
   -      AMQPRedirectHandler redirectHandler = new AMQPRedirectHandler(protocolManager.getServer(),
   -         connectionCallback, connection, handler.getSASLResult() != null ? handler.getSASLResult().getUser() : null);
   +      final boolean tryRedirect = connectionCallback.getTransportConnection().getRedirectTo() != null;
    
   -      if (redirectHandler.redirect() || !validateConnection(connection)) {
   +      if (tryRedirect && redirect(connection) || !validateConnection(connection)) {
             connection.close();
   @@ -557,2 +556,9 @@ public class AMQPConnectionContext extends ProtonInitializable implements EventH
    
   +   private final boolean redirect(Connection connection) throws Exception {
   +      AMQPRedirectHandler redirectHandler = new AMQPRedirectHandler(protocolManager.getServer(),
   +            connectionCallback, connection, handler.getSASLResult() != null ? handler.getSASLResult().getUser() : null);
   +
   +      return redirectHandler.redirect();
   +   }
   +
       class ScheduleOperator implements UnaryOperator<Future<?>> {
   ```
   
   
   [1]  I still had the the 2212d02f206bbdf9916db225e876eef4583c1326 version locally, I put it at https://github.com/gemmellr/activemq-artemis/tree/balancer-pr3634-old1 in case you should want it.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657472546



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connections, the supported values are:
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of brokers and checks periodically their state.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections. 
+By default, a pool doesn't include the local target broker, to include it the `local-target-enabled` parameter must be `true`.
+A pool becomes ready when the minimum number of ready targets defined by the `quorum-size` parameter is reached.

Review comment:
       I used the `quorum-size` name just to be consistent with other parameter names, see replicatedPolicyType and replicaPolicyType.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r659892559



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the condition as the description. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to me why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683710314



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.
+By default, a pool doesn't include the local broker, to include it as a target the `local-target-enabled` parameter must be `true`.
+There are two pool types: [discovery pool](#discovery-pool) and [static pool](#static-pool).
+
+### Discovery Pool
+The discovery pool uses a [discovery group](clusters.md#discovery-groups) to discover the target brokers to add.
+Let's take a look at a discovery pool example from broker.xml that uses a discovery group:
+```xml
+<pool>
+    <discovery-group-ref discovery-group-name="dg1"/>
+</pool>
+```
+
+### Static Pool
+The static pool uses a list of static connectors to define the target brokers to add.
+Let's take a look at a static pool example from broker.xml that uses a list of static connectors:
+```xml
+<pool>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+### Defining pools
+A pool is defined by the `pool` element that includes the following items:
+* the `username` element defines the username to connect to the target broker;
+* the `password` element defines the password to connect to the target broker;
+* the `check-period` element defines the often to check the target broker;
+* the `quorum-size` element defines the minimum number of ready targets to activate the pool;
+* the `quorum-timeout` element defines the timeout to get the minimum number of ready targets;
+* the `local-target-enabled` element defines whether the pool has to include a local target;
+* the `static-connectors` element defines a list of static connectors used by the [static pool](#static-pool);
+* the `discovery-group` element defines the [discovery group](clusters.md#discovery-groups) used by the [discovery pool](#discovery-pool).
+
+Let's take a look at a pool example from broker.xml:
+```xml
+<pool>
+    <quorum-size>2</quorum-size>
+    <check-period>1000</check-period>
+    <local-target-enabled>true</local-target-enabled>
+    <static-connectors>
+        <connector-ref>connector1</connector-ref>
+        <connector-ref>connector2</connector-ref>
+        <connector-ref>connector3</connector-ref>
+    </static-connectors>
+</pool>
+```
+
+## Policies
+The policy define how to select a broker from a pool. The included policies are:
+* `FIRST_ELEMENT` to select the first target broker from the pool which is ready. It is useful to select the ready target brokers
+  according to the priority defined with their sequence order, ie supposing there are 2 target brokers
+  this policy selects the second target broker only when the first target broker isn't ready.
+* `ROUND_ROBIN` to select a target sequentially from a pool, this policy is useful to evenly distribute;
+* `CONSISTENT_HASH` to select a target by a key. This policy always selects the same target broker for the same key until it is removed from the pool.
+* `LEAST_CONNECTIONS` to select the targets with the fewest active connections. This policy helps you maintain an equal distribution of active connections with the target brokers.
+
+A policy is defined by the `policy` element. Let's take a look at a policy example from broker.xml:
+```xml
+<policy name="FIRST_ELEMENT"/>
+```
+
+## Cache
+The broker balancer provides a cache with a timeout to improve the stickiness of the target broker selected.
+The broker balancer returns the same target broker for a target key as long as it is present in the cache and is ready.
+By default, the cache is enabled, to disable the cache the `cache-timeout` parameter must be `0`.
+
+## Defining broker balancers
+A broker balancer is defined by `broker-balancer` element, it includes the following items:
+* the `name` attribute defines the name of the broker balancer;
+* the `target-key` element defines what key to select a target broker, the supported values are: `CLIENT_ID`, `SNI_HOST`, `SOURCE_IP`, `USER_NAME`.
+* the `target-key-filter` element defines a regular expression to filter the resolved keys;
+* the `local-target-filter` element defines a regular expression to filter the keys that have to return a local target;
+* the `cache-timeout` element is the time period for a target broker to remain in the cache;
+* the `pool` element defines the pool to group the target brokers, see [pools](#pools).
+* the `policy` element defines the policy used to select the target brokers, see [policies](#policies);
+
+Let's take a look at some broker balancer examples from broker.xml:
+```xml
+<broker-balancers>
+    <broker-balancer name="simple-balancer">
+        <policy name="FIRST_ELEMENT"/>
+        <pool>
+            <static-connectors>
+                <connector-ref>connector1</connector-ref>
+                <connector-ref>connector2</connector-ref>
+                <connector-ref>connector3</connector-ref>
+            </static-connectors>
+        </pool>
+    </broker-balancer>
+    <broker-balancer name="consistent-hash-balancer">
+        <target-key>USER_NAME</target-key>
+        <local-filter>admin</local-filter>
+        <policy name="CONSISTENT_HASH"/>
+        <pool>
+            <local-target-enabled>true</local-target-enabled>
+            <discovery-group-ref discovery-group-name="dg1"/>
+        </pool>
+    <policy name="CONSISTENT_HASH"/>
+    </broker-balancer>
+    <broker-balancer name="least-connections-balancer">
+        <policy name="LEAST_CONNECTIONS"/>
+        <pool>
+            <discovery-group-ref discovery-group-name="dg2"/>
+        </pool>
+    </broker-balancer>

Review comment:
       doc updated

##########
File path: examples/features/broker-balancer/evenly-redirect/readme.md
##########
@@ -0,0 +1,6 @@
+# Evenly Redirect Example
+
+To run the example, simply type **mvn verify** from this directory, or **mvn -PnoServer verify** if you want to create and start the broker manually.
+
+This example demonstrates how incoming client connections are evenly redirected across two brokers
+using a third broker with a broker balancer to redirect incoming client connections.

Review comment:
       doc updated




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r683542647



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,176 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+### This feature is still **EXPERIMENTAL** and not meant to be run in production yet. Furthermore, its configuration can change until declared as **officially stable**.
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another reachable broker.
+
+## Target Key
+The broker balancer uses a target key to select a target broker.
+It is a string retrieved from an incoming client connection, the supported values are:
+* `CLIENT_ID` is the JMS client ID;
+* `SNI_HOST` is the hostname indicated by the client in the SNI extension of the TLS protocol;
+* `SOURCE_IP` is the source IP address of the client;
+* `USER_NAME` is the username indicated by the client.
+
+## Pools
+The pool is a group of target brokers and checks periodically their state.
+It provides a list of ready target brokers to distribute incoming client connections only when it is active.
+A pool becomes active when the minimum number of ready target brokers defined by the `quorum-size` parameter is reached.
+When it is not active, it doesn't provide any target avoiding weird distribution at startup or after a restart.
+Including the local target broker in the pool allows broker hosting the broker balancer to accept incoming client connections.

Review comment:
       updated




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gtully commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gtully commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r657277193



##########
File path: docs/user-manual/en/broker-balancers.md
##########
@@ -0,0 +1,156 @@
+# Broker Balancers
+Apache ActiveMQ Artemis broker balancers allow incoming client connections to be distributed across multiple [target brokers](target-brokers).
+The target brokers are grouped in [pools](#pools) and the broker balancers use a [target key](#target-key)
+to select a target broker from a pool of brokers according to a [policy](#policies).
+
+## Target Broker
+Target broker is a broker that can accept incoming client connections and is local or remote.
+The local target is a special target that represents the same broker hosting the broker balancer.
+The remote target is another broker reachable by the broker that hosts the broker balancer.

Review comment:
       that comment is for line 9.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r659877781



##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());

Review comment:
       Just adding the condition name again is a pretty unhelpful description. Clients will likely print both. Might be nicer to include something in the description giving context for the reason, aiding users to know whats going on, like 'Balancer is redirecting...'

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the description as the condition. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to be why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));

Review comment:
       Although the spec amusingly does not specify a specific type, I would probably default to sending a numeric type for 'port'. I'd just go with integer personally (or UnsignedInteger after that, but I tend to avoid the unsigned types personally)

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the condition as the description. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to be why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Again, not particularly helpful setting the condition as the description. Perhaps some context on the problem to help. Why did this happen, what can poor confused user do about it etc.
   
   What is a 'local redirect' even? EDIT: According to the docs later in the diff, its a redirect to the broker doing the balancing/redirects, and there seems to be an explicit toggle to enable this situation to happen. As such its not clear to me why this is set up as a failure case causing the connection to be forced closed without explanation. Shouldnt it simply succeed, like any old connection would without the balancer?

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +473,45 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         Target target = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo())
+            .getTarget(transportConnection, connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(ConnectionError.REDIRECT.toString());
+               Map<Symbol, String> info = new HashMap<>();
+               info.put(AmqpSupport.NETWORK_HOST, host);
+               info.put(AmqpSupport.PORT, Integer.toString(port));
+               error.setInfo(info);
+               connection.setCondition(error);
+
+               redirected = true;
+            }
+         } else {
+            ActiveMQServerLogger.LOGGER.cannotRedirectClientConnection(transportConnection);
+
+            ErrorCondition error = new ErrorCondition();
+            error.setCondition(ConnectionError.CONNECTION_FORCED);
+            error.setDescription(ConnectionError.CONNECTION_FORCED.toString());

Review comment:
       Oops misread diff, that else bit is when target==null. General sentiment of 'give a more useful error description' still applies, i.e give some detail so poor user can perhaps understand and maybe help themselves if they did something wrong. As is a client is likely to just retry, possibly in a loop if this case repeats, with no real indication whats going on.

##########
File path: artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/proton/AMQPConnectionContext.java
##########
@@ -469,7 +474,46 @@ public void onRemoteOpen(Connection connection) throws Exception {
       } catch (Exception e) {
          log.error("Error init connection", e);
       }
-      if (!validateConnection(connection)) {
+
+      boolean redirected = false;
+      if (connectionCallback.getTransportConnection().getRedirectTo() != null) {
+         org.apache.activemq.artemis.spi.core.remoting.Connection transportConnection = connectionCallback.getTransportConnection();
+         BrokerBalancer brokerBalancer = protocolManager.getServer().getBalancerManager()
+            .getBalancer(transportConnection.getRedirectTo());
+         Target target = brokerBalancer.getTarget(transportConnection,
+            connection.getRemoteContainer(), handler.getSASLResult().getUser());
+
+         if (target != null) {
+            ActiveMQServerLogger.LOGGER.redirectClientConnection(transportConnection, target);
+
+            if (!target.isLocal()) {
+               String host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, target.getConnector().getParams());
+               int port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, target.getConnector().getParams());
+
+               ErrorCondition error = new ErrorCondition();
+               error.setCondition(ConnectionError.REDIRECT);
+               error.setDescription(String.format("Connection redirected to %s by broker balancer %s", brokerBalancer.getName(), target));

Review comment:
       Are the args possibly reversed? Havent tried it, but the format string seems to read more like the balancer name is expected to be second/last?
   
   Either way, the toString() on Target seems like this might result in including a bunch of config/names some might consider 'internal' to the broker setup into the description. Or perhaps just not entirely relevant to an AMQP client/user that doesnt use them. 
   
   It might be simpler and clearer just to use the target host:port, which are already available here.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-868710253


   @gtully not really. The keys are business keys, we want to shard on that, akin to why you may want to use kafka partition keys not tied to the client at all. Theres actually a nice implementation in the old fabric8 that im looking at pulling across, update and enhance.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-868710253


   @gtully not really. The keys are business keys, we want to shard on that, akin to why you may want to use kafka partition keys not tied to the client at all. Theres actually a nice implementation in the old fabric8 that im looking at pulling across, update and enhance. Whats really nice is with the zk quorum stuff it means we can reuse on that too.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] brusdev commented on a change in pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
brusdev commented on a change in pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#discussion_r682848946



##########
File path: examples/features/broker-balancer/evenly-redirect/src/main/java/org/apache/activemq/artemis/jms/example/EvenlyRedirectExample.java
##########
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.artemis.jms.example;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+
+/**
+ * This example is demonstrating how incoming client connections are evely redirected from one broker towards
+ * worker brokers.
+ */
+public class EvenlyRedirectExample {
+
+   public static void main(final String[] args) throws Exception {
+
+      ConnectionFactory connectionFactoryClient0 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_0");
+      ConnectionFactory connectionFactoryClient1 = new ActiveMQConnectionFactory("tcp://localhost:61616?ha=true&reconnectAttempts=30&clientID=CLIENT_1");
+
+      /**
+       * Step 1. Create a connection for producer0 and producer1, and send a few messages.
+       * the server0 will redirect the connection of each producer to a different target brokers.
+       */
+      Connection connectionProducer0 = null;
+      Connection connectionProducer1 = null;
+
+      try {
+         connectionProducer0 = connectionFactoryClient0.createConnection();
+         connectionProducer1 = connectionFactoryClient1.createConnection();
+
+         for (Connection connectionProducer : new Connection[] {connectionProducer0, connectionProducer1}) {
+            Session session = connectionProducer.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+            Queue queue = session.createQueue("exampleQueue");
+            MessageProducer sender = session.createProducer(queue);
+            for (int i = 0; i < 100; i++) {
+               sender.send(session.createTextMessage("Hello world n" + i + " - " + connectionProducer.getClientID()));
+            }
+         }
+      } finally {
+         if (connectionProducer0 != null) {
+            connectionProducer0.close();
+         }
+
+         if (connectionProducer1 != null) {
+            connectionProducer1.close();
+         }
+      }
+
+      /**
+       * Step 2. create a connection for consumer0 and consumer1, and receive a few messages.
+       * the server0 will redirect the connection to the same target broker of the respective producer
+       * because the consumer and the producer share the same clientID.

Review comment:
       The broker balancer defined int the evenly-redirect example uses a cache based on the CLIENT_ID key to provide affinity. I'll change the example to prove it.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] michaelandrepearce edited a comment on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
michaelandrepearce edited a comment on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-867158673


   Ok so thats a no then. ;) mgroups has to be flexible as typically grouping is done by a business key. Ill continue with the thing ive been working on then.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] gemmellr commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
gemmellr commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-894166518


   Ah, so @brusdev nudged me toward the fact the protocol manager isnt created per-connection, so there is indeed now less of the handlers being made with this version, with it now being the new contexts created per-connection and passed around to the existing handler, only after the check of 'redirect-to' presence.
   
   I'd say I still prefer the simpler code from before just creating the handler, but only when its needed per the above suggestion.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [activemq-artemis] clebertsuconic commented on pull request #3634: ARTEMIS-3365 Broker Balancers

Posted by GitBox <gi...@apache.org>.
clebertsuconic commented on pull request #3634:
URL: https://github.com/apache/activemq-artemis/pull/3634#issuecomment-892202641


   @brusdev rebase it please?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: gitbox-unsubscribe@activemq.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org