containers.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package docker
  2. /*
  3. containers.go
  4. Container listing and lifecycle (start/stop/restart/remove/inspect). Every
  5. container reference coming from a request is validated against a strict
  6. charset before it is handed to the docker CLI: because args are passed as
  7. discrete exec.Command elements there is no shell to inject into, but the
  8. validation additionally prevents a value like "-x" from being interpreted as
  9. a docker flag.
  10. */
  11. import (
  12. "encoding/json"
  13. "errors"
  14. "net/http"
  15. "regexp"
  16. "strings"
  17. "imuslab.com/arozos/mod/utils"
  18. )
  19. // containerRefRegex matches valid docker container IDs and names. Names cannot
  20. // start with a dash, which also blocks flag-injection through a reference.
  21. var containerRefRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)
  22. // ContainerInfo mirrors the subset of `docker ps -a --format "{{json .}}"`
  23. // per-line output that the UI consumes. The docker CLI emits every value as a
  24. // string.
  25. type ContainerInfo struct {
  26. ID string `json:"ID"`
  27. Names string `json:"Names"`
  28. Image string `json:"Image"`
  29. Command string `json:"Command"`
  30. State string `json:"State"`
  31. Status string `json:"Status"`
  32. Ports string `json:"Ports"`
  33. CreatedAt string `json:"CreatedAt"`
  34. RunningFor string `json:"RunningFor"`
  35. Size string `json:"Size"`
  36. }
  37. // validateContainerRef rejects empty or malformed container references.
  38. func validateContainerRef(ref string) error {
  39. if ref == "" {
  40. return errors.New("empty container reference")
  41. }
  42. if !containerRefRegex.MatchString(ref) {
  43. return errors.New("invalid container reference")
  44. }
  45. return nil
  46. }
  47. // ListContainers returns all containers, running and stopped.
  48. func (d *DockerManager) ListContainers() ([]ContainerInfo, error) {
  49. out, err := runDocker("ps", "-a", "--no-trunc", "--format", "{{json .}}")
  50. if err != nil {
  51. return nil, err
  52. }
  53. return parseContainerList(out)
  54. }
  55. // parseContainerList parses the line-delimited JSON of `docker ps`. Malformed
  56. // lines are skipped defensively rather than failing the whole listing.
  57. func parseContainerList(out []byte) ([]ContainerInfo, error) {
  58. results := []ContainerInfo{}
  59. for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
  60. line = strings.TrimSpace(line)
  61. if line == "" {
  62. continue
  63. }
  64. var c ContainerInfo
  65. if err := json.Unmarshal([]byte(line), &c); err != nil {
  66. continue
  67. }
  68. results = append(results, c)
  69. }
  70. return results, nil
  71. }
  72. // simpleContainerAction runs a one-argument docker subcommand (start/stop/
  73. // restart) against a validated container reference.
  74. func (d *DockerManager) simpleContainerAction(action, ref string) error {
  75. if err := validateContainerRef(ref); err != nil {
  76. return err
  77. }
  78. _, err := runDocker(action, ref)
  79. return err
  80. }
  81. // RemoveContainer force-removes a container (stopping it first if running).
  82. func (d *DockerManager) RemoveContainer(ref string) error {
  83. if err := validateContainerRef(ref); err != nil {
  84. return err
  85. }
  86. _, err := runDocker("rm", "-f", ref)
  87. return err
  88. }
  89. // InspectContainer returns the raw `docker inspect` JSON for one container.
  90. func (d *DockerManager) InspectContainer(ref string) ([]byte, error) {
  91. if err := validateContainerRef(ref); err != nil {
  92. return nil, err
  93. }
  94. return runDocker("inspect", ref)
  95. }
  96. /* ---------- HTTP handlers (registered admin-only in src/docker.go) ---------- */
  97. // HandleContainerList serves the full container list as JSON.
  98. func (d *DockerManager) HandleContainerList(w http.ResponseWriter, r *http.Request) {
  99. containers, err := d.ListContainers()
  100. if err != nil {
  101. utils.SendErrorResponse(w, err.Error())
  102. return
  103. }
  104. js, _ := json.Marshal(containers)
  105. utils.SendJSONResponse(w, string(js))
  106. }
  107. // HandleContainerInspect serves raw inspect JSON for one container.
  108. func (d *DockerManager) HandleContainerInspect(w http.ResponseWriter, r *http.Request) {
  109. ref, err := utils.GetPara(r, "id")
  110. if err != nil {
  111. utils.SendErrorResponse(w, "missing container id")
  112. return
  113. }
  114. out, err := d.InspectContainer(ref)
  115. if err != nil {
  116. utils.SendErrorResponse(w, err.Error())
  117. return
  118. }
  119. utils.SendJSONResponse(w, string(out))
  120. }
  121. // handleContainerAction is the shared POST handler body for start/stop/restart/
  122. // remove. actionFn performs the work for the validated reference.
  123. func (d *DockerManager) handleContainerAction(w http.ResponseWriter, r *http.Request, actionFn func(ref string) error) {
  124. if r.Method != http.MethodPost {
  125. utils.SendErrorResponse(w, "method not allowed")
  126. return
  127. }
  128. ref, err := utils.PostPara(r, "id")
  129. if err != nil {
  130. utils.SendErrorResponse(w, "missing container id")
  131. return
  132. }
  133. if err := actionFn(ref); err != nil {
  134. utils.SendErrorResponse(w, err.Error())
  135. return
  136. }
  137. utils.SendOK(w)
  138. }
  139. func (d *DockerManager) HandleContainerStart(w http.ResponseWriter, r *http.Request) {
  140. d.handleContainerAction(w, r, func(ref string) error { return d.simpleContainerAction("start", ref) })
  141. }
  142. func (d *DockerManager) HandleContainerStop(w http.ResponseWriter, r *http.Request) {
  143. d.handleContainerAction(w, r, func(ref string) error { return d.simpleContainerAction("stop", ref) })
  144. }
  145. func (d *DockerManager) HandleContainerRestart(w http.ResponseWriter, r *http.Request) {
  146. d.handleContainerAction(w, r, func(ref string) error { return d.simpleContainerAction("restart", ref) })
  147. }
  148. func (d *DockerManager) HandleContainerRemove(w http.ResponseWriter, r *http.Request) {
  149. d.handleContainerAction(w, r, d.RemoveContainer)
  150. }