Refactor oom watcher to allow greater test coverage

This diff contains a strict refactor; there are no behavioral changes.

Address a long standing TODO in `oom_watcher_linux_test.go` around test
coverage. We refactor our `oom.Watcher` so it takes in a struct
fulfulling the `streamer` interface (i.e. defines `StreamOoms` method).
In production, we will continue to use the `oomparser` from `cadvisor`.
However, for testing purposes, we can now create our own `fakeStreamer`,
and control how it streams `oomparser.OomInstance`. With this fake, we
can implement richer unit testing for the `oom.Watcher` itself.

Actually adding the additional unit tests will come in a later commit.
This commit is contained in:
mattjmcnaughton
2019-12-29 09:26:35 -05:00
parent 886cf062a4
commit 8897c435ad
5 changed files with 43 additions and 19 deletions

View File

@@ -30,29 +30,41 @@ import (
"github.com/google/cadvisor/utils/oomparser"
)
type streamer interface {
StreamOoms(chan<- *oomparser.OomInstance)
}
var _ streamer = &oomparser.OomParser{}
type realWatcher struct {
recorder record.EventRecorder
recorder record.EventRecorder
oomStreamer streamer
}
var _ Watcher = &realWatcher{}
// NewWatcher creates and initializes a OOMWatcher based on parameters.
func NewWatcher(recorder record.EventRecorder) Watcher {
return &realWatcher{
recorder: recorder,
// NewWatcher creates and initializes a OOMWatcher backed by Cadvisor as
// the oom streamer.
func NewWatcher(recorder record.EventRecorder) (Watcher, error) {
oomStreamer, err := oomparser.New()
if err != nil {
return nil, err
}
watcher := &realWatcher{
recorder: recorder,
oomStreamer: oomStreamer,
}
return watcher, nil
}
const systemOOMEvent = "SystemOOM"
// Start watches for system oom's and records an event for every system oom encountered.
func (ow *realWatcher) Start(ref *v1.ObjectReference) error {
oomLog, err := oomparser.New()
if err != nil {
return err
}
outStream := make(chan *oomparser.OomInstance, 10)
go oomLog.StreamOoms(outStream)
go ow.oomStreamer.StreamOoms(outStream)
go func() {
defer runtime.HandleCrash()