parallelizing domain checking

This commit is contained in:
Laurent Le Houerou 2020-10-27 16:33:18 +04:00
parent 45f5f46c86
commit ba27df891e

View File

@ -3,11 +3,13 @@ package main
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"path" "path"
"strings" "strings"
"sync"
"time" "time"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -107,39 +109,73 @@ func update(ctx context.Context, requester outboundip.IpRequester, manager dns.M
} }
newIp := newIpResult.Ip newIp := newIpResult.Ip
wg := sync.WaitGroup{}
updatedDomains := "" updatedDomains := ""
updatedDomainsChannel := make(chan string)
for _, domain := range configuration.Domains { for _, domain := range configuration.Domains {
currentIp, err := manager.GetARecord(domain) domain := domain
wg.Add(1)
go func() {
defer wg.Done()
updated, err := checkDomain(manager, domain, newIp)
if err != nil { if err != nil {
return fmt.Errorf("getting current ip: %v", err) log.Error().Err(err).Str("domain", domain).Msg("checking domain ip change")
} }
if updated {
if currentIp == newIp { updatedDomainsChannel <- domain
continue
} }
log. }()
Ctx(ctx). }
Info(). go func() {
Str("domain", domain). wg.Wait()
Str("current ip", currentIp). close(updatedDomainsChannel)
Str("new ip", newIp). }()
Msg("ip has changed") for {
err = manager.SetARecord(domain, newIp) select {
if err != nil { case <-ctx.Done():
return fmt.Errorf("setting current ip: %v", err) return errors.New("context canceled")
case d, ok := <-updatedDomainsChannel:
if !ok {
updatedDomainsChannel = nil
break
}
updatedDomains += fmt.Sprintf("\t- %s\n", d)
}
if updatedDomainsChannel == nil {
break
} }
updatedDomains += fmt.Sprintf("\t- %s\n", domain)
} }
if updatedDomains != "" { if updatedDomains != "" {
SendStatusMail(fmt.Sprintf(`Home IP has changed : %s SendStatusMail(fmt.Sprintf(`Home IP has changed : %s
Dns updated successfully for domains Dns updated successfully for domains
%s`, newIp, updatedDomains)) %s`, newIp, updatedDomains))
} }
return nil return nil
} }
func checkDomain(manager dns.Manager, domainname string, outboundip string) (bool, error) {
currentIp, err := manager.GetARecord(domainname)
if err != nil {
return false, fmt.Errorf("getting current ip: %v", err)
}
if currentIp == outboundip {
return false, nil
}
log.
Info().
Str("domain", domainname).
Str("current ip", currentIp).
Str("new ip", outboundip).
Msg("ip has changed")
err = manager.SetARecord(domainname, outboundip)
if err != nil {
return false, fmt.Errorf("setting current ip: %v", err)
}
return true, nil
}
func SendStatusMail(messageText string) { func SendStatusMail(messageText string) {
settings := configuration.MailSettings settings := configuration.MailSettings