dockerd.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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\tNAME\tSIZE\tADDED\n")
  44. for _, layer := range docker.layers {
  45. fmt.Fprintf(w, "%s\t%s\t%.1fM\t%s ago\n", layer.Id, layer.Name, float32(layer.Size) / 1024 / 1024, humanDuration(time.Now().Sub(layer.Added)))
  46. }
  47. w.Flush()
  48. return nil
  49. }
  50. func (docker *Docker) CmdDownload(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  51. if len(args) < 1 {
  52. return errors.New("Not enough arguments")
  53. }
  54. fmt.Fprintf(stdout, "Downloading from %s...\n", args[0])
  55. time.Sleep(2 * time.Second)
  56. return docker.CmdUpload(stdin, stdout, args...)
  57. return nil
  58. }
  59. func (docker *Docker) CmdUpload(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  60. layer := Layer{Id: randomId(), Name: args[0], Added: time.Now(), Size: uint(rand.Int31n(142 * 1024 * 1024))}
  61. docker.layers = append(docker.layers, layer)
  62. time.Sleep(1 * time.Second)
  63. fmt.Fprintf(stdout, "New layer: %s %s %.1fM\n", layer.Id, layer.Name, float32(layer.Size) / 1024 / 1024)
  64. return nil
  65. }
  66. func (docker *Docker) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  67. if len(docker.layers) == 0 {
  68. return errors.New("No layers")
  69. }
  70. container := Container{
  71. Id: randomId(),
  72. Cmd: args[0],
  73. Args: args[1:],
  74. Created: time.Now(),
  75. Layers: docker.layers[:1],
  76. FilesChanged: uint(rand.Int31n(42)),
  77. BytesChanged: uint(rand.Int31n(24 * 1024 * 1024)),
  78. }
  79. docker.containers = append(docker.containers, container)
  80. cmd := exec.Command(args[0], args[1:]...)
  81. cmd_stdin, cmd_stdout, err := startCommand(cmd, false)
  82. if err != nil {
  83. return err
  84. }
  85. copy_out := Go(func() error {
  86. _, err := io.Copy(stdout, cmd_stdout)
  87. return err
  88. })
  89. copy_in := Go(func() error {
  90. //_, err := io.Copy(cmd_stdin, stdin)
  91. cmd_stdin.Close()
  92. stdin.Close()
  93. //return err
  94. return nil
  95. })
  96. if err := cmd.Wait(); err != nil {
  97. return err
  98. }
  99. if err := <-copy_in; err != nil {
  100. return err
  101. }
  102. if err := <-copy_out; err != nil {
  103. return err
  104. }
  105. return nil
  106. }
  107. func startCommand(cmd *exec.Cmd, interactive bool) (io.WriteCloser, io.ReadCloser, error) {
  108. if interactive {
  109. term, err := pty.Start(cmd)
  110. if err != nil {
  111. return nil, nil, err
  112. }
  113. return term, term, nil
  114. }
  115. stdin, err := cmd.StdinPipe()
  116. if err != nil {
  117. return nil, nil, err
  118. }
  119. stdout, err := cmd.StdoutPipe()
  120. if err != nil {
  121. return nil, nil, err
  122. }
  123. if err := cmd.Start(); err != nil {
  124. return nil, nil, err
  125. }
  126. return stdin, stdout, nil
  127. }
  128. func (docker *Docker) CmdList(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  129. var longestCol int
  130. for _, container := range docker.containers {
  131. if l := len(container.CmdString()); l > longestCol {
  132. longestCol = l
  133. }
  134. }
  135. if longestCol > 50 {
  136. longestCol = 50
  137. } else if longestCol < 5 {
  138. longestCol = 8
  139. }
  140. tpl := "%-16s %-*.*s %-6s %-25s %10s %-s\n"
  141. fmt.Fprintf(stdout, tpl, "ID", longestCol, longestCol, "CMD", "STATUS", "CREATED", "CHANGES", "LAYERS")
  142. for _, container := range docker.containers {
  143. var layers []string
  144. for _, layer := range container.Layers {
  145. layers = append(layers, layer.Name)
  146. }
  147. fmt.Fprintf(stdout, tpl,
  148. /* ID */ container.Id,
  149. /* CMD */ longestCol, longestCol, container.CmdString(),
  150. /* STATUS */ "?",
  151. /* CREATED */ humanDuration(time.Now().Sub(container.Created)) + " ago",
  152. /* CHANGES */ fmt.Sprintf("%.1fM", float32(container.BytesChanged) / 1024 / 1024),
  153. /* LAYERS */ strings.Join(layers, ", "))
  154. }
  155. return nil
  156. }
  157. func main() {
  158. rand.Seed(time.Now().UTC().UnixNano())
  159. flag.Parse()
  160. if err := http.ListenAndServe(":4242", new(Docker)); err != nil {
  161. log.Fatal(err)
  162. }
  163. }
  164. type AutoFlush struct {
  165. http.ResponseWriter
  166. }
  167. func (w *AutoFlush) Write(data []byte) (int, error) {
  168. ret, err := w.ResponseWriter.Write(data)
  169. if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
  170. flusher.Flush()
  171. }
  172. return ret, err
  173. }
  174. func (docker *Docker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  175. cmd, args := URLToCall(r.URL)
  176. log.Printf("%s\n", strings.Join(append(append([]string{"docker"}, cmd), args...), " "))
  177. if cmd == "" {
  178. docker.CmdUsage(r.Body, w, "")
  179. return
  180. }
  181. method := docker.getMethod(cmd)
  182. if method == nil {
  183. docker.CmdUsage(r.Body, w, cmd)
  184. } else {
  185. err := method(r.Body, &AutoFlush{w}, args...)
  186. if err != nil {
  187. fmt.Fprintf(w, "Error: %s\n", err)
  188. }
  189. }
  190. }
  191. func (docker *Docker) getMethod(name string) Cmd {
  192. methodName := "Cmd"+strings.ToUpper(name[:1])+strings.ToLower(name[1:])
  193. method, exists := reflect.TypeOf(docker).MethodByName(methodName)
  194. if !exists {
  195. return nil
  196. }
  197. return func(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  198. ret := method.Func.CallSlice([]reflect.Value{
  199. reflect.ValueOf(docker),
  200. reflect.ValueOf(stdin),
  201. reflect.ValueOf(stdout),
  202. reflect.ValueOf(args),
  203. })[0].Interface()
  204. if ret == nil {
  205. return nil
  206. }
  207. return ret.(error)
  208. }
  209. }
  210. func Go(f func() error) chan error {
  211. ch := make(chan error)
  212. go func() {
  213. ch <- f()
  214. }()
  215. return ch
  216. }
  217. type Docker struct {
  218. layers []Layer
  219. containers []Container
  220. }
  221. type Layer struct {
  222. Id string
  223. Name string
  224. Added time.Time
  225. Size uint
  226. }
  227. type Container struct {
  228. Id string
  229. Cmd string
  230. Args []string
  231. Layers []Layer
  232. Created time.Time
  233. FilesChanged uint
  234. BytesChanged uint
  235. }
  236. func (c *Container) CmdString() string {
  237. return strings.Join(append([]string{c.Cmd}, c.Args...), " ")
  238. }
  239. type Cmd func(io.ReadCloser, io.Writer, ...string) error
  240. type CmdMethod func(*Docker, io.ReadCloser, io.Writer, ...string) error
  241. // Use this key to encode an RPC call into an URL,
  242. // eg. domain.tld/path/to/method?q=get_user&q=gordon
  243. const ARG_URL_KEY = "q"
  244. func URLToCall(u *url.URL) (method string, args []string) {
  245. return path.Base(u.Path), u.Query()[ARG_URL_KEY]
  246. }
  247. func randomBytes() io.Reader {
  248. return bytes.NewBuffer([]byte(fmt.Sprintf("%x", rand.Int())))
  249. }
  250. func ComputeId(content io.Reader) (string, error) {
  251. h := sha256.New()
  252. if _, err := io.Copy(h, content); err != nil {
  253. return "", err
  254. }
  255. return fmt.Sprintf("%x", h.Sum(nil)[:8]), nil
  256. }
  257. func randomId() string {
  258. id, _ := ComputeId(randomBytes()) // can't fail
  259. return id
  260. }
  261. func humanDuration(d time.Duration) string {
  262. if seconds := int(d.Seconds()); seconds < 1 {
  263. return "Less than a second"
  264. } else if seconds < 60 {
  265. return fmt.Sprintf("%d seconds", seconds)
  266. } else if minutes := int(d.Minutes()); minutes == 1 {
  267. return "About a minute"
  268. } else if minutes < 60 {
  269. return fmt.Sprintf("%d minutes", minutes)
  270. } else if hours := int(d.Hours()); hours == 1{
  271. return "About an hour"
  272. } else if hours < 48 {
  273. return fmt.Sprintf("%d hours", hours)
  274. } else if hours < 24 * 7 * 2 {
  275. return fmt.Sprintf("%d days", hours / 24)
  276. } else if hours < 24 * 30 * 3 {
  277. return fmt.Sprintf("%d weeks", hours / 24 / 7)
  278. } else if hours < 24 * 365 * 2 {
  279. return fmt.Sprintf("%d months", hours / 24 / 30)
  280. }
  281. return fmt.Sprintf("%d years", d.Hours() / 24 / 365)
  282. }