snapcore / spread

Spread - Convenient full-system test (task) distribution
GNU General Public License v3.0
99 stars 58 forks source link

Do not copy log.Logger and the contained sync.Mutex #111

Open zyga opened 3 years ago

zyga commented 3 years ago

Go vet reports the following problem:

# github.com/snapcore/spread/spread
spread/logger.go:135:13: assignment copies lock value to logSaved: log.Logger contains sync.Mutex
spread/logger.go:142:12: assignment copies lock value to *Logger: log.Logger contains sync.Mutex
spread/logger.go:146:12: assignment copies lock value to *Logger: log.Logger contains sync.Mutex

Cursory inspection of the termLock and termUnlock functions performing this overwrite indicates that it is to restore the flags, prefix and the io.Writer used by the logger internally. Analysis of the go 1.13 source code indicates that there's very little other state:

type Logger struct {
    mu     sync.Mutex // ensures atomic writes; protects the following fields
    prefix string     // prefix to write at beginning of each line
    flag   int        // properties
    out    io.Writer  // destination for output
    buf    []byte     // for accumulating text to write
}

Instead of writing over the whole struct, save and restore individual fields. Globally only the io.Writer needs to be saved across termLock and termUnlock calls. Inside termUnlock, flags and prefix are also saved and restore around the internal "flush".

Signed-off-by: Zygmunt Krynicki zygmunt.krynicki@huawei.com