stats_helpers.go 5.9 KB

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