From 08823ddc923f5ee4a76bc22fa10a3efbbc1cf1e2 Mon Sep 17 00:00:00 2001 From: aler9 <46489434+aler9@users.noreply.github.com> Date: Sat, 31 Oct 2020 17:03:03 +0100 Subject: [PATCH] fix memory leak caused by time.Timer --- externalcmd/externalcmd.go | 45 +++++++++++++++++++------------------- sourcertmp/source.go | 30 +++++++++++++++---------- sourcertsp/source.go | 29 ++++++++++++++---------- 3 files changed, 57 insertions(+), 47 deletions(-) diff --git a/externalcmd/externalcmd.go b/externalcmd/externalcmd.go index 49cc4e07..6ab55553 100644 --- a/externalcmd/externalcmd.go +++ b/externalcmd/externalcmd.go @@ -46,35 +46,34 @@ func (e *ExternalCmd) run() { defer close(e.done) for { - if !e.runInner() { + ok := func() bool { + ok := e.runInner() + if !ok { + return false + } + + if !e.restart { + <-e.terminate + return false + } + + t := time.NewTimer(restartPause) + defer t.Stop() + + select { + case <-t.C: + return true + case <-e.terminate: + return false + } + }() + if !ok { break } } } func (e *ExternalCmd) runInner() bool { - ok := e.runInnerInner() - if !ok { - return false - } - - if !e.restart { - <-e.terminate - return false - } - - t := time.NewTimer(restartPause) - defer t.Stop() - - select { - case <-t.C: - return true - case <-e.terminate: - return false - } -} - -func (e *ExternalCmd) runInnerInner() bool { var cmd *exec.Cmd if runtime.GOOS == "windows" { // on Windows the shell is not used and command is started directly diff --git a/sourcertmp/source.go b/sourcertmp/source.go index f169739d..278754c5 100644 --- a/sourcertmp/source.go +++ b/sourcertmp/source.go @@ -123,20 +123,25 @@ outer: func (s *Source) runInner() { defer close(s.innerDone) -outer: for { - ok := s.runInnerInner() + ok := func() bool { + ok := s.runInnerInner() + if !ok { + return false + } + + t := time.NewTimer(retryInterval) + defer t.Stop() + + select { + case <-t.C: + return true + case <-s.innerTerminate: + return false + } + }() if !ok { - break outer - } - - t := time.NewTimer(retryInterval) - defer t.Stop() - - select { - case <-s.innerTerminate: - break outer - case <-t.C: + break } } } @@ -209,6 +214,7 @@ func (s *Source) runInnerInner() bool { }() timer := time.NewTimer(5 * time.Second) + defer timer.Stop() select { case <-confDone: diff --git a/sourcertsp/source.go b/sourcertsp/source.go index d29f0ecf..7d8f5e47 100644 --- a/sourcertsp/source.go +++ b/sourcertsp/source.go @@ -127,20 +127,25 @@ outer: func (s *Source) runInner() { defer close(s.innerDone) -outer: for { - ok := s.runInnerInner() + ok := func() bool { + ok := s.runInnerInner() + if !ok { + return false + } + + t := time.NewTimer(retryInterval) + defer t.Stop() + + select { + case <-t.C: + return true + case <-s.innerTerminate: + return false + } + }() if !ok { - break outer - } - - t := time.NewTimer(retryInterval) - defer t.Stop() - - select { - case <-s.innerTerminate: - break outer - case <-t.C: + break } } }