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
if err != nil { wg.Add(1)
return fmt.Errorf("getting current ip: %v", err) go func() {
} defer wg.Done()
updated, err := checkDomain(manager, domain, newIp)
if currentIp == newIp { if err != nil {
continue log.Error().Err(err).Str("domain", domain).Msg("checking domain ip change")
} }
log. if updated {
Ctx(ctx). updatedDomainsChannel <- domain
Info(). }
Str("domain", domain). }()
Str("current ip", currentIp). }
Str("new ip", newIp). go func() {
Msg("ip has changed") wg.Wait()
err = manager.SetARecord(domain, newIp) close(updatedDomainsChannel)
if err != nil { }()
return fmt.Errorf("setting current ip: %v", err) for {
} select {
updatedDomains += fmt.Sprintf("\t- %s\n", domain) case <-ctx.Done():
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
}
} }
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