Single quotes have to be backslash-escaped when using jboss-cli in non-interactive mode.

Recently I had to automate a cleanup task that used to be done manually in JBoss-CLI. More specifically, messages older than 1 month had to be removed from HornetQ and the script was supposed to be run periodically by a cron task. That last part, which seems like a trivial detail, actually proved to be the longest.

The management command

After a bit of fiddling with the interactive shell, I came up with the following management command :

/subsystem=messaging/hornetq-server=default/jms-queue=my.queue.name:remove-messages(filter="msg_functional_date LIKE '201712%'")

This has to be run for every queue. Fortunately jboss-cli.sh can be called from within a script with the --command argument :

You can use the --command argument to provide a single CLI command to execute. The management CLI will terminate once the commands have completed.

So I slapped together a crude shell script to do this:

port=27099;

lastMonthDate="`date +%Y-%m-01` -1 month"
lastMonth=`date --date="$lastMonthDate" +'%Y%m'`
tmpFile=`mktemp`

$JBOSS_HOME/bin/jboss-cli.sh  --connect controller=`hostname`:$port --command="/subsystem=messaging/hornetq-server=default:read-children-names(child-type=jms-queue)" | grep -Po '(?<=\s{4}")[^"]+(?=",)' | while read queue; do
    $JBOSS_HOME/bin/jboss-cli.sh  --connect controller=`hostname`:$port --command="/subsystem=messaging/hornetq-server=default/jms-queue=${queue}:remove-messages(filter=\"msg_functional_date LIKE '${lastMonth}%'\")"
done

And it completely failed.

JBoss-CLI and the filer syntax

When you pass an otherwise valid filter expression to jboss-cli through the --command argument, you get the following error :

{
    "outcome" => "failed",
    "result" => undefined,
    "failure-description" => "HQ119020: Invalid filter: msg_functional_date LIKE 201702%",
    "rolled-back" => true
}

This happens every time you use a litteral String in your command.

Working around a zealous unquoting

The solution is to replace the single quotes surrounding your String litterals by an opening '\' and a closing \''. That is, wherever you’re using 'foo' in your management command, replace it with '\'foo\'':

port=27099;

lastMonthDate="`date +%Y-%m-01` -1 month"
lastMonth=`date --date="$lastMonthDate" +'%Y%m'`
tmpFile=`mktemp`

$JBOSS_HOME/bin/jboss-cli.sh  --connect controller=`hostname`:$port --command="/subsystem=messaging/hornetq-server=default:read-children-names(child-type=jms-queue)" | grep -Po '(?<=\s{4}")[^"]+(?=",)' | while read queue; do
    $JBOSS_HOME/bin/jboss-cli.sh  --connect controller=`hostname`:$port --command="/subsystem=messaging/hornetq-server=default/jms-queue=${queue}:remove-messages(filter=\"msg_functional_date LIKE '\'${lastMonth}%\''\")"
done
Note
Another solution is to output your commands to a file and use the --file option for jboss-cli to parse it.