This is an automated email from the ASF dual-hosted git repository.

ShannonDing pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/rocketmq.git


The following commit(s) were added to refs/heads/develop by this push:
     new 78fb83c197 [ISSUE #11565] Honor the target broker in mqadmin 
sendMessage (#11566)
78fb83c197 is described below

commit 78fb83c197c78c096175dac89feaad1bbb84443f
Author: Wiedbol <[email protected]>
AuthorDate: Mon Nov 23 18:59:16 2026 +0800

    [ISSUE #11565] Honor the target broker in mqadmin sendMessage (#11566)
    
    * [ISSUE #11565] Validate broker and queue options in mqadmin sendMessage
    
    * [ISSUE #11565] Route broker-only sends to the requested broker
---
 .../tools/command/message/SendMessageCommand.java  |  75 +++++++++-----
 .../command/message/SendMessageCommandTest.java    | 114 +++++++++++++++++++--
 2 files changed, 156 insertions(+), 33 deletions(-)

diff --git 
a/tools/src/main/java/org/apache/rocketmq/tools/command/message/SendMessageCommand.java
 
b/tools/src/main/java/org/apache/rocketmq/tools/command/message/SendMessageCommand.java
index bd9b7a8795..cfdc2d14d4 100644
--- 
a/tools/src/main/java/org/apache/rocketmq/tools/command/message/SendMessageCommand.java
+++ 
b/tools/src/main/java/org/apache/rocketmq/tools/command/message/SendMessageCommand.java
@@ -17,19 +17,24 @@
 
 package org.apache.rocketmq.tools.command.message;
 
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.stream.Collectors;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.Option;
 import org.apache.commons.cli.Options;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.rocketmq.client.exception.MQClientException;
 import org.apache.rocketmq.client.producer.DefaultMQProducer;
 import org.apache.rocketmq.client.producer.SendResult;
+import org.apache.rocketmq.common.MixAll;
 import org.apache.rocketmq.common.message.Message;
 import org.apache.rocketmq.common.message.MessageQueue;
 import org.apache.rocketmq.remoting.RPCHook;
 import org.apache.rocketmq.tools.command.SubCommand;
 import org.apache.rocketmq.tools.command.SubCommandException;
 
-import java.nio.charset.StandardCharsets;
-
 public class SendMessageCommand implements SubCommand {
 
     private DefaultMQProducer producer;
@@ -62,11 +67,11 @@ public class SendMessageCommand implements SubCommand {
         opt.setRequired(false);
         options.addOption(opt);
 
-        opt = new Option("b", "broker", true, "Send message to target broker");
+        opt = new Option("b", "broker", true, "Target broker name. Without -i, 
select a writable queue on this broker.");
         opt.setRequired(false);
         options.addOption(opt);
 
-        opt = new Option("i", "qid", true, "Send message to target queue");
+        opt = new Option("i", "qid", true, "Target queue ID, a non-negative 
integer (requires -b)");
         opt.setRequired(false);
         options.addOption(opt);
 
@@ -89,13 +94,34 @@ public class SendMessageCommand implements SubCommand {
 
     @Override
     public void execute(CommandLine commandLine, Options options, RPCHook 
rpcHook) throws SubCommandException {
-        Message msg = null;
         String topic = commandLine.getOptionValue('t').trim();
+        String brokerName = StringUtils.trim(commandLine.getOptionValue('b'));
+        String queueIdValue = commandLine.getOptionValue('i');
+        if (brokerName != null && brokerName.isEmpty()) {
+            throw new SubCommandException("Option -b (--broker) must specify a 
broker name.");
+        }
+
+        MessageQueue targetQueue = null;
+        if (queueIdValue != null) {
+            if (brokerName == null) {
+                throw new SubCommandException("Option -i (--qid) requires -b 
(--broker).");
+            }
+            int queueId;
+            try {
+                queueId = Integer.parseInt(queueIdValue.trim());
+            } catch (NumberFormatException e) {
+                throw new SubCommandException("Option -i (--qid) must be a 
non-negative integer.", e);
+            }
+            if (queueId < 0) {
+                throw new SubCommandException("Option -i (--qid) must be a 
non-negative integer.");
+            }
+            targetQueue = new MessageQueue(topic, brokerName, queueId);
+        }
+
+        Message msg;
         String body = commandLine.getOptionValue('p');
         String tag = null;
         String keys = null;
-        String brokerName = null;
-        int queueId = -1;
         try {
             if (commandLine.hasOption('k')) {
                 keys = commandLine.getOptionValue('k').trim();
@@ -103,17 +129,6 @@ public class SendMessageCommand implements SubCommand {
             if (commandLine.hasOption('c')) {
                 tag = commandLine.getOptionValue('c').trim();
             }
-            if (commandLine.hasOption('b')) {
-                brokerName = commandLine.getOptionValue('b').trim();
-            }
-            if (commandLine.hasOption('i')) {
-                if (!commandLine.hasOption('b')) {
-                    System.out.print("Broker name must be set if the queue is 
chosen!");
-                    return;
-                } else {
-                    queueId = 
Integer.parseInt(commandLine.getOptionValue('i').trim());
-                }
-            }
             msg = new Message(topic, tag, keys, 
body.getBytes(StandardCharsets.UTF_8));
         } catch (Exception e) {
             throw new RuntimeException(this.getClass().getSimpleName() + " 
command failed", e);
@@ -126,13 +141,12 @@ public class SendMessageCommand implements SubCommand {
         SendResult result;
         try {
             producer.start();
-            if (brokerName != null && queueId > -1) {
-                MessageQueue messageQueue = new MessageQueue(topic, 
brokerName, queueId);
-                result = producer.send(msg, messageQueue);
-            } else {
-                result = producer.send(msg);
+            if (targetQueue == null && brokerName != null) {
+                targetQueue = selectQueueOnBroker(producer, topic, brokerName);
             }
-
+            result = targetQueue == null ? producer.send(msg) : 
producer.send(msg, targetQueue);
+        } catch (SubCommandException e) {
+            throw e;
         } catch (Exception e) {
             throw new RuntimeException(this.getClass().getSimpleName() + " 
command failed", e);
         } finally {
@@ -162,4 +176,17 @@ public class SendMessageCommand implements SubCommand {
             );
         }
     }
+
+    private MessageQueue selectQueueOnBroker(DefaultMQProducer producer, 
String topic, String brokerName)
+        throws MQClientException, SubCommandException {
+        // Static topic queues use logical names that do not pin a physical 
broker.
+        List<MessageQueue> queues = 
producer.fetchPublishMessageQueues(topic).stream()
+            .filter(queue -> brokerName.equals(queue.getBrokerName()))
+            .filter(queue -> 
!queue.getBrokerName().startsWith(MixAll.LOGICAL_QUEUE_MOCK_BROKER_PREFIX))
+            .collect(Collectors.toList());
+        if (queues.isEmpty()) {
+            throw new SubCommandException("No writable queue for topic %s on 
broker %s.", topic, brokerName);
+        }
+        return queues.get(ThreadLocalRandom.current().nextInt(queues.size()));
+    }
 }
diff --git 
a/tools/src/test/java/org/apache/rocketmq/tools/command/message/SendMessageCommandTest.java
 
b/tools/src/test/java/org/apache/rocketmq/tools/command/message/SendMessageCommandTest.java
index 88e793b8f8..2e748610fe 100644
--- 
a/tools/src/test/java/org/apache/rocketmq/tools/command/message/SendMessageCommandTest.java
+++ 
b/tools/src/test/java/org/apache/rocketmq/tools/command/message/SendMessageCommandTest.java
@@ -21,6 +21,8 @@ import java.io.ByteArrayOutputStream;
 import java.io.PrintStream;
 import java.lang.reflect.Field;
 import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -29,6 +31,7 @@ import org.apache.rocketmq.client.exception.MQClientException;
 import org.apache.rocketmq.client.producer.DefaultMQProducer;
 import org.apache.rocketmq.client.producer.SendResult;
 import org.apache.rocketmq.client.producer.SendStatus;
+import org.apache.rocketmq.common.MixAll;
 import org.apache.rocketmq.common.message.Message;
 import org.apache.rocketmq.common.message.MessageQueue;
 import org.apache.rocketmq.remoting.exception.RemotingException;
@@ -43,12 +46,14 @@ import org.mockito.ArgumentCaptor;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
 import static org.mockito.Mockito.when;
 
 public class SendMessageCommandTest {
 
-    private static SendMessageCommand sendMessageCommand = new 
SendMessageCommand();
+    private static SendMessageCommand sendMessageCommand;
 
     @BeforeClass
     public static void init() throws MQClientException, RemotingException, 
InterruptedException, MQBrokerException, NoSuchFieldException, 
IllegalAccessException {
@@ -64,9 +69,7 @@ public class SendMessageCommandTest {
         
when(defaultMQProducer.send(any(Message.class))).thenReturn(sendResult);
         when(defaultMQProducer.send(any(Message.class), 
any(MessageQueue.class))).thenReturn(sendResult);
 
-        Field producerField = 
SendMessageCommand.class.getDeclaredField("producer");
-        producerField.setAccessible(true);
-        producerField.set(sendMessageCommand, defaultMQProducer);
+        sendMessageCommand = commandWithProducer(defaultMQProducer);
     }
 
     @AfterClass
@@ -113,17 +116,101 @@ public class SendMessageCommandTest {
         assertMessageBody("message body", false);
     }
 
+    @Test
+    public void testExecuteSelectsWritableQueueOnRequestedBroker() throws 
Exception {
+        DefaultMQProducer producer = mock(DefaultMQProducer.class);
+        MessageQueue first = new MessageQueue("mytopic", "broker-a", 0);
+        MessageQueue second = new MessageQueue("mytopic", "broker-a", 1);
+        MessageQueue otherBroker = new MessageQueue("mytopic", "broker-b", 0);
+        
when(producer.fetchPublishMessageQueues("mytopic")).thenReturn(Arrays.asList(otherBroker,
 first, second));
+        when(producer.send(any(Message.class), 
any(MessageQueue.class))).thenAnswer(invocation ->
+            new SendResult(SendStatus.SEND_OK, "message-id", "offset-id", 
invocation.getArgument(1), 0));
+
+        executeWithTargetOptions(producer, "-b", "broker-a");
+
+        ArgumentCaptor<MessageQueue> queue = 
ArgumentCaptor.forClass(MessageQueue.class);
+        verify(producer).send(any(Message.class), queue.capture());
+        Assert.assertTrue(Arrays.asList(first, 
second).contains(queue.getValue()));
+        verify(producer, never()).send(any(Message.class));
+    }
+
+    @Test
+    public void testExecuteRejectsBrokerWithoutWritableQueue() throws 
Exception {
+        assertNoQueueOnBroker("broker-a", new MessageQueue("mytopic", 
"broker-b", 0));
+    }
+
+    @Test
+    public void testExecuteRejectsLogicalQueueInBrokerOnlyMode() throws 
Exception {
+        String logicalBroker = MixAll.LOGICAL_QUEUE_MOCK_BROKER_PREFIX + 
"scope";
+        assertNoQueueOnBroker(logicalBroker, new MessageQueue("mytopic", 
logicalBroker, 0));
+    }
+
+    @Test
+    public void testExecuteDoesNotFallBackWhenTargetQueueSendFails() throws 
Exception {
+        DefaultMQProducer producer = mock(DefaultMQProducer.class);
+        MessageQueue queue = new MessageQueue("mytopic", "broker-a", 0);
+        
when(producer.fetchPublishMessageQueues("mytopic")).thenReturn(Collections.singletonList(queue));
+        MQClientException failure = new MQClientException("Target broker 
unavailable", null);
+        when(producer.send(any(Message.class), eq(queue))).thenThrow(failure);
+
+        RuntimeException error = Assert.assertThrows(RuntimeException.class,
+            () -> executeWithTargetOptions(producer, "-b", "broker-a"));
+
+        Assert.assertSame(failure, error.getCause());
+        verify(producer, never()).send(any(Message.class));
+        verify(producer).shutdown();
+    }
+
+    @Test
+    public void testExecuteRejectsQueueWithoutBroker() throws Exception {
+        assertInvalidTarget("requires -b", "-i", "0");
+    }
+
+    @Test
+    public void testExecuteRejectsInvalidTargetQueue() throws Exception {
+        assertInvalidTarget("must be a non-negative integer", "-b", 
"broker-a", "-i", "-1");
+        assertInvalidTarget("must be a non-negative integer", "-b", 
"broker-a", "-i", "invalid");
+        assertInvalidTarget("must specify a broker name", "-b", " ");
+    }
+
+    private void assertNoQueueOnBroker(String broker, MessageQueue 
availableQueue) throws Exception {
+        DefaultMQProducer producer = mock(DefaultMQProducer.class);
+        
when(producer.fetchPublishMessageQueues("mytopic")).thenReturn(Collections.singletonList(availableQueue));
+
+        SubCommandException error = 
Assert.assertThrows(SubCommandException.class,
+            () -> executeWithTargetOptions(producer, "-b", broker));
+
+        Assert.assertTrue(error.getMessage(), error.getMessage().contains("No 
writable queue for topic mytopic on broker " + broker));
+        verify(producer, never()).send(any(Message.class));
+        verify(producer, never()).send(any(Message.class), 
any(MessageQueue.class));
+        verify(producer).shutdown();
+    }
+
+    private void assertInvalidTarget(String expectedError, String... 
targetOptions) throws Exception {
+        DefaultMQProducer producer = mock(DefaultMQProducer.class);
+        SubCommandException error = 
Assert.assertThrows(SubCommandException.class,
+            () -> executeWithTargetOptions(producer, targetOptions));
+        Assert.assertTrue(error.getMessage(), 
error.getMessage().contains(expectedError));
+        verifyNoInteractions(producer);
+    }
+
+    private void executeWithTargetOptions(DefaultMQProducer producer, 
String... targetOptions) throws Exception {
+        SendMessageCommand command = commandWithProducer(producer);
+        Options options = command.buildCommandlineOptions(new Options());
+        String[] arguments = new String[4 + targetOptions.length];
+        System.arraycopy(new String[] {"-t", "mytopic", "-p", "message body"}, 
0, arguments, 0, 4);
+        System.arraycopy(targetOptions, 0, arguments, 4, targetOptions.length);
+        CommandLine commandLine = new DefaultParser().parse(options, 
arguments);
+        command.execute(commandLine, options, null);
+    }
+
     private void assertMessageBody(String body, boolean sendToQueue) throws 
Exception {
-        SendMessageCommand command = new SendMessageCommand();
         DefaultMQProducer producer = mock(DefaultMQProducer.class);
+        SendMessageCommand command = commandWithProducer(producer);
         MessageQueue queue = new MessageQueue("mytopic", "broker-a", 1);
         SendResult result = new SendResult(SendStatus.SEND_OK, "message-id", 
"offset-id", queue, 0);
         when(producer.send(any(Message.class))).thenReturn(result);
         when(producer.send(any(Message.class), 
any(MessageQueue.class))).thenReturn(result);
-        Field producerField = 
SendMessageCommand.class.getDeclaredField("producer");
-        producerField.setAccessible(true);
-        producerField.set(command, producer);
-
         Options options = command.buildCommandlineOptions(new Options());
         String[] arguments = sendToQueue
             ? new String[] {"-t", "mytopic", "-p", body, "-b", "broker-a", 
"-i", "1"}
@@ -139,4 +226,13 @@ public class SendMessageCommandTest {
         }
         Assert.assertArrayEquals(body.getBytes(StandardCharsets.UTF_8), 
messageCaptor.getValue().getBody());
     }
+
+    private static SendMessageCommand commandWithProducer(DefaultMQProducer 
producer)
+        throws NoSuchFieldException, IllegalAccessException {
+        SendMessageCommand command = new SendMessageCommand();
+        Field producerField = 
SendMessageCommand.class.getDeclaredField("producer");
+        producerField.setAccessible(true);
+        producerField.set(command, producer);
+        return command;
+    }
 }

Reply via email to