stats_helpers.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.Container); !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.Container == cid {
  43. return i, true
  44. }
  45. }
  46. return -1, false
  47. }
  48. func collect(ctx context.Context, s *formatter.ContainerStats, cli client.APIClient, streamStats bool, waitFirst *sync.WaitGroup) {
  49. logrus.Debugf("collecting stats for %s", s.Container)
  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.Container, 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. Name: v.Name,
  115. ID: v.ID,
  116. CPUPercentage: cpuPercent,
  117. Memory: mem,
  118. MemoryPercentage: memPerc,
  119. MemoryLimit: memLimit,
  120. NetworkRx: netRx,
  121. NetworkTx: netTx,
  122. BlockRead: float64(blkRead),
  123. BlockWrite: float64(blkWrite),
  124. PidsCurrent: pidsStatsCurrent,
  125. })
  126. u <- nil
  127. if !streamStats {
  128. return
  129. }
  130. }
  131. }()
  132. for {
  133. select {
  134. case <-time.After(2 * time.Second):
  135. // zero out the values if we have not received an update within
  136. // the specified duration.
  137. s.SetErrorAndReset(errors.New("timeout waiting for stats"))
  138. // if this is the first stat you get, release WaitGroup
  139. if !getFirst {
  140. getFirst = true
  141. waitFirst.Done()
  142. }
  143. case err := <-u:
  144. if err != nil {
  145. s.SetError(err)
  146. continue
  147. }
  148. s.SetError(nil)
  149. // if this is the first stat you get, release WaitGroup
  150. if !getFirst {
  151. getFirst = true
  152. waitFirst.Done()
  153. }
  154. }
  155. if !streamStats {
  156. return
  157. }
  158. }
  159. }
  160. func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
  161. var (
  162. cpuPercent = 0.0
  163. // calculate the change for the cpu usage of the container in between readings
  164. cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
  165. // calculate the change for the entire system between readings
  166. systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
  167. )
  168. if systemDelta > 0.0 && cpuDelta > 0.0 {
  169. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  170. }
  171. return cpuPercent
  172. }
  173. func calculateCPUPercentWindows(v *types.StatsJSON) float64 {
  174. // Max number of 100ns intervals between the previous time read and now
  175. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  176. possIntervals /= 100 // Convert to number of 100ns intervals
  177. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  178. // Intervals used
  179. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  180. // Percentage avoiding divide-by-zero
  181. if possIntervals > 0 {
  182. return float64(intervalsUsed) / float64(possIntervals) * 100.0
  183. }
  184. return 0.00
  185. }
  186. func calculateBlockIO(blkio types.BlkioStats) (blkRead uint64, blkWrite uint64) {
  187. for _, bioEntry := range blkio.IoServiceBytesRecursive {
  188. switch strings.ToLower(bioEntry.Op) {
  189. case "read":
  190. blkRead = blkRead + bioEntry.Value
  191. case "write":
  192. blkWrite = blkWrite + bioEntry.Value
  193. }
  194. }
  195. return
  196. }
  197. func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) {
  198. var rx, tx float64
  199. for _, v := range network {
  200. rx += float64(v.RxBytes)
  201. tx += float64(v.TxBytes)
  202. }
  203. return rx, tx
  204. }