Skip to content

Commit

Permalink
refactor(mqtt): dry
Browse files Browse the repository at this point in the history
Signed-off-by: Julian Strobl <jmastr@mailbox.org>
  • Loading branch information
jmastr committed Nov 15, 2024
1 parent 8d2ecf6 commit 1bda49e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 37 deletions.
22 changes: 11 additions & 11 deletions monitor/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (mms *MqttMonitor) AddParticipant(address string, lastSeenTS int64) (err er

lastSeenBytes, err := json.Marshal(lastSeen)
if err != nil {
Log("[app] [Monitor] Error serializing ConversionRequest: " + err.Error())
Log("Error serializing ConversionRequest: " + err.Error())
return
}

Expand All @@ -34,9 +34,9 @@ func (mms *MqttMonitor) AddParticipant(address string, lastSeenTS int64) (err er
err = mms.db.Put([]byte(address), lastSeenBytes, nil)
mms.dbMutex.Unlock()
if err != nil {
Log("[app] [Monitor] error storing addresses in DB: " + err.Error())
Log("error storing addresses in DB: " + err.Error())
} else {
Log("[app] [Monitor] stored address in DB: " + address)
Log("stored address in DB: " + address)
}

return
Expand All @@ -60,9 +60,9 @@ func (mms *MqttMonitor) getAmountOfElements() (amount int64, err error) {

// Check for any errors encountered during iteration
if err := iter.Error(); err != nil {
Log("[app] [Monitor] " + err.Error())
Log("" + err.Error())
} else {
Log("[app] [Monitor] elements: " + strconv.FormatInt(amount, 10))
Log("elements: " + strconv.FormatInt(amount, 10))
}

return
Expand All @@ -72,14 +72,14 @@ func (mms *MqttMonitor) getDataFromIter(iter iterator.Iterator) (lastSeen LastSe
value := iter.Value()
err = json.Unmarshal(value, &lastSeen)
if err != nil {
Log("[app] [Monitor] Failed to unmarshal entry: " + string(key) + " - " + err.Error())
Log("Failed to unmarshal entry: " + string(key) + " - " + err.Error())
}
return
}

func (mms *MqttMonitor) CleanupDB() {
// Create an iterator for the database
Log("[app] [Monitor] Starting clean-up process")
Log("Starting clean-up process")
iter := mms.db.NewIterator(nil, nil)
defer iter.Release() // Make sure to release the iterator at the end

Expand All @@ -88,23 +88,23 @@ func (mms *MqttMonitor) CleanupDB() {
// Use iter.Key() and iter.Value() to access the key and value
lastSeen, err := mms.getDataFromIter(iter)
if err != nil {
Log("[app] [Monitor] Failed to unmarshal entry: " + string(iter.Key()) + " - " + err.Error())
Log("Failed to unmarshal entry: " + string(iter.Key()) + " - " + err.Error())
continue
}
timeThreshold := time.Now().Add(-1 * mms.CleanupPeriodicityInMinutes * time.Minute).Unix()
if lastSeen.Timestamp <= timeThreshold {
// If the entry is older than 12 hours, delete it
err := mms.deleteEntry(iter.Key())
if err != nil {
Log("[app] [Monitor] Failed to delete entry: " + err.Error())
Log("Failed to delete entry: " + err.Error())
} else {
Log("[app] [Monitor] Delete entry: " + string(iter.Key()))
Log("Delete entry: " + string(iter.Key()))
}
}
}

// Check for any errors encountered during iteration
if err := iter.Error(); err != nil {
Log("[app] [Monitor] error during cleanup : " + err.Error())
Log("error during cleanup : " + err.Error())
}
}
2 changes: 1 addition & 1 deletion monitor/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,5 @@ func Log(msg string) {
if mqttLogger == nil {
return
}
mqttLogger.Info(msg)
mqttLogger.Info("[app] [Monitor] " + msg)
}
50 changes: 25 additions & 25 deletions monitor/mqtt_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (mms *MqttMonitor) lazyLoadMonitorMQTTClient() util.MQTTClientI {
opts.SetTLSConfig(tlsConfig)
}

Log("[app] [Monitor] create new client")
Log("create new client")
client := mqtt.NewClient(opts)
return client
}
Expand Down Expand Up @@ -141,8 +141,8 @@ func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger str
return
}
randomChallenger, randomChallengee := mms.getRandomNumbers()
Log("[app] [Monitor] number of elements: " + strconv.Itoa(numElements))
Log("[app] [Monitor] selected IDs: " + strconv.Itoa(randomChallenger) + " " + strconv.Itoa(randomChallengee))
Log("number of elements: " + strconv.Itoa(numElements))
Log("selected IDs: " + strconv.Itoa(randomChallenger) + " " + strconv.Itoa(randomChallengee))
iter := mms.db.NewIterator(nil, nil)
defer iter.Release()
count := 0
Expand All @@ -152,15 +152,15 @@ func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger str
if count == randomChallenger {
lastSeen, err = mms.getDataFromIter(iter)
if err != nil {
Log("[app] [Monitor] could not get Data from ID" + strconv.Itoa(randomChallenger))
Log("could not get Data from ID" + strconv.Itoa(randomChallenger))
return
}
challenger = lastSeen.Address
found++
} else if count == randomChallengee {
lastSeen, err = mms.getDataFromIter(iter)
if err != nil {
Log("[app] [Monitor] could not get Data from ID" + strconv.Itoa(randomChallengee))
Log("could not get Data from ID" + strconv.Itoa(randomChallengee))
return
}
challengee = lastSeen.Address
Expand All @@ -172,7 +172,7 @@ func (mms *MqttMonitor) SelectPoPParticipantsOutOfActiveActors() (challenger str
break
}
}
Log("[app] [Monitor] challenger, challengee: " + challenger + " " + challengee)
Log("challenger, challengee: " + challenger + " " + challengee)
return
}

