oom_watcher_linux.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // +build linux
  2. /*
  3. Copyright 2015 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package oom
  15. import (
  16. "fmt"
  17. v1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/util/runtime"
  19. "k8s.io/client-go/tools/record"
  20. "k8s.io/klog"
  21. "github.com/google/cadvisor/utils/oomparser"
  22. )
  23. type streamer interface {
  24. StreamOoms(chan<- *oomparser.OomInstance)
  25. }
  26. var _ streamer = &oomparser.OomParser{}
  27. type realWatcher struct {
  28. recorder record.EventRecorder
  29. oomStreamer streamer
  30. }
  31. var _ Watcher = &realWatcher{}
  32. // NewWatcher creates and initializes a OOMWatcher backed by Cadvisor as
  33. // the oom streamer.
  34. func NewWatcher(recorder record.EventRecorder) (Watcher, error) {
  35. oomStreamer, err := oomparser.New()
  36. if err != nil {
  37. return nil, err
  38. }
  39. watcher := &realWatcher{
  40. recorder: recorder,
  41. oomStreamer: oomStreamer,
  42. }
  43. return watcher, nil
  44. }
  45. const (
  46. systemOOMEvent = "SystemOOM"
  47. recordEventContainerName = "/"
  48. )
  49. // Start watches for system oom's and records an event for every system oom encountered.
  50. func (ow *realWatcher) Start(ref *v1.ObjectReference) error {
  51. outStream := make(chan *oomparser.OomInstance, 10)
  52. go ow.oomStreamer.StreamOoms(outStream)
  53. go func() {
  54. defer runtime.HandleCrash()
  55. for event := range outStream {
  56. if event.ContainerName == recordEventContainerName {
  57. klog.V(1).Infof("Got sys oom event: %v", event)
  58. eventMsg := "System OOM encountered"
  59. if event.ProcessName != "" && event.Pid != 0 {
  60. eventMsg = fmt.Sprintf("%s, victim process: %s, pid: %d", eventMsg, event.ProcessName, event.Pid)
  61. }
  62. ow.recorder.Eventf(ref, v1.EventTypeWarning, systemOOMEvent, eventMsg)
  63. }
  64. }
  65. klog.Errorf("Unexpectedly stopped receiving OOM notifications")
  66. }()
  67. return nil
  68. }