stats_helpers.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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, cpuPercent float64
  75. blkRead, blkWrite uint64 // Only used on Linux
  76. mem, memLimit, memPerc float64
  77. pidsStatsCurrent uint64
  78. )
  79. if err := dec.Decode(&v); err != nil {
  80. dec = json.NewDecoder(io.MultiReader(dec.Buffered(), response.Body))
  81. u <- err
  82. if err == io.EOF {
  83. break
  84. }
  85. time.Sleep(100 * time.Millisecond)
  86. continue
  87. }
  88. daemonOSType = response.OSType
  89. if daemonOSType != "windows" {
  90. // MemoryStats.Limit will never be 0 unless the container is not running and we haven't
  91. // got any data from cgroup
  92. if v.MemoryStats.Limit != 0 {
  93. memPercent = float64(v.MemoryStats.Usage) / float64(v.MemoryStats.Limit) * 100.0
  94. }
  95. previousCPU = v.PreCPUStats.CPUUsage.TotalUsage
  96. previousSystem = v.PreCPUStats.SystemUsage
  97. cpuPercent = calculateCPUPercentUnix(previousCPU, previousSystem, v)
  98. blkRead, blkWrite = calculateBlockIO(v.BlkioStats)
  99. mem = float64(v.MemoryStats.Usage)
  100. memLimit = float64(v.MemoryStats.Limit)
  101. memPerc = memPercent
  102. pidsStatsCurrent = v.PidsStats.Current
  103. } else {
  104. cpuPercent = calculateCPUPercentWindows(v)
  105. blkRead = v.StorageStats.ReadSizeBytes
  106. blkWrite = v.StorageStats.WriteSizeBytes
  107. mem = float64(v.MemoryStats.PrivateWorkingSet)
  108. }
  109. netRx, netTx := calculateNetwork(v.Networks)
  110. s.SetStatistics(formatter.StatsEntry{
  111. Name: v.Name,
  112. ID: v.ID,
  113. CPUPercentage: cpuPercent,
  114. Memory: mem,
  115. MemoryPercentage: memPerc,
  116. MemoryLimit: memLimit,
  117. NetworkRx: netRx,
  118. NetworkTx: netTx,
  119. BlockRead: float64(blkRead),
  120. BlockWrite: float64(blkWrite),
  121. PidsCurrent: pidsStatsCurrent,
  122. })
  123. u <- nil
  124. if !streamStats {
  125. return
  126. }
  127. }
  128. }()
  129. for {
  130. select {
  131. case <-time.After(2 * time.Second):
  132. // zero out the values if we have not received an update within
  133. // the specified duration.
  134. s.SetErrorAndReset(errors.New("timeout waiting for stats"))
  135. // if this is the first stat you get, release WaitGroup
  136. if !getFirst {
  137. getFirst = true
  138. waitFirst.Done()
  139. }
  140. case err := <-u:
  141. s.SetError(err)
  142. if err == io.EOF {
  143. break
  144. }
  145. if err != nil {
  146. continue
  147. }
  148. // if this is the first stat you get, release WaitGroup
  149. if !getFirst {
  150. getFirst = true
  151. waitFirst.Done()
  152. }
  153. }
  154. if !streamStats {
  155. return
  156. }
  157. }
  158. }
  159. func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
  160. var (
  161. cpuPercent = 0.0
  162. // calculate the change for the cpu usage of the container in between readings
  163. cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
  164. // calculate the change for the entire system between readings
  165. systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
  166. )
  167. if systemDelta > 0.0 && cpuDelta > 0.0 {
  168. cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
  169. }
  170. return cpuPercent
  171. }
  172. func calculateCPUPercentWindows(v *types.StatsJSON) float64 {
  173. // Max number of 100ns intervals between the previous time read and now
  174. possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
  175. possIntervals /= 100 // Convert to number of 100ns intervals
  176. possIntervals *= uint64(v.NumProcs) // Multiple by the number of processors
  177. // Intervals used
  178. intervalsUsed := v.CPUStats.CPUUsage.TotalUsage - v.PreCPUStats.CPUUsage.TotalUsage
  179. // Percentage avoiding divide-by-zero
  180. if possIntervals > 0 {
  181. return float64(intervalsUsed) / float64(possIntervals) * 100.0
  182. }
  183. return 0.00
  184. }
  185. func calculateBlockIO(blkio types.BlkioStats) (blkRead uint64, blkWrite uint64) {
  186. for _, bioEntry := range blkio.IoServiceBytesRecursive {
  187. switch strings.ToLower(bioEntry.Op) {
  188. case "read":
  189. blkRead = blkRead + bioEntry.Value
  190. case "write":
  191. blkWrite = blkWrite + bioEntry.Value
  192. }
  193. }
  194. return
  195. }
  196. func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) {
  197. var rx, tx float64
  198. for _, v := range network {
  199. rx += float64(v.RxBytes)
  200. tx += float64(v.TxBytes)
  201. }
  202. return rx, tx
  203. }