Public IP getter loop refactored

This commit is contained in:
Quentin McGaw
2020-12-28 01:51:55 +00:00
parent 91f5338db0
commit db886163c2
11 changed files with 279 additions and 135 deletions

View File

@@ -6,7 +6,9 @@ import (
"sync"
"time"
"github.com/qdm12/gluetun/internal/constants"
"github.com/qdm12/gluetun/internal/models"
"github.com/qdm12/gluetun/internal/settings"
"github.com/qdm12/golibs/files"
"github.com/qdm12/golibs/logging"
"github.com/qdm12/golibs/network"
@@ -15,65 +17,57 @@ import (
type Looper interface {
Run(ctx context.Context, wg *sync.WaitGroup)
RunRestartTicker(ctx context.Context, wg *sync.WaitGroup)
Restart()
Stop()
GetPeriod() (period time.Duration)
SetPeriod(period time.Duration)
GetStatus() (status models.LoopStatus)
SetStatus(status models.LoopStatus) (outcome string, err error)
GetSettings() (settings settings.PublicIP)
SetSettings(settings settings.PublicIP) (outcome string)
GetPublicIP() (publicIP net.IP)
}
type looper struct {
period time.Duration
periodMutex sync.RWMutex
getter IPGetter
logger logging.Logger
fileManager files.FileManager
ipMutex sync.RWMutex
ip net.IP
ipStatusFilepath models.Filepath
uid int
gid int
restart chan struct{}
stop chan struct{}
updateTicker chan struct{}
timeNow func() time.Time
timeSince func(time.Time) time.Duration
state state
// Objects
getter IPGetter
logger logging.Logger
fileManager files.FileManager
// Fixed settings
uid int
gid int
// Internal channels and locks
loopLock sync.Mutex
start chan struct{}
running chan models.LoopStatus
stop chan struct{}
stopped chan struct{}
updateTicker chan struct{}
// Mock functions
timeNow func() time.Time
timeSince func(time.Time) time.Duration
}
func NewLooper(client network.Client, logger logging.Logger, fileManager files.FileManager,
ipStatusFilepath models.Filepath, period time.Duration, uid, gid int) Looper {
settings settings.PublicIP, uid, gid int) Looper {
return &looper{
period: period,
getter: NewIPGetter(client),
logger: logger.WithPrefix("ip getter: "),
fileManager: fileManager,
ipStatusFilepath: ipStatusFilepath,
uid: uid,
gid: gid,
restart: make(chan struct{}),
stop: make(chan struct{}),
updateTicker: make(chan struct{}),
timeNow: time.Now,
timeSince: time.Since,
state: state{
status: constants.Stopped,
settings: settings,
},
// Objects
getter: NewIPGetter(client),
logger: logger.WithPrefix("ip getter: "),
fileManager: fileManager,
uid: uid,
gid: gid,
start: make(chan struct{}),
running: make(chan models.LoopStatus),
stop: make(chan struct{}),
stopped: make(chan struct{}),
updateTicker: make(chan struct{}),
timeNow: time.Now,
timeSince: time.Since,
}
}
func (l *looper) Restart() { l.restart <- struct{}{} }
func (l *looper) Stop() { l.stop <- struct{}{} }
func (l *looper) GetPeriod() (period time.Duration) {
l.periodMutex.RLock()
defer l.periodMutex.RUnlock()
return l.period
}
func (l *looper) SetPeriod(period time.Duration) {
l.periodMutex.Lock()
l.period = period
l.periodMutex.Unlock()
l.updateTicker <- struct{}{}
}
func (l *looper) logAndWait(ctx context.Context, err error) {
l.logger.Error(err)
const waitTime = 5 * time.Second
@@ -90,54 +84,84 @@ func (l *looper) logAndWait(ctx context.Context, err error) {
func (l *looper) Run(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
crashed := false
select {
case <-l.restart:
case <-l.start:
case <-ctx.Done():
return
}
defer l.logger.Warn("loop exited")
enabled := true
for ctx.Err() == nil {
for !enabled {
// wait for a signal to re-enable
select {
case <-l.stop:
l.logger.Info("already disabled")
case <-l.restart:
enabled = true
case <-ctx.Done():
getCtx, getCancel := context.WithCancel(ctx)
defer getCancel()
ipCh := make(chan net.IP)
errorCh := make(chan error)
go func() {
ip, err := l.getter.Get(getCtx)
if err != nil {
errorCh <- err
return
}
ipCh <- ip
}()
if !crashed {
l.running <- constants.Running
crashed = false
} else {
l.state.setStatusWithLock(constants.Running)
}
// Enabled and has a period set
ip, err := l.getter.Get(ctx)
if err != nil {
l.logAndWait(ctx, err)
continue
}
l.setPublicIP(ip)
l.logger.Info("Public IP address is %s", ip)
const userReadWritePermissions = 0600
err = l.fileManager.WriteLinesToFile(
string(l.ipStatusFilepath),
[]string{ip.String()},
files.Ownership(l.uid, l.gid),
files.Permissions(userReadWritePermissions))
if err != nil {
l.logAndWait(ctx, err)
continue
}
select {
case <-l.restart: // triggered restart
case <-l.stop:
enabled = false
case <-ctx.Done():
return
stayHere := true
for stayHere {
select {
case <-ctx.Done():
l.logger.Warn("context canceled: exiting loop")
getCancel()
close(errorCh)
filepath := l.GetSettings().IPFilepath
l.logger.Info("Removing ip file %s", filepath)
if err := l.fileManager.Remove(string(filepath)); err != nil {
l.logger.Error(err)
}
return
case <-l.start:
l.logger.Info("starting")
getCancel()
stayHere = false
case <-l.stop:
l.logger.Info("stopping")
getCancel()
<-errorCh
l.stopped <- struct{}{}
case ip := <-ipCh:
getCancel()
l.state.setPublicIP(ip)
l.logger.Info("Public IP address is %s", ip)
const userReadWritePermissions = 0600
err := l.fileManager.WriteLinesToFile(
string(l.state.settings.IPFilepath),
[]string{ip.String()},
files.Ownership(l.uid, l.gid),
files.Permissions(userReadWritePermissions))
if err != nil {
l.logger.Error(err)
}
l.state.setStatusWithLock(constants.Completed)
case err := <-errorCh:
getCancel()
close(ipCh)
l.state.setStatusWithLock(constants.Crashed)
l.logAndWait(ctx, err)
crashed = true
stayHere = false
}
}
close(errorCh)
}
}
@@ -146,10 +170,9 @@ func (l *looper) RunRestartTicker(ctx context.Context, wg *sync.WaitGroup) {
timer := time.NewTimer(time.Hour)
timer.Stop() // 1 hour, cannot be a race condition
timerIsStopped := true
period := l.GetPeriod()
if period > 0 {
timer.Reset(period)
if period := l.GetSettings().Period; period > 0 {
timerIsStopped = false
timer.Reset(period)
}
lastTick := time.Unix(0, 0)
for {
@@ -161,14 +184,14 @@ func (l *looper) RunRestartTicker(ctx context.Context, wg *sync.WaitGroup) {
return
case <-timer.C:
lastTick = l.timeNow()
l.restart <- struct{}{}
timer.Reset(l.GetPeriod())
l.start <- struct{}{}
timer.Reset(l.GetSettings().Period)
case <-l.updateTicker:
if !timer.Stop() {
if !timerIsStopped && !timer.Stop() {
<-timer.C
}
timerIsStopped = true
period := l.GetPeriod()
period := l.GetSettings().Period
if period == 0 {
continue
}