stats.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "runtime"
  7. "time"
  8. "github.com/containerd/log"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/backend"
  11. "github.com/docker/docker/api/types/versions"
  12. "github.com/docker/docker/api/types/versions/v1p20"
  13. "github.com/docker/docker/container"
  14. "github.com/docker/docker/errdefs"
  15. "github.com/docker/docker/pkg/ioutils"
  16. )
  17. // ContainerStats writes information about the container to the stream
  18. // given in the config object.
  19. func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, config *backend.ContainerStatsConfig) error {
  20. // Engine API version (used for backwards compatibility)
  21. apiVersion := config.Version
  22. if isWindows && versions.LessThan(apiVersion, "1.21") {
  23. return errors.New("API versions pre v1.21 do not support stats on Windows")
  24. }
  25. ctr, err := daemon.GetContainer(prefixOrName)
  26. if err != nil {
  27. return err
  28. }
  29. if config.Stream && config.OneShot {
  30. return errdefs.InvalidParameter(errors.New("cannot have stream=true and one-shot=true"))
  31. }
  32. // If the container is either not running or restarting and requires no stream, return an empty stats.
  33. if (!ctr.IsRunning() || ctr.IsRestarting()) && !config.Stream {
  34. return json.NewEncoder(config.OutStream).Encode(&types.StatsJSON{
  35. Name: ctr.Name,
  36. ID: ctr.ID,
  37. })
  38. }
  39. // Get container stats directly if OneShot is set
  40. if config.OneShot {
  41. stats, err := daemon.GetContainerStats(ctr)
  42. if err != nil {
  43. return err
  44. }
  45. return json.NewEncoder(config.OutStream).Encode(stats)
  46. }
  47. outStream := config.OutStream
  48. if config.Stream {
  49. wf := ioutils.NewWriteFlusher(outStream)
  50. defer wf.Close()
  51. wf.Flush()
  52. outStream = wf
  53. }
  54. var preCPUStats types.CPUStats
  55. var preRead time.Time
  56. getStatJSON := func(v interface{}) *types.StatsJSON {
  57. ss := v.(types.StatsJSON)
  58. ss.Name = ctr.Name
  59. ss.ID = ctr.ID
  60. ss.PreCPUStats = preCPUStats
  61. ss.PreRead = preRead
  62. preCPUStats = ss.CPUStats
  63. preRead = ss.Read
  64. return &ss
  65. }
  66. enc := json.NewEncoder(outStream)
  67. updates := daemon.subscribeToContainerStats(ctr)
  68. defer daemon.unsubscribeToContainerStats(ctr, updates)
  69. noStreamFirstFrame := !config.OneShot
  70. for {
  71. select {
  72. case v, ok := <-updates:
  73. if !ok {
  74. return nil
  75. }
  76. var statsJSON interface{}
  77. statsJSONPost120 := getStatJSON(v)
  78. if versions.LessThan(apiVersion, "1.21") {
  79. var (
  80. rxBytes uint64
  81. rxPackets uint64
  82. rxErrors uint64
  83. rxDropped uint64
  84. txBytes uint64
  85. txPackets uint64
  86. txErrors uint64
  87. txDropped uint64
  88. )
  89. for _, v := range statsJSONPost120.Networks {
  90. rxBytes += v.RxBytes
  91. rxPackets += v.RxPackets
  92. rxErrors += v.RxErrors
  93. rxDropped += v.RxDropped
  94. txBytes += v.TxBytes
  95. txPackets += v.TxPackets
  96. txErrors += v.TxErrors
  97. txDropped += v.TxDropped
  98. }
  99. statsJSON = &v1p20.StatsJSON{
  100. Stats: statsJSONPost120.Stats,
  101. Network: types.NetworkStats{
  102. RxBytes: rxBytes,
  103. RxPackets: rxPackets,
  104. RxErrors: rxErrors,
  105. RxDropped: rxDropped,
  106. TxBytes: txBytes,
  107. TxPackets: txPackets,
  108. TxErrors: txErrors,
  109. TxDropped: txDropped,
  110. },
  111. }
  112. } else {
  113. statsJSON = statsJSONPost120
  114. }
  115. if !config.Stream && noStreamFirstFrame {
  116. // prime the cpu stats so they aren't 0 in the final output
  117. noStreamFirstFrame = false
  118. continue
  119. }
  120. if err := enc.Encode(statsJSON); err != nil {
  121. return err
  122. }
  123. if !config.Stream {
  124. return nil
  125. }
  126. case <-ctx.Done():
  127. return nil
  128. }
  129. }
  130. }
  131. func (daemon *Daemon) subscribeToContainerStats(c *container.Container) chan interface{} {
  132. return daemon.statsCollector.Collect(c)
  133. }
  134. func (daemon *Daemon) unsubscribeToContainerStats(c *container.Container, ch chan interface{}) {
  135. daemon.statsCollector.Unsubscribe(c, ch)
  136. }
  137. // GetContainerStats collects all the stats published by a container
  138. func (daemon *Daemon) GetContainerStats(container *container.Container) (*types.StatsJSON, error) {
  139. stats, err := daemon.stats(container)
  140. if err != nil {
  141. goto done
  142. }
  143. // Sample system CPU usage close to container usage to avoid
  144. // noise in metric calculations.
  145. // FIXME: move to containerd on Linux (not Windows)
  146. stats.CPUStats.SystemUsage, stats.CPUStats.OnlineCPUs, err = getSystemCPUUsage()
  147. if err != nil {
  148. goto done
  149. }
  150. // We already have the network stats on Windows directly from HCS.
  151. if !container.Config.NetworkDisabled && runtime.GOOS != "windows" {
  152. stats.Networks, err = daemon.getNetworkStats(container)
  153. }
  154. done:
  155. switch err.(type) {
  156. case nil:
  157. return stats, nil
  158. case errdefs.ErrConflict, errdefs.ErrNotFound:
  159. // return empty stats containing only name and ID if not running or not found
  160. return &types.StatsJSON{
  161. Name: container.Name,
  162. ID: container.ID,
  163. }, nil
  164. default:
  165. log.G(context.TODO()).Errorf("collecting stats for container %s: %v", container.Name, err)
  166. return nil, err
  167. }
  168. }