stats_helpers.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package container
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/cli/command/formatter"
  12. "github.com/docker/docker/client"
  13. "golang.org/x/net/context"
  14. )
  15. type stats struct {
  16. ostype string
  17. mu sync.Mutex
  18. cs []*formatter.ContainerStats
  19. }
  20. // daemonOSType is set once we have at least one stat for a container
  21. // from the daemon. It is used to ensure we print the right header based
  22. // on the daemon platform.
  23. var daemonOSType string
  24. func (s *stats) add(cs *formatter.ContainerStats) bool {
  25. s.mu.Lock()
  26. defer s.mu.Unlock()
  27. if _, exists := s.isKnownContainer(cs.Name); !exists {
  28. s.cs = append(s.cs, cs)
  29. return true
  30. }
  31. return false
  32. }
  33. func (s *stats) remove(id string) {
  34. s.mu.Lock()
  35. if i, exists := s.isKnownContainer(id); exists {
  36. s.cs = append(s.cs[:i], s.cs[i+1:]...)
  37. }
  38. s.mu.Unlock()
  39. }
  40. func (s *stats) isKnownContainer(cid string) (int, bool) {
  41. for i, c := range s.cs {
  42. if c.Name == cid {
  43. return i, true
  44. }
  45. }
  46. return -1, false
  47. }
  48. func collect(s *formatter.ContainerStats, ctx context.Context, cli client.APIClient, streamStats bool, waitFirst *sync.WaitGroup) {
  49. logrus.Debugf("collecting stats for %s", s.Name)
  50. var (
  51. getFirst bool
  52. previousCPU uint64
  53. previousSystem uint64
  54. u = make(chan error, 1)
  55. )
  56. defer func() {
  57. // if error happens and we get nothing of stats, release wait group whatever
  58. if !getFirst {
  59. getFirst = true
  60. waitFirst.Done()
  61. }
  62. }()
  63. response, err := cli.ContainerStats(ctx, s.Name, streamStats)
  64. if err != nil {
  65. s.SetError(err)
  66. return
  67. }
  68. defer response.Body.Close()
  69. dec := json.NewDecoder(response.Body)
  70. go func() {
  71. for {
  72. var (
  73. v *types.StatsJSON
  74. memPercent = 0.0
  75. cpuPercent = 0.0
  76. blkRead, blkWrite uint64 // Only used on Linux
  77. mem = 0.0
  78. memLimit = 0.0
  79. memPerc = 0.0
  80. pidsStatsCurrent uint64
  81. )
  82. if err := dec.Decode(&v); err != nil {
  83. dec = json.NewDecoder(io.MultiReader(dec.Buffered(), response.Body))
  84. u <- err
  85. if err == io.EOF {
  86. break
  87. }
  88. time.Sleep(100 * time.Millisecond)
  89. continue
  90. }
  91. daemonOSType = response.OSType
  92. if daemonOSType != "windows" {
  93. // MemoryStats.Limit will never be 0 unless the container is not running and we haven't
  94. // got any data from cgroup
  95. if v.MemoryStats.Limit != 0 {
  96. memPercent = float64(v.MemoryStats.Usage) / float64(v.MemoryStats.Limit) * 100.0
  97. }
  98. previousCPU = v.PreCPUStats.CPUUsage.TotalUsage
  99. previousSystem = v.PreCPUStats.SystemUsage
  100. cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v)
  101. blkRead, blkWrite = calculateBlockIO(v.BlkioStats)
  102. mem = float64(v.MemoryStats.Usage)
  103. memLimit = float64(v.MemoryStats.Limit)
  104. memPerc = memPercent
  105. pidsStatsCurrent = v.PidsStats.Current
  106. } else {
  107. cpuPercent = calculateCPUPercentWindows(v)
  108. blkRead = v.StorageStats.ReadSizeBytes
  109. blkWrite = v.StorageStats.WriteSizeBytes
  110. mem = float64(v.MemoryStats.PrivateWorkingSet)
  111. }
  112. netRx, netTx := calculateNetwork(v.Networks)
  113. s.SetStatistics(formatter.StatsEntry{
  114. CPUPercentage: cpuPercent,
  115. Memory: mem,
  116. MemoryPercentage: memPerc,
  117. MemoryLimit: memLimit,
  118. NetworkRx: netRx,
  119. NetworkTx: netTx,
  120. BlockRead: float64(blkRead),
  121. BlockWrite: float64(blkWrite),
  122. PidsCurrent: pidsStatsCurrent,
  123. })
  124. u <- nil
  125. if !streamStats {
  126. return
  127. }
  128. }
  129. }()
  130. for {
  131. select {
  132. case <-time.After(2 * time.Second):
  133. // zero out the values if we have not received an update within
  134. // the specified duration.
  135. s.SetErrorAndReset(errors.New("timeout waiting for stats"))
  136. // if this is the first stat you get, release WaitGroup
  137. if !getFirst {
  138. getFirst = true
  139. waitFirst.Done()
  140. }
  141. case err := <-u:
  142. if err != nil {
  143. s.SetError(err)
  144. continue
  145. }
  146. s.SetError(nil)
  147. // if this is the first stat you get, release WaitGroup
  148. if !getFirst {
  149. getFirst = true
  150. waitFirst.Done()
  151. }
  152. }
  153. if !streamStats {
  154. return
  155. }
  156. }
  157. }
  158. func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
  159. var (
  160. cpuPercent = 0.0
  161. // calculate the change for the cpu usage of the container in between readings
  162. cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
  163. // calculate the change for the entire system between readings
  164. systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
  165. )
  166. if systemDelta > 0.0 && cpuDelta > 0.0 {
  167. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  168. }
  169. return cpuPercent
  170. }
  171. func calculateCPUPercentWindows(v *types.StatsJSON) float64 {
  172. // Max number of 100ns intervals between the previous time read and now
  173. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  174. possIntervals /= 100 // Convert to number of 100ns intervals
  175. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  176. // Intervals used
  177. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  178. // Percentage avoiding divide-by-zero
  179. if possIntervals > 0 {
  180. return float64(intervalsUsed) / float64(possIntervals) * 100.0
  181. }
  182. return 0.00
  183. }
  184. func calculateBlockIO(blkio types.BlkioStats) (blkRead uint64, blkWrite uint64) {
  185. for _, bioEntry := range blkio.IoServiceBytesRecursive {
  186. switch strings.ToLower(bioEntry.Op) {
  187. case "read":
  188. blkRead = blkRead + bioEntry.Value
  189. case "write":
  190. blkWrite = blkWrite + bioEntry.Value
  191. }
  192. }
  193. return
  194. }
  195. func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) {
  196. var rx, tx float64
  197. for _, v := range network {
  198. rx += float64(v.RxBytes)
  199. tx += float64(v.TxBytes)
  200. }
  201. return rx, tx
  202. }