system_routes.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package system // import "github.com/docker/docker/api/server/router/system"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "time"
  8. "github.com/docker/docker/api/server/httputils"
  9. "github.com/docker/docker/api/server/router/build"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/events"
  12. "github.com/docker/docker/api/types/filters"
  13. "github.com/docker/docker/api/types/registry"
  14. timetypes "github.com/docker/docker/api/types/time"
  15. "github.com/docker/docker/api/types/versions"
  16. "github.com/docker/docker/pkg/ioutils"
  17. pkgerrors "github.com/pkg/errors"
  18. "github.com/sirupsen/logrus"
  19. "golang.org/x/sync/errgroup"
  20. )
  21. func optionsHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  22. w.WriteHeader(http.StatusOK)
  23. return nil
  24. }
  25. func (s *systemRouter) pingHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  26. w.Header().Add("Cache-Control", "no-cache, no-store, must-revalidate")
  27. w.Header().Add("Pragma", "no-cache")
  28. builderVersion := build.BuilderVersion(*s.features)
  29. if bv := builderVersion; bv != "" {
  30. w.Header().Set("Builder-Version", string(bv))
  31. }
  32. if r.Method == http.MethodHead {
  33. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  34. w.Header().Set("Content-Length", "0")
  35. return nil
  36. }
  37. _, err := w.Write([]byte{'O', 'K'})
  38. return err
  39. }
  40. func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  41. info := s.backend.SystemInfo()
  42. if s.cluster != nil {
  43. info.Swarm = s.cluster.Info()
  44. info.Warnings = append(info.Warnings, info.Swarm.Warnings...)
  45. }
  46. if versions.LessThan(httputils.VersionFromContext(ctx), "1.25") {
  47. // TODO: handle this conversion in engine-api
  48. type oldInfo struct {
  49. *types.Info
  50. ExecutionDriver string
  51. }
  52. old := &oldInfo{
  53. Info: info,
  54. ExecutionDriver: "<not supported>",
  55. }
  56. nameOnlySecurityOptions := []string{}
  57. kvSecOpts, err := types.DecodeSecurityOptions(old.SecurityOptions)
  58. if err != nil {
  59. return err
  60. }
  61. for _, s := range kvSecOpts {
  62. nameOnlySecurityOptions = append(nameOnlySecurityOptions, s.Name)
  63. }
  64. old.SecurityOptions = nameOnlySecurityOptions
  65. return httputils.WriteJSON(w, http.StatusOK, old)
  66. }
  67. if versions.LessThan(httputils.VersionFromContext(ctx), "1.39") {
  68. if info.KernelVersion == "" {
  69. info.KernelVersion = "<unknown>"
  70. }
  71. if info.OperatingSystem == "" {
  72. info.OperatingSystem = "<unknown>"
  73. }
  74. }
  75. return httputils.WriteJSON(w, http.StatusOK, info)
  76. }
  77. func (s *systemRouter) getVersion(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  78. info := s.backend.SystemVersion()
  79. return httputils.WriteJSON(w, http.StatusOK, info)
  80. }
  81. func (s *systemRouter) getDiskUsage(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  82. eg, ctx := errgroup.WithContext(ctx)
  83. var du *types.DiskUsage
  84. eg.Go(func() error {
  85. var err error
  86. du, err = s.backend.SystemDiskUsage(ctx)
  87. return err
  88. })
  89. var buildCache []*types.BuildCache
  90. eg.Go(func() error {
  91. var err error
  92. buildCache, err = s.builder.DiskUsage(ctx)
  93. if err != nil {
  94. return pkgerrors.Wrap(err, "error getting build cache usage")
  95. }
  96. return nil
  97. })
  98. if err := eg.Wait(); err != nil {
  99. return err
  100. }
  101. if versions.LessThan(httputils.VersionFromContext(ctx), "1.42") {
  102. var builderSize int64
  103. for _, b := range buildCache {
  104. builderSize += b.Size
  105. }
  106. du.BuilderSize = builderSize
  107. }
  108. du.BuildCache = buildCache
  109. if buildCache == nil {
  110. // Ensure empty `BuildCache` field is represented as empty JSON array(`[]`)
  111. // instead of `null` to be consistent with `Images`, `Containers` etc.
  112. du.BuildCache = []*types.BuildCache{}
  113. }
  114. return httputils.WriteJSON(w, http.StatusOK, du)
  115. }
  116. type invalidRequestError struct {
  117. Err error
  118. }
  119. func (e invalidRequestError) Error() string {
  120. return e.Err.Error()
  121. }
  122. func (e invalidRequestError) InvalidParameter() {}
  123. func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  124. if err := httputils.ParseForm(r); err != nil {
  125. return err
  126. }
  127. since, err := eventTime(r.Form.Get("since"))
  128. if err != nil {
  129. return err
  130. }
  131. until, err := eventTime(r.Form.Get("until"))
  132. if err != nil {
  133. return err
  134. }
  135. var (
  136. timeout <-chan time.Time
  137. onlyPastEvents bool
  138. )
  139. if !until.IsZero() {
  140. if until.Before(since) {
  141. return invalidRequestError{fmt.Errorf("`since` time (%s) cannot be after `until` time (%s)", r.Form.Get("since"), r.Form.Get("until"))}
  142. }
  143. now := time.Now()
  144. onlyPastEvents = until.Before(now)
  145. if !onlyPastEvents {
  146. dur := until.Sub(now)
  147. timer := time.NewTimer(dur)
  148. defer timer.Stop()
  149. timeout = timer.C
  150. }
  151. }
  152. ef, err := filters.FromJSON(r.Form.Get("filters"))
  153. if err != nil {
  154. return err
  155. }
  156. w.Header().Set("Content-Type", "application/json")
  157. output := ioutils.NewWriteFlusher(w)
  158. defer output.Close()
  159. output.Flush()
  160. enc := json.NewEncoder(output)
  161. buffered, l := s.backend.SubscribeToEvents(since, until, ef)
  162. defer s.backend.UnsubscribeFromEvents(l)
  163. for _, ev := range buffered {
  164. if err := enc.Encode(ev); err != nil {
  165. return err
  166. }
  167. }
  168. if onlyPastEvents {
  169. return nil
  170. }
  171. for {
  172. select {
  173. case ev := <-l:
  174. jev, ok := ev.(events.Message)
  175. if !ok {
  176. logrus.Warnf("unexpected event message: %q", ev)
  177. continue
  178. }
  179. if err := enc.Encode(jev); err != nil {
  180. return err
  181. }
  182. case <-timeout:
  183. return nil
  184. case <-ctx.Done():
  185. logrus.Debug("Client context cancelled, stop sending events")
  186. return nil
  187. }
  188. }
  189. }
  190. func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  191. var config *types.AuthConfig
  192. err := json.NewDecoder(r.Body).Decode(&config)
  193. r.Body.Close()
  194. if err != nil {
  195. return err
  196. }
  197. status, token, err := s.backend.AuthenticateToRegistry(ctx, config)
  198. if err != nil {
  199. return err
  200. }
  201. return httputils.WriteJSON(w, http.StatusOK, &registry.AuthenticateOKBody{
  202. Status: status,
  203. IdentityToken: token,
  204. })
  205. }
  206. func eventTime(formTime string) (time.Time, error) {
  207. t, tNano, err := timetypes.ParseTimestamps(formTime, -1)
  208. if err != nil {
  209. return time.Time{}, err
  210. }
  211. if t == -1 {
  212. return time.Time{}, nil
  213. }
  214. return time.Unix(t, tNano), nil
  215. }