stats_helpers.go 7.8 KB

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