Fix potential race in ThrottledLogger flusher.
authorTom Clegg <tom@curoverse.com>
Thu, 4 Aug 2016 20:53:32 +0000 (16:53 -0400)
committerTom Clegg <tom@curoverse.com>
Thu, 4 Aug 2016 21:45:17 +0000 (17:45 -0400)
No issue #

services/crunch-run/logging.go

index db9d101b581b560314374792421c134f918c47b0..a2aa5c6b48d8ca9b9d970323ab43175d45b063a6 100644 (file)
@@ -84,22 +84,20 @@ func (tl *ThrottledLogger) flusher() {
        // actually initiated closer every 1s instead of every
        // 1s + (time to it takes to write).
        go goWriter(tl.writer, bufchan, bufterm)
-       for {
-               if !tl.stop {
-                       time.Sleep(1 * time.Second)
-               }
+
+       // We use a separate "stopping" var here to ensure we flush
+       // tl.buf after tl.stop becomes true.
+       stopping := false
+       for !stopping {
+               time.Sleep(time.Second)
+               stopping = tl.stop
                tl.Mutex.Lock()
                if tl.buf != nil && tl.buf.Len() > 0 {
                        oldbuf := tl.buf
                        tl.buf = nil
-                       tl.Mutex.Unlock()
                        bufchan <- oldbuf
-               } else if tl.stop {
-                       tl.Mutex.Unlock()
-                       break
-               } else {
-                       tl.Mutex.Unlock()
                }
+               tl.Mutex.Unlock()
        }
        close(bufchan)
        <-bufterm