Expand Down Expand Up @@ -210,9 +210,9 @@ func (mms *MqttMonitor) MqttMsgHandler(_ mqtt.Client, msg mqtt.Message) {
err = mms.AddParticipant(address, unixTime)

if err != nil {
Log("[app] [Monitor] error adding active actor to DB: " + address + " " + err.Error())
Log("error adding active actor to DB: " + address + " " + err.Error())
} else {
Log("[app] [Monitor] added active actor to DB: " + address)
Log("added active actor to DB: " + address)
}
}

Expand All @@ -226,7 +226,7 @@ func IsLegitMachineAddress(address string) (active bool, err error) {
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
Log("[app] [Monitor] cannot send machine query request " + err.Error())
Log("cannot send machine query request " + err.Error())
return
}

Expand All @@ -236,7 +236,7 @@ func IsLegitMachineAddress(address string) (active bool, err error) {
// Send the request
resp, err := client.Do(req)
if err != nil {
Log("[app] [Monitor] cannot connect to server: " + err.Error())
Log("cannot connect to server: " + err.Error())
return
}

Expand All @@ -246,43 +246,43 @@ func IsLegitMachineAddress(address string) (active bool, err error) {
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
Log("[app] [Monitor] cannot read response: " + err.Error())
Log("cannot read response: " + err.Error())
return
}

// Check the status code
if resp.StatusCode != http.StatusOK {
Log("[app] [Monitor] unexpected status code: " + string(body))
Log("unexpected status code: " + string(body))
return
}

// Unmarshal the response body into a map
var data map[string]interface{}
err = json.Unmarshal(body, &data)
if err != nil {
Log("[app] [Monitor] cannot unmarshal response " + err.Error())
Log("cannot unmarshal response " + err.Error())
return
}

// Check if the "info" key exists
machineValue, ok := data["machine"]
if !ok {
Log("[app] [Monitor] response does not contain the required machine")
Log("response does not contain the required machine")
return
}
machineMap, ok := machineValue.(map[string]interface{})
if !ok {
Log("[app] [Monitor] cannot convert machine map")
Log("cannot convert machine map")
return
}
addressMap, ok := machineMap["address"]
if !ok {
Log("[app] [Monitor] response does not contain the required name")
Log("response does not contain the required name")
return
}
value, ok := addressMap.(string)
if !ok || value != address {
Log("[app] [Monitor] return machine is not the required one")
Log("return machine is not the required one")
return
}

Expand All @@ -292,7 +292,7 @@ func IsLegitMachineAddress(address string) (active bool, err error) {
}

func (mms *MqttMonitor) onConnectionLost(_ mqtt.Client, err error) {
Log("[app] [Monitor] Connection lost: " + err.Error())
Log("Connection lost: " + err.Error())
// Handle connection loss here (e.g., reconnect attempts, logging)
if !mms.IsTerminated() {
mms.lostConnectionMutex.Lock()
Expand All @@ -304,7 +304,7 @@ func (mms *MqttMonitor) onConnectionLost(_ mqtt.Client, err error) {
func (mms *MqttMonitor) MonitorActiveParticipants() {
mms.clientMutex.Lock()
if mms.localMqttClient != nil {
Log("[app] [Monitor] client is still working")
Log("client is still working")
mms.clientMutex.Unlock()
return
}
Expand All @@ -316,7 +316,7 @@ func (mms *MqttMonitor) MonitorActiveParticipants() {
mms.SetMaxRetries()
for !mms.IsTerminated() && mms.maxRetries > 0 {
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
Log("[app] [Monitor] error connecting to mqtt: " + token.Error().Error())
Log("error connecting to mqtt: " + token.Error().Error())
mms.maxRetries--
time.Sleep(time.Second * 5)
continue
Expand All @@ -325,24 +325,24 @@ func (mms *MqttMonitor) MonitorActiveParticipants() {
mms.lostConnection = false
mms.lostConnectionMutex.Unlock()

Log("[app] [Monitor] established connection")
Log("established connection")

var messageHandler mqtt.MessageHandler = mms.MqttMsgHandler

// Subscribe to a topic
subscriptionTopic := "tele/#"
if token := mqttClient.Subscribe(subscriptionTopic, 0, messageHandler); token.Wait() && token.Error() != nil {
Log("[app] [Monitor] error registering the mqtt subscription: " + token.Error().Error())
Log("error registering the mqtt subscription: " + token.Error().Error())
continue
}
Log("[app] [Monitor] subscribed to tele/# channels")
Log("subscribed to tele/# channels")

for !mms.IsTerminated() {
mms.lostConnectionMutex.Lock()
lostConnectionEvent := mms.lostConnection
mms.lostConnectionMutex.Unlock()
if !mqttClient.IsConnected() || !mqttClient.IsConnectionOpen() || lostConnectionEvent {
Log("[app] [Monitor] retry establishing a connection")
Log("retry establishing a connection")
break // Exit inner loop on disconnect
}

Expand All @@ -353,7 +353,7 @@ func (mms *MqttMonitor) MonitorActiveParticipants() {
}

if mms.maxRetries == 0 {
Log("[app] [Monitor] Reached maximum reconnection attempts. Exiting. New client will be activated soon.")
Log("Reached maximum reconnection attempts. Exiting. New client will be activated soon.")
}

mms.clientMutex.Lock()
Expand Down

0 comments on commit 1bda49e

Please sign in to comment.