events.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // +build linux
  2. package runc
  3. import (
  4. "encoding/json"
  5. "os"
  6. "sync"
  7. "time"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/codegangsta/cli"
  10. "github.com/opencontainers/runc/libcontainer"
  11. )
  12. // event struct for encoding the event data to json.
  13. type event struct {
  14. Type string `json:"type"`
  15. ID string `json:"id"`
  16. Data interface{} `json:"data,omitempty"`
  17. }
  18. var eventsCommand = cli.Command{
  19. Name: "events",
  20. Usage: "display container events such as OOM notifications, cpu, memory, IO and network stats",
  21. ArgsUsage: `<container-id>
  22. Where "<container-id>" is the name for the instance of the container.`,
  23. Description: `The events command displays information about the container. By default the
  24. information is displayed once every 5 seconds.`,
  25. Flags: []cli.Flag{
  26. cli.DurationFlag{Name: "interval", Value: 5 * time.Second, Usage: "set the stats collection interval"},
  27. cli.BoolFlag{Name: "stats", Usage: "display the container's stats then exit"},
  28. },
  29. Action: func(context *cli.Context) {
  30. container, err := getContainer(context)
  31. if err != nil {
  32. fatal(err)
  33. }
  34. var (
  35. stats = make(chan *libcontainer.Stats, 1)
  36. events = make(chan *event, 1024)
  37. group = &sync.WaitGroup{}
  38. )
  39. group.Add(1)
  40. go func() {
  41. defer group.Done()
  42. enc := json.NewEncoder(os.Stdout)
  43. for e := range events {
  44. if err := enc.Encode(e); err != nil {
  45. logrus.Error(err)
  46. }
  47. }
  48. }()
  49. if context.Bool("stats") {
  50. s, err := container.Stats()
  51. if err != nil {
  52. fatal(err)
  53. }
  54. events <- &event{Type: "stats", ID: container.ID(), Data: s}
  55. close(events)
  56. group.Wait()
  57. return
  58. }
  59. go func() {
  60. for range time.Tick(context.Duration("interval")) {
  61. s, err := container.Stats()
  62. if err != nil {
  63. logrus.Error(err)
  64. continue
  65. }
  66. stats <- s
  67. }
  68. }()
  69. n, err := container.NotifyOOM()
  70. if err != nil {
  71. fatal(err)
  72. }
  73. for {
  74. select {
  75. case _, ok := <-n:
  76. if ok {
  77. // this means an oom event was received, if it is !ok then
  78. // the channel was closed because the container stopped and
  79. // the cgroups no longer exist.
  80. events <- &event{Type: "oom", ID: container.ID()}
  81. } else {
  82. n = nil
  83. }
  84. case s := <-stats:
  85. events <- &event{Type: "stats", ID: container.ID(), Data: s}
  86. }
  87. if n == nil {
  88. close(events)
  89. break
  90. }
  91. }
  92. group.Wait()
  93. },
  94. }