dockerd.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package main
  2. import (
  3. "errors"
  4. "log"
  5. "io"
  6. // "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "os/exec"
  10. "flag"
  11. "reflect"
  12. "fmt"
  13. "github.com/kr/pty"
  14. "path"
  15. "strings"
  16. "time"
  17. "math/rand"
  18. "crypto/sha256"
  19. "bytes"
  20. "text/tabwriter"
  21. )
  22. func (docker *Docker) CmdUsage(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  23. fmt.Fprintf(stdout, "Usage: docker COMMAND [arg...]\n\nCommands:\n")
  24. for _, cmd := range [][]interface{}{
  25. {"run", "Run a command in a container"},
  26. {"list", "Display a list of containers"},
  27. {"layers", "Display a list of layers"},
  28. {"download", "Download a layer from a remote location"},
  29. {"upload", "Upload a layer"},
  30. {"wait", "Wait for the state of a container to change"},
  31. {"stop", "Stop a running container"},
  32. {"logs", "Fetch the logs of a container"},
  33. {"export", "Extract changes to a container's filesystem into a new layer"},
  34. {"attach", "Attach to the standard inputs and outputs of a running container"},
  35. {"info", "Display system-wide information"},
  36. } {
  37. fmt.Fprintf(stdout, " %-10.10s%s\n", cmd...)
  38. }
  39. return nil
  40. }
  41. func (docker *Docker) CmdLayers(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  42. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  43. fmt.Fprintf(w, "ID\tSOURCE\tADDED\n")
  44. for _, layer := range docker.layers {
  45. fmt.Fprintf(w, "%s\t%s\t%s ago\n", layer.Id, layer.Name, time.Now().Sub(layer.Added))
  46. }
  47. w.Flush()
  48. return nil
  49. }
  50. func (docker *Docker) CmdUpload(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  51. layer := Layer{Id: randomId(), Name: args[0], Added: time.Now()}
  52. docker.layers = append(docker.layers, layer)
  53. fmt.Fprintf(stdout, "New layer: %s (%s)\n", layer.Id, layer.Name)
  54. return nil
  55. }
  56. func (docker *Docker) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  57. if len(docker.layers) == 0 {
  58. return errors.New("No layers")
  59. }
  60. container := Container{
  61. Id: randomId(),
  62. Cmd: args[0],
  63. Args: args[1:],
  64. Layers: docker.layers[:1],
  65. }
  66. docker.containers = append(docker.containers, container)
  67. cmd := exec.Command(args[0], args[1:]...)
  68. cmd_stdin, cmd_stdout, err := startCommand(cmd, false)
  69. if err != nil {
  70. return err
  71. }
  72. copy_out := Go(func() error {
  73. _, err := io.Copy(stdout, cmd_stdout)
  74. return err
  75. })
  76. copy_in := Go(func() error {
  77. //_, err := io.Copy(cmd_stdin, stdin)
  78. cmd_stdin.Close()
  79. stdin.Close()
  80. //return err
  81. return nil
  82. })
  83. if err := cmd.Wait(); err != nil {
  84. return err
  85. }
  86. if err := <-copy_in; err != nil {
  87. return err
  88. }
  89. if err := <-copy_out; err != nil {
  90. return err
  91. }
  92. return nil
  93. }
  94. func startCommand(cmd *exec.Cmd, interactive bool) (io.WriteCloser, io.ReadCloser, error) {
  95. if interactive {
  96. term, err := pty.Start(cmd)
  97. if err != nil {
  98. return nil, nil, err
  99. }
  100. return term, term, nil
  101. }
  102. stdin, err := cmd.StdinPipe()
  103. if err != nil {
  104. return nil, nil, err
  105. }
  106. stdout, err := cmd.StdoutPipe()
  107. if err != nil {
  108. return nil, nil, err
  109. }
  110. if err := cmd.Start(); err != nil {
  111. return nil, nil, err
  112. }
  113. return stdin, stdout, nil
  114. }
  115. func (docker *Docker) CmdList(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  116. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  117. fmt.Fprintf(w, "ID\tCMD\tSTATUS\tLAYERS\n")
  118. for _, container := range docker.containers {
  119. var layers []string
  120. for _, layer := range container.Layers {
  121. layers = append(layers, layer.Name)
  122. }
  123. fmt.Fprintf(w, "%s\t%s %s\t?\t%s\n",
  124. container.Id,
  125. container.Cmd,
  126. strings.Join(container.Args, " "),
  127. strings.Join(layers, ", "))
  128. }
  129. w.Flush()
  130. return nil
  131. }
  132. func main() {
  133. rand.Seed(time.Now().UTC().UnixNano())
  134. flag.Parse()
  135. if err := http.ListenAndServe(":4242", new(Docker)); err != nil {
  136. log.Fatal(err)
  137. }
  138. }
  139. func (docker *Docker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  140. cmd, args := URLToCall(r.URL)
  141. method := docker.getMethod(cmd)
  142. if method == nil {
  143. docker.CmdUsage(r.Body, w, cmd)
  144. } else {
  145. err := method(r.Body, w, args...)
  146. if err != nil {
  147. fmt.Fprintf(w, "Error: %s\n", err)
  148. }
  149. }
  150. }
  151. func (docker *Docker) getMethod(name string) Cmd {
  152. methodName := "Cmd"+strings.ToUpper(name[:1])+strings.ToLower(name[1:])
  153. method, exists := reflect.TypeOf(docker).MethodByName(methodName)
  154. if !exists {
  155. return nil
  156. }
  157. return func(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  158. ret := method.Func.CallSlice([]reflect.Value{
  159. reflect.ValueOf(docker),
  160. reflect.ValueOf(stdin),
  161. reflect.ValueOf(stdout),
  162. reflect.ValueOf(args),
  163. })[0].Interface()
  164. if ret == nil {
  165. return nil
  166. }
  167. return ret.(error)
  168. }
  169. }
  170. func Go(f func() error) chan error {
  171. ch := make(chan error)
  172. go func() {
  173. ch <- f()
  174. }()
  175. return ch
  176. }
  177. type Docker struct {
  178. layers []Layer
  179. containers []Container
  180. }
  181. type Layer struct {
  182. Id string
  183. Name string
  184. Added time.Time
  185. }
  186. type Container struct {
  187. Id string
  188. Cmd string
  189. Args []string
  190. Layers []Layer
  191. }
  192. type Cmd func(io.ReadCloser, io.Writer, ...string) error
  193. type CmdMethod func(*Docker, io.ReadCloser, io.Writer, ...string) error
  194. // Use this key to encode an RPC call into an URL,
  195. // eg. domain.tld/path/to/method?q=get_user&q=gordon
  196. const ARG_URL_KEY = "q"
  197. func URLToCall(u *url.URL) (method string, args []string) {
  198. return path.Base(u.Path), u.Query()[ARG_URL_KEY]
  199. }
  200. func randomBytes() io.Reader {
  201. return bytes.NewBuffer([]byte(fmt.Sprintf("%x", rand.Int())))
  202. }
  203. func ComputeId(content io.Reader) (string, error) {
  204. h := sha256.New()
  205. if _, err := io.Copy(h, content); err != nil {
  206. return "", err
  207. }
  208. return fmt.Sprintf("%x", h.Sum(nil)[:8]), nil
  209. }
  210. func randomId() string {
  211. id, _ := ComputeId(randomBytes()) // can't fail
  212. return id
  213. }