From 524a9af060314f858842528ca48c653e94c80288 Mon Sep 17 00:00:00 2001 From: Michael Stapelberg Date: Mon, 11 Jan 2021 03:21:02 +0100 Subject: [PATCH] retry listening indefinitely (#105) When starting hmq immediately after booting, the IP address specified in the --host flag (e.g. --host=10.0.0.217) might not be configured yet. Without this commit, hmq would try to listen, give up, and then just hang. With this commit, hmq automatically recovers. --- broker/broker.go | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/broker/broker.go b/broker/broker.go index 415d530..cc980c2 100644 --- a/broker/broker.go +++ b/broker/broker.go @@ -177,21 +177,27 @@ func (b *Broker) wsHandler(ws *websocket.Conn) { } func (b *Broker) StartClientListening(Tls bool) { - var hp string var err error var l net.Listener - if Tls { - hp = b.config.TlsHost + ":" + b.config.TlsPort - l, err = tls.Listen("tcp", hp, b.tlsConfig) - log.Info("Start TLS Listening client on ", zap.String("hp", hp)) - } else { - hp := b.config.Host + ":" + b.config.Port - l, err = net.Listen("tcp", hp) - log.Info("Start Listening client on ", zap.String("hp", hp)) - } - if err != nil { - log.Error("Error listening on ", zap.Error(err)) - return + // Retry listening indefinitely so that specifying IP addresses + // (e.g. --host=10.0.0.217) starts working once the IP address is actually + // configured on the interface. + for { + if Tls { + hp := b.config.TlsHost + ":" + b.config.TlsPort + l, err = tls.Listen("tcp", hp, b.tlsConfig) + log.Info("Start TLS Listening client on ", zap.String("hp", hp)) + } else { + hp := b.config.Host + ":" + b.config.Port + l, err = net.Listen("tcp", hp) + log.Info("Start Listening client on ", zap.String("hp", hp)) + } + if err != nil { + log.Error("Error listening on ", zap.Error(err)) + time.Sleep(1 * time.Second) + } else { + break // successfully listening + } } tmpDelay := 10 * ACCEPT_MIN_SLEEP for {