mqtt: support ActiveMQ failover URIs with multiple brokers

The MQTT URI can now list several brokers, either as an ActiveMQ-style
failover URI (as used by Amazon MQ active/standby brokers) or as a plain
comma-separated list:

  failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)

Each broker is registered with paho, which tries them in order on
connect and reconnect. Transport options after the closing parenthesis
are ignored. The diagnostics dialer is only installed when every broker
uses a TCP-based scheme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
cedricve
2026-11-23 15:55:47 +00:00
co-authored by Claude Opus 5.5
parent 9a9b5d051b
commit 7d70361870
2 changed files with 113 additions and 16 deletions
+57 -15
View File
@@ -58,21 +58,59 @@ func init() {
mqtt.ERROR = pahoErrorLogger{}
}
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURL string) {
if !strings.Contains(brokerURL, "://") {
options.SetCustomOpenConnectionFn(openMQTTConnection)
return
// parseMQTTBrokers turns the configured MQTT URI into the list of brokers to
// connect to. Besides a single broker URI it accepts an ActiveMQ-style
// failover URI, as used by Amazon MQ active/standby brokers:
//
// failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)
//
// and a plain comma-separated list of broker URIs. Transport options after
// the closing parenthesis (e.g. "?randomize=false") are ignored: paho tries
// the brokers in the order they are listed, on connect and on reconnect.
func parseMQTTBrokers(raw string) []string {
raw = strings.TrimSpace(raw)
if len(raw) >= len("failover:") && strings.EqualFold(raw[:len("failover:")], "failover:") {
raw = strings.TrimSpace(raw[len("failover:"):])
if strings.HasPrefix(raw, "(") {
if end := strings.LastIndex(raw, ")"); end > 0 {
raw = raw[1:end]
} else {
raw = raw[1:]
}
}
}
parsedURL, err := url.Parse(brokerURL)
if err != nil {
brokers := []string{}
for _, broker := range strings.Split(raw, ",") {
if broker = strings.TrimSpace(broker); broker != "" {
brokers = append(brokers, broker)
}
}
return brokers
}
// enableMQTTConnectionDiagnostics installs our instrumented TCP/TLS dialer.
// The custom dialer is used for every broker, so it is only installed when
// all brokers use a TCP-based scheme (WebSocket brokers keep paho's dialer).
func enableMQTTConnectionDiagnostics(options *mqtt.ClientOptions, brokerURLs []string) {
if len(brokerURLs) == 0 {
return
}
switch strings.ToLower(parsedURL.Scheme) {
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
options.SetCustomOpenConnectionFn(openMQTTConnection)
for _, brokerURL := range brokerURLs {
if !strings.Contains(brokerURL, "://") {
continue
}
parsedURL, err := url.Parse(brokerURL)
if err != nil {
return
}
switch strings.ToLower(parsedURL.Scheme) {
case "", "mqtt", "tcp", "ssl", "tls", "mqtts", "mqtt+ssl", "tcps":
default:
return
}
}
options.SetCustomOpenConnectionFn(openMQTTConnection)
}
func openMQTTConnection(uri *url.URL, options mqtt.ClientOptions) (net.Conn, error) {
@@ -270,8 +308,11 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
// We will set the MQTT endpoint to which we want to connect
// and share and receive messages to/from.
mqttURL := config.MQTTURI
opts.AddBroker(mqttURL)
// The URI may list several brokers (failover), paho tries them in order.
mqttBrokers := parseMQTTBrokers(config.MQTTURI)
for _, broker := range mqttBrokers {
opts.AddBroker(broker)
}
// Our MQTT broker can have username/password credentials
// to protect it from the outside.
@@ -282,7 +323,8 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
opts.SetPassword(mqtt_password)
}
log.WithFields(log.Fields{
"broker_configured": mqttURL != "",
"broker_configured": len(mqttBrokers) > 0,
"broker_count": len(mqttBrokers),
"component": "routers/mqtt",
"event": "credentials_configured",
"password_configured": mqtt_password != "",
@@ -292,7 +334,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
// Some extra options to make sure the connection behaves
// properly. More information here: github.com/eclipse/paho.mqtt.golang.
//opts.SetCleanSession(true)
enableMQTTConnectionDiagnostics(opts, mqttURL)
enableMQTTConnectionDiagnostics(opts, mqttBrokers)
opts.SetCleanSession(false)
opts.SetResumeSubs(true)
opts.SetStore(mqtt.NewMemoryStore())
@@ -354,7 +396,7 @@ func ConfigureMQTT(configDirectory string, configuration *models.Configuration,
"event": "connected",
}).Info("MQTT broker connected")
log.WithFields(log.Fields{
"broker_configured": mqttURL != "",
"broker_configured": len(mqttBrokers) > 0,
"component": "routers/mqtt",
"event": "connection_details",
}).Debug("MQTT connection details")
+56 -1
View File
@@ -23,12 +23,15 @@ func TestEnableMQTTConnectionDiagnostics(t *testing.T) {
{name: "TCP", brokerURL: "tcp://broker.example:1883", want: true},
{name: "default TCP", brokerURL: "broker.example:1883", want: true},
{name: "WebSocket", brokerURL: "wss://broker.example/mqtt", want: false},
{name: "ActiveMQ failover", brokerURL: "failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)", want: true},
{name: "mixed TCP and WebSocket", brokerURL: "tcp://b-1.example:1883,wss://b-2.example/mqtt", want: false},
{name: "empty", brokerURL: "", want: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
options := mqtt.NewClientOptions()
enableMQTTConnectionDiagnostics(options, test.brokerURL)
enableMQTTConnectionDiagnostics(options, parseMQTTBrokers(test.brokerURL))
if got := options.CustomOpenConnectionFn != nil; got != test.want {
t.Fatalf("CustomOpenConnectionFn configured = %t, want %t", got, test.want)
}
@@ -206,3 +209,55 @@ func TestRemoteSessionReservationIsIdempotent(t *testing.T) {
t.Fatalf("duplicate reserve() error = %v, want %v", err, errRemoteSessionExists)
}
}
func TestParseMQTTBrokers(t *testing.T) {
tests := []struct {
name string
raw string
want []string
}{
{name: "single", raw: "mqtt+ssl://broker.example:8883", want: []string{"mqtt+ssl://broker.example:8883"}},
{name: "empty", raw: " ", want: []string{}},
{
name: "Amazon MQ failover",
raw: "failover:(mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883,mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883)",
want: []string{"mqtt+ssl://b-1.mq.eu-west-2.amazonaws.com:8883", "mqtt+ssl://b-2.mq.eu-west-2.amazonaws.com:8883"},
},
{
name: "failover with spaces and transport options",
raw: " FAILOVER:( ssl://b-1.example:8883 , ssl://b-2.example:8883 )?randomize=false",
want: []string{"ssl://b-1.example:8883", "ssl://b-2.example:8883"},
},
{name: "failover without parentheses", raw: "failover:tcp://b-1.example:1883", want: []string{"tcp://b-1.example:1883"}},
{name: "comma separated", raw: "tcp://b-1.example:1883,tcp://b-2.example:1883", want: []string{"tcp://b-1.example:1883", "tcp://b-2.example:1883"}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := parseMQTTBrokers(test.raw)
if len(got) != len(test.want) {
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
}
for i := range got {
if got[i] != test.want[i] {
t.Fatalf("parseMQTTBrokers(%q) = %q, want %q", test.raw, got, test.want)
}
}
})
}
}
func TestConfigureMQTTOptionsRegistersFailoverBrokers(t *testing.T) {
options := mqtt.NewClientOptions()
for _, broker := range parseMQTTBrokers("failover:(mqtt+ssl://b-1.example:8883,mqtt+ssl://b-2.example:8883)") {
options.AddBroker(broker)
}
if len(options.Servers) != 2 {
t.Fatalf("registered %d brokers, want 2", len(options.Servers))
}
for i, host := range []string{"b-1.example:8883", "b-2.example:8883"} {
if options.Servers[i].Scheme != "mqtt+ssl" || options.Servers[i].Host != host {
t.Fatalf("broker %d = %s, want mqtt+ssl://%s", i, options.Servers[i], host)
}
}
}