system_routes.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. "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. if err := httputils.ParseForm(r); err != nil {
  83. return err
  84. }
  85. version := httputils.VersionFromContext(ctx)
  86. var getContainers, getImages, getVolumes, getBuildCache bool
  87. typeStrs, ok := r.Form["type"]
  88. if versions.LessThan(version, "1.42") || !ok {
  89. getContainers, getImages, getVolumes, getBuildCache = true, true, true, true
  90. } else {
  91. for _, typ := range typeStrs {
  92. switch types.DiskUsageObject(typ) {
  93. case types.ContainerObject:
  94. getContainers = true
  95. case types.ImageObject:
  96. getImages = true
  97. case types.VolumeObject:
  98. getVolumes = true
  99. case types.BuildCacheObject:
  100. getBuildCache = true
  101. default:
  102. return invalidRequestError{Err: fmt.Errorf("unknown object type: %s", typ)}
  103. }
  104. }
  105. }
  106. eg, ctx := errgroup.WithContext(ctx)
  107. var systemDiskUsage *types.DiskUsage
  108. if getContainers || getImages || getVolumes {
  109. eg.Go(func() error {
  110. var err error
  111. systemDiskUsage, err = s.backend.SystemDiskUsage(ctx, DiskUsageOptions{
  112. Containers: getContainers,
  113. Images: getImages,
  114. Volumes: getVolumes,
  115. })
  116. return err
  117. })
  118. }
  119. var buildCache []*types.BuildCache
  120. if getBuildCache {
  121. eg.Go(func() error {
  122. var err error
  123. buildCache, err = s.builder.DiskUsage(ctx)
  124. if err != nil {
  125. return errors.Wrap(err, "error getting build cache usage")
  126. }
  127. if buildCache == nil {
  128. // Ensure empty `BuildCache` field is represented as empty JSON array(`[]`)
  129. // instead of `null` to be consistent with `Images`, `Containers` etc.
  130. buildCache = []*types.BuildCache{}
  131. }
  132. return nil
  133. })
  134. }
  135. if err := eg.Wait(); err != nil {
  136. return err
  137. }
  138. var builderSize int64
  139. if versions.LessThan(version, "1.42") {
  140. for _, b := range buildCache {
  141. builderSize += b.Size
  142. }
  143. }
  144. du := types.DiskUsage{
  145. BuildCache: buildCache,
  146. BuilderSize: builderSize,
  147. }
  148. if systemDiskUsage != nil {
  149. du.LayersSize = systemDiskUsage.LayersSize
  150. du.Images = systemDiskUsage.Images
  151. du.Containers = systemDiskUsage.Containers
  152. du.Volumes = systemDiskUsage.Volumes
  153. }
  154. return httputils.WriteJSON(w, http.StatusOK, du)
  155. }
  156. type invalidRequestError struct {
  157. Err error
  158. }
  159. func (e invalidRequestError) Error() string {
  160. return e.Err.Error()
  161. }
  162. func (e invalidRequestError) InvalidParameter() {}
  163. func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  164. if err := httputils.ParseForm(r); err != nil {
  165. return err
  166. }
  167. since, err := eventTime(r.Form.Get("since"))
  168. if err != nil {
  169. return err
  170. }
  171. until, err := eventTime(r.Form.Get("until"))
  172. if err != nil {
  173. return err
  174. }
  175. var (
  176. timeout <-chan time.Time
  177. onlyPastEvents bool
  178. )
  179. if !until.IsZero() {
  180. if until.Before(since) {
  181. return invalidRequestError{fmt.Errorf("`since` time (%s) cannot be after `until` time (%s)", r.Form.Get("since"), r.Form.Get("until"))}
  182. }
  183. now := time.Now()
  184. onlyPastEvents = until.Before(now)
  185. if !onlyPastEvents {
  186. dur := until.Sub(now)
  187. timer := time.NewTimer(dur)
  188. defer timer.Stop()
  189. timeout = timer.C
  190. }
  191. }
  192. ef, err := filters.FromJSON(r.Form.Get("filters"))
  193. if err != nil {
  194. return err
  195. }
  196. w.Header().Set("Content-Type", "application/json")
  197. output := ioutils.NewWriteFlusher(w)
  198. defer output.Close()
  199. output.Flush()
  200. enc := json.NewEncoder(output)
  201. buffered, l := s.backend.SubscribeToEvents(since, until, ef)
  202. defer s.backend.UnsubscribeFromEvents(l)
  203. for _, ev := range buffered {
  204. if err := enc.Encode(ev); err != nil {
  205. return err
  206. }
  207. }
  208. if onlyPastEvents {
  209. return nil
  210. }
  211. for {
  212. select {
  213. case ev := <-l:
  214. jev, ok := ev.(events.Message)
  215. if !ok {
  216. logrus.Warnf("unexpected event message: %q", ev)
  217. continue
  218. }
  219. if err := enc.Encode(jev); err != nil {
  220. return err
  221. }
  222. case <-timeout:
  223. return nil
  224. case <-ctx.Done():
  225. logrus.Debug("Client context cancelled, stop sending events")
  226. return nil
  227. }
  228. }
  229. }
  230. func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  231. var config *types.AuthConfig
  232. err := json.NewDecoder(r.Body).Decode(&config)
  233. r.Body.Close()
  234. if err != nil {
  235. return err
  236. }
  237. status, token, err := s.backend.AuthenticateToRegistry(ctx, config)
  238. if err != nil {
  239. return err
  240. }
  241. return httputils.WriteJSON(w, http.StatusOK, &registry.AuthenticateOKBody{
  242. Status: status,
  243. IdentityToken: token,
  244. })
  245. }
  246. func eventTime(formTime string) (time.Time, error) {
  247. t, tNano, err := timetypes.ParseTimestamps(formTime, -1)
  248. if err != nil {
  249. return time.Time{}, err
  250. }
  251. if t == -1 {
  252. return time.Time{}, nil
  253. }
  254. return time.Unix(t, tNano), nil
  255. }