commands.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/dotcloud/docker/auth"
  8. "github.com/dotcloud/docker/graph"
  9. "github.com/dotcloud/docker/rcli"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "math/rand"
  14. "net/http"
  15. "net/url"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "text/tabwriter"
  21. "time"
  22. )
  23. const VERSION = "0.0.3"
  24. func (srv *Server) Name() string {
  25. return "docker"
  26. }
  27. // FIXME: Stop violating DRY by repeating usage here and in Subcmd declarations
  28. func (srv *Server) Help() string {
  29. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  30. for _, cmd := range [][]interface{}{
  31. {"run", "Run a command in a container"},
  32. {"ps", "Display a list of containers"},
  33. {"import", "Create a new filesystem image from the contents of a tarball"},
  34. {"attach", "Attach to a running container"},
  35. {"commit", "Create a new image from a container's changes"},
  36. {"diff", "Inspect changes on a container's filesystem"},
  37. {"images", "List images"},
  38. {"info", "Display system-wide information"},
  39. {"inspect", "Return low-level information on a container"},
  40. {"kill", "Kill a running container"},
  41. {"login", "Register or Login to the docker registry server"},
  42. {"logs", "Fetch the logs of a container"},
  43. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  44. {"ps", "List containers"},
  45. {"restart", "Restart a running container"},
  46. {"rm", "Remove a container"},
  47. {"rmi", "Remove an image"},
  48. {"run", "Run a command in a new container"},
  49. {"start", "Start a stopped container"},
  50. {"stop", "Stop a running container"},
  51. {"export", "Stream the contents of a container as a tar archive"},
  52. {"version", "Show the docker version information"},
  53. {"wait", "Block until a container stops, then print its exit code"},
  54. } {
  55. help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1])
  56. }
  57. return help
  58. }
  59. // 'docker login': login / register a user to registry service.
  60. func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  61. cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server")
  62. if err := cmd.Parse(args); err != nil {
  63. return nil
  64. }
  65. var username string
  66. var password string
  67. var email string
  68. authConfig, err := auth.LoadConfig()
  69. if err != nil {
  70. fmt.Fprintf(stdout, "Error : %s\n", err)
  71. }
  72. fmt.Fprint(stdout, "Username (", authConfig.Username, "): ")
  73. fmt.Fscanf(stdin, "%s", &username)
  74. if username == "" {
  75. username = authConfig.Username
  76. }
  77. if username != authConfig.Username {
  78. fmt.Fprint(stdout, "Password: ")
  79. fmt.Fscanf(stdin, "%s", &password)
  80. if password == "" {
  81. return errors.New("Error : Password Required\n")
  82. }
  83. fmt.Fprint(stdout, "Email (", authConfig.Email, "): ")
  84. fmt.Fscanf(stdin, "%s", &email)
  85. if email == "" {
  86. email = authConfig.Email
  87. }
  88. } else {
  89. password = authConfig.Password
  90. email = authConfig.Email
  91. }
  92. newAuthConfig := auth.AuthConfig{Username: username, Password: password, Email: email}
  93. status, err := auth.Login(newAuthConfig)
  94. if err != nil {
  95. fmt.Fprintf(stdout, "Error : %s\n", err)
  96. }
  97. if status != "" {
  98. fmt.Fprintf(stdout, status)
  99. }
  100. return nil
  101. }
  102. // 'docker wait': block until a container stops
  103. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  104. cmd := rcli.Subcmd(stdout, "wait", "[OPTIONS] NAME", "Block until a container stops, then print its exit code.")
  105. if err := cmd.Parse(args); err != nil {
  106. return nil
  107. }
  108. if cmd.NArg() < 1 {
  109. cmd.Usage()
  110. return nil
  111. }
  112. for _, name := range cmd.Args() {
  113. if container := srv.runtime.Get(name); container != nil {
  114. fmt.Fprintln(stdout, container.Wait())
  115. } else {
  116. return errors.New("No such container: " + name)
  117. }
  118. }
  119. return nil
  120. }
  121. // 'docker version': show version information
  122. func (srv *Server) CmdVersion(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  123. fmt.Fprintf(stdout, "Version:%s\n", VERSION)
  124. return nil
  125. }
  126. // 'docker info': display system-wide information.
  127. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  128. images, _ := srv.runtime.graph.All()
  129. var imgcount int
  130. if images == nil {
  131. imgcount = 0
  132. } else {
  133. imgcount = len(images)
  134. }
  135. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  136. if err := cmd.Parse(args); err != nil {
  137. return nil
  138. }
  139. if cmd.NArg() > 0 {
  140. cmd.Usage()
  141. return nil
  142. }
  143. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  144. len(srv.runtime.List()),
  145. VERSION,
  146. imgcount)
  147. return nil
  148. }
  149. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  150. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  151. if err := cmd.Parse(args); err != nil {
  152. return nil
  153. }
  154. if cmd.NArg() < 1 {
  155. cmd.Usage()
  156. return nil
  157. }
  158. for _, name := range cmd.Args() {
  159. if container := srv.runtime.Get(name); container != nil {
  160. if err := container.Stop(); err != nil {
  161. return err
  162. }
  163. fmt.Fprintln(stdout, container.Id)
  164. } else {
  165. return errors.New("No such container: " + name)
  166. }
  167. }
  168. return nil
  169. }
  170. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  171. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  172. if err := cmd.Parse(args); err != nil {
  173. return nil
  174. }
  175. if cmd.NArg() < 1 {
  176. cmd.Usage()
  177. return nil
  178. }
  179. for _, name := range cmd.Args() {
  180. if container := srv.runtime.Get(name); container != nil {
  181. if err := container.Restart(); err != nil {
  182. return err
  183. }
  184. fmt.Fprintln(stdout, container.Id)
  185. } else {
  186. return errors.New("No such container: " + name)
  187. }
  188. }
  189. return nil
  190. }
  191. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  192. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  193. if err := cmd.Parse(args); err != nil {
  194. return nil
  195. }
  196. if cmd.NArg() < 1 {
  197. cmd.Usage()
  198. return nil
  199. }
  200. for _, name := range cmd.Args() {
  201. if container := srv.runtime.Get(name); container != nil {
  202. if err := container.Start(); err != nil {
  203. return err
  204. }
  205. fmt.Fprintln(stdout, container.Id)
  206. } else {
  207. return errors.New("No such container: " + name)
  208. }
  209. }
  210. return nil
  211. }
  212. func (srv *Server) CmdMount(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  213. cmd := rcli.Subcmd(stdout, "umount", "[OPTIONS] NAME", "mount a container's filesystem (debug only)")
  214. if err := cmd.Parse(args); err != nil {
  215. return nil
  216. }
  217. if cmd.NArg() < 1 {
  218. cmd.Usage()
  219. return nil
  220. }
  221. for _, name := range cmd.Args() {
  222. if container := srv.runtime.Get(name); container != nil {
  223. if err := container.EnsureMounted(); err != nil {
  224. return err
  225. }
  226. fmt.Fprintln(stdout, container.Id)
  227. } else {
  228. return errors.New("No such container: " + name)
  229. }
  230. }
  231. return nil
  232. }
  233. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  234. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  235. if err := cmd.Parse(args); err != nil {
  236. return nil
  237. }
  238. if cmd.NArg() < 1 {
  239. cmd.Usage()
  240. return nil
  241. }
  242. name := cmd.Arg(0)
  243. var obj interface{}
  244. if container := srv.runtime.Get(name); container != nil {
  245. obj = container
  246. } else if image, err := srv.runtime.graph.Get(name); err != nil {
  247. return err
  248. } else if image != nil {
  249. obj = image
  250. } else {
  251. // No output means the object does not exist
  252. // (easier to script since stdout and stderr are not differentiated atm)
  253. return nil
  254. }
  255. data, err := json.Marshal(obj)
  256. if err != nil {
  257. return err
  258. }
  259. indented := new(bytes.Buffer)
  260. if err = json.Indent(indented, data, "", " "); err != nil {
  261. return err
  262. }
  263. if _, err := io.Copy(stdout, indented); err != nil {
  264. return err
  265. }
  266. stdout.Write([]byte{'\n'})
  267. return nil
  268. }
  269. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  270. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  271. if err := cmd.Parse(args); err != nil {
  272. return nil
  273. }
  274. if cmd.NArg() != 2 {
  275. cmd.Usage()
  276. return nil
  277. }
  278. name := cmd.Arg(0)
  279. privatePort := cmd.Arg(1)
  280. if container := srv.runtime.Get(name); container == nil {
  281. return errors.New("No such container: " + name)
  282. } else {
  283. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  284. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  285. } else {
  286. fmt.Fprintln(stdout, frontend)
  287. }
  288. }
  289. return nil
  290. }
  291. // 'docker rmi NAME' removes all images with the name NAME
  292. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  293. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  294. if cmd.Parse(args) != nil || cmd.NArg() < 1 {
  295. cmd.Usage()
  296. return nil
  297. }
  298. for _, name := range cmd.Args() {
  299. if err := srv.runtime.graph.Delete(name); err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  306. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  307. if err := cmd.Parse(args); err != nil {
  308. return nil
  309. }
  310. for _, name := range cmd.Args() {
  311. container := srv.runtime.Get(name)
  312. if container == nil {
  313. return errors.New("No such container: " + name)
  314. }
  315. if err := srv.runtime.Destroy(container); err != nil {
  316. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  317. }
  318. }
  319. return nil
  320. }
  321. // 'docker kill NAME' kills a running container
  322. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  323. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  324. if err := cmd.Parse(args); err != nil {
  325. return nil
  326. }
  327. for _, name := range cmd.Args() {
  328. container := srv.runtime.Get(name)
  329. if container == nil {
  330. return errors.New("No such container: " + name)
  331. }
  332. if err := container.Kill(); err != nil {
  333. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  334. }
  335. }
  336. return nil
  337. }
  338. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  339. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  340. var archive io.Reader
  341. var resp *http.Response
  342. if err := cmd.Parse(args); err != nil {
  343. return nil
  344. }
  345. src := cmd.Arg(0)
  346. if src == "" {
  347. return errors.New("Not enough arguments")
  348. } else if src == "-" {
  349. archive = stdin
  350. } else {
  351. u, err := url.Parse(src)
  352. if err != nil {
  353. return err
  354. }
  355. if u.Scheme == "" {
  356. u.Scheme = "http"
  357. }
  358. fmt.Fprintf(stdout, "Downloading from %s\n", u.String())
  359. // Download with curl (pretty progress bar)
  360. // If curl is not available, fallback to http.Get()
  361. resp, err = Download(u.String(), stdout)
  362. if err != nil {
  363. return err
  364. }
  365. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  366. }
  367. img, err := srv.runtime.graph.Create(archive, "", "Imported from "+src)
  368. if err != nil {
  369. return err
  370. }
  371. // Optionally register the image at REPO/TAG
  372. if repository := cmd.Arg(1); repository != "" {
  373. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  374. if err := srv.runtime.repositories.Set(repository, tag, img.Id); err != nil {
  375. return err
  376. }
  377. }
  378. fmt.Fprintln(stdout, img.Id)
  379. return nil
  380. }
  381. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  382. cmd := rcli.Subcmd(stdout, "push", "[OPTIONS] IMAGE", "Push an image to the registry")
  383. if err := cmd.Parse(args); err != nil {
  384. return nil
  385. }
  386. if cmd.NArg() == 0 {
  387. cmd.Usage()
  388. return nil
  389. }
  390. client := &http.Client{}
  391. if img, err := srv.runtime.graph.Get(cmd.Arg(0)); err != nil {
  392. return nil
  393. } else {
  394. img.WalkHistory(func(img *graph.Image) {
  395. fmt.Fprintf(stdout, "Pushing %s\n", img.Id)
  396. data := strings.NewReader("{\"id\": \"ddd\", \"created\": \"2013-03-21T00:18:18-07:00\"}")
  397. req, err := http.NewRequest("PUT", "http://192.168.56.1:5000/v1/images/"+img.Id+"/json", data)
  398. res, err := client.Do(req)
  399. if err != nil || res.StatusCode != 200 {
  400. switch res.StatusCode {
  401. case 400:
  402. fmt.Fprintf(stdout, "Error: Invalid Json\n")
  403. return
  404. default:
  405. fmt.Fprintf(stdout, "Error: Internal server error\n")
  406. return
  407. }
  408. fmt.Fprintf(stdout, "Error trying to push image {%s} (json): %s\n", img.Id, err)
  409. return
  410. }
  411. req2, err := http.NewRequest("PUT", "http://192.168.56.1:5000/v1/images/"+img.Id+"/layer", nil)
  412. res2, err := client.Do(req2)
  413. if err != nil || res2.StatusCode != 307 {
  414. fmt.Fprintf(stdout, "Error trying to push image {%s} (layer 1): %s\n", img.Id, err)
  415. return
  416. }
  417. url, err := res2.Location()
  418. if err != nil || url == nil {
  419. fmt.Fprintf(stdout, "Fail to retrieve layer storage URL for image {%s}: %s\n", img.Id, err)
  420. return
  421. }
  422. req3, err := http.NewRequest("PUT", url.String(), data)
  423. res3, err := client.Do(req3)
  424. if err != nil {
  425. fmt.Fprintf(stdout, "Error trying to push image {%s} (layer 2): %s\n", img.Id, err)
  426. return
  427. }
  428. fmt.Fprintf(stdout, "Status code storage: %d\n", res3.StatusCode)
  429. })
  430. }
  431. return nil
  432. }
  433. func newImgJson(src []byte) (*graph.Image, error) {
  434. ret := &graph.Image{}
  435. fmt.Printf("Json string: {%s}\n", src)
  436. // FIXME: Is there a cleaner way to "puryfy" the input json?
  437. src = []byte(strings.Replace(string(src), "null", "\"\"", -1))
  438. if err := json.Unmarshal(src, ret); err != nil {
  439. return nil, err
  440. }
  441. return ret, nil
  442. }
  443. func newMultipleImgJson(src []byte) (map[*graph.Image]graph.Archive, error) {
  444. ret := map[*graph.Image]graph.Archive{}
  445. fmt.Printf("Json string2: {%s}\n", src)
  446. dec := json.NewDecoder(strings.NewReader(strings.Replace(string(src), "null", "\"\"", -1)))
  447. for {
  448. m := &graph.Image{}
  449. if err := dec.Decode(m); err == io.EOF {
  450. break
  451. } else if err != nil {
  452. return nil, err
  453. }
  454. ret[m] = nil
  455. }
  456. return ret, nil
  457. }
  458. func getHistory(base_uri, id string) (map[*graph.Image]graph.Archive, error) {
  459. res, err := http.Get(base_uri + id + "/history")
  460. if err != nil {
  461. return nil, fmt.Errorf("Error while getting from the server: %s\n", err)
  462. }
  463. defer res.Body.Close()
  464. jsonString, err := ioutil.ReadAll(res.Body)
  465. if err != nil {
  466. return nil, fmt.Errorf("Error while reading the http response: %s\n", err)
  467. }
  468. history, err := newMultipleImgJson(jsonString)
  469. if err != nil {
  470. return nil, fmt.Errorf("Error while parsing the json: %s\n", err)
  471. }
  472. return history, nil
  473. }
  474. func getRemoteImage(base_uri, id string) (*graph.Image, graph.Archive, error) {
  475. // Get the Json
  476. res, err := http.Get(base_uri + id + "/json")
  477. if err != nil {
  478. return nil, nil, fmt.Errorf("Error while getting from the server: %s\n", err)
  479. }
  480. defer res.Body.Close()
  481. jsonString, err := ioutil.ReadAll(res.Body)
  482. if err != nil {
  483. return nil, nil, fmt.Errorf("Error while reading the http response: %s\n", err)
  484. }
  485. img, err := newImgJson(jsonString)
  486. if err != nil {
  487. return nil, nil, fmt.Errorf("Error while parsing the json: %s\n", err)
  488. }
  489. img.Id = id
  490. // Get the layer
  491. res, err = http.Get(base_uri + id + "/layer")
  492. if err != nil {
  493. return nil, nil, fmt.Errorf("Error while getting from the server: %s\n", err)
  494. }
  495. return img, res.Body, nil
  496. }
  497. func (srv *Server) CmdPulli(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  498. cmd := rcli.Subcmd(stdout, "pulli", "[OPTIONS] IMAGE", "Pull an image from the registry")
  499. if err := cmd.Parse(args); err != nil {
  500. return nil
  501. }
  502. if cmd.NArg() == 0 {
  503. cmd.Usage()
  504. return nil
  505. }
  506. // First, retrieve the history
  507. base_uri := "http://192.168.56.1:5000/v1/images/"
  508. // Now we have the history, remove the images we already have
  509. history, err := getHistory(base_uri, cmd.Arg(0))
  510. if err != nil {
  511. return err
  512. }
  513. for j := range history {
  514. if !srv.runtime.graph.Exists(j.Id) {
  515. img, layer, err := getRemoteImage(base_uri, j.Id)
  516. if err != nil {
  517. // FIXME: Keep goging in case of error?
  518. return err
  519. }
  520. if err = srv.runtime.graph.Register(layer, img); err != nil {
  521. return err
  522. }
  523. }
  524. }
  525. return nil
  526. }
  527. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  528. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  529. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  530. quiet := cmd.Bool("q", false, "only show numeric IDs")
  531. if err := cmd.Parse(args); err != nil {
  532. return nil
  533. }
  534. if cmd.NArg() > 1 {
  535. cmd.Usage()
  536. return nil
  537. }
  538. var nameFilter string
  539. if cmd.NArg() == 1 {
  540. nameFilter = cmd.Arg(0)
  541. }
  542. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  543. if !*quiet {
  544. fmt.Fprintf(w, "REPOSITORY\tTAG\tID\tCREATED\tPARENT\n")
  545. }
  546. allImages, err := srv.runtime.graph.Map()
  547. if err != nil {
  548. return err
  549. }
  550. for name, repository := range srv.runtime.repositories.Repositories {
  551. if nameFilter != "" && name != nameFilter {
  552. continue
  553. }
  554. for tag, id := range repository {
  555. image, err := srv.runtime.graph.Get(id)
  556. if err != nil {
  557. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  558. continue
  559. }
  560. delete(allImages, id)
  561. if !*quiet {
  562. for idx, field := range []string{
  563. /* REPOSITORY */ name,
  564. /* TAG */ tag,
  565. /* ID */ id,
  566. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  567. /* PARENT */ image.Parent,
  568. } {
  569. if idx == 0 {
  570. w.Write([]byte(field))
  571. } else {
  572. w.Write([]byte("\t" + field))
  573. }
  574. }
  575. w.Write([]byte{'\n'})
  576. } else {
  577. stdout.Write([]byte(image.Id + "\n"))
  578. }
  579. }
  580. }
  581. // Display images which aren't part of a
  582. if nameFilter == "" {
  583. for id, image := range allImages {
  584. if !*quiet {
  585. for idx, field := range []string{
  586. /* REPOSITORY */ "",
  587. /* TAG */ "",
  588. /* ID */ id,
  589. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  590. /* PARENT */ image.Parent,
  591. } {
  592. if idx == 0 {
  593. w.Write([]byte(field))
  594. } else {
  595. w.Write([]byte("\t" + field))
  596. }
  597. }
  598. w.Write([]byte{'\n'})
  599. } else {
  600. stdout.Write([]byte(image.Id + "\n"))
  601. }
  602. }
  603. }
  604. if !*quiet {
  605. w.Flush()
  606. }
  607. return nil
  608. }
  609. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  610. cmd := rcli.Subcmd(stdout,
  611. "ps", "[OPTIONS]", "List containers")
  612. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  613. fl_all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  614. fl_full := cmd.Bool("notrunc", false, "Don't truncate output")
  615. if err := cmd.Parse(args); err != nil {
  616. return nil
  617. }
  618. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  619. if !*quiet {
  620. fmt.Fprintf(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT\n")
  621. }
  622. for _, container := range srv.runtime.List() {
  623. if !container.State.Running && !*fl_all {
  624. continue
  625. }
  626. if !*quiet {
  627. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  628. if !*fl_full {
  629. command = Trunc(command, 20)
  630. }
  631. for idx, field := range []string{
  632. /* ID */ container.Id,
  633. /* IMAGE */ container.Image,
  634. /* COMMAND */ command,
  635. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  636. /* STATUS */ container.State.String(),
  637. /* COMMENT */ "",
  638. } {
  639. if idx == 0 {
  640. w.Write([]byte(field))
  641. } else {
  642. w.Write([]byte("\t" + field))
  643. }
  644. }
  645. w.Write([]byte{'\n'})
  646. } else {
  647. stdout.Write([]byte(container.Id + "\n"))
  648. }
  649. }
  650. if !*quiet {
  651. w.Flush()
  652. }
  653. return nil
  654. }
  655. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  656. cmd := rcli.Subcmd(stdout,
  657. "commit", "[OPTIONS] CONTAINER [DEST]",
  658. "Create a new image from a container's changes")
  659. if err := cmd.Parse(args); err != nil {
  660. return nil
  661. }
  662. containerName, imgName := cmd.Arg(0), cmd.Arg(1)
  663. if containerName == "" || imgName == "" {
  664. cmd.Usage()
  665. return nil
  666. }
  667. if container := srv.runtime.Get(containerName); container != nil {
  668. // FIXME: freeze the container before copying it to avoid data corruption?
  669. // FIXME: this shouldn't be in commands.
  670. rwTar, err := container.ExportRw()
  671. if err != nil {
  672. return err
  673. }
  674. // Create a new image from the container's base layers + a new layer from container changes
  675. img, err := srv.runtime.graph.Create(rwTar, container.Image, "")
  676. if err != nil {
  677. return err
  678. }
  679. fmt.Fprintln(stdout, img.Id)
  680. return nil
  681. }
  682. return errors.New("No such container: " + containerName)
  683. }
  684. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  685. cmd := rcli.Subcmd(stdout,
  686. "export", "CONTAINER",
  687. "Export the contents of a filesystem as a tar archive")
  688. if err := cmd.Parse(args); err != nil {
  689. return nil
  690. }
  691. name := cmd.Arg(0)
  692. if container := srv.runtime.Get(name); container != nil {
  693. data, err := container.Export()
  694. if err != nil {
  695. return err
  696. }
  697. // Stream the entire contents of the container (basically a volatile snapshot)
  698. if _, err := io.Copy(stdout, data); err != nil {
  699. return err
  700. }
  701. return nil
  702. }
  703. return errors.New("No such container: " + name)
  704. }
  705. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  706. cmd := rcli.Subcmd(stdout,
  707. "diff", "CONTAINER [OPTIONS]",
  708. "Inspect changes on a container's filesystem")
  709. if err := cmd.Parse(args); err != nil {
  710. return nil
  711. }
  712. if cmd.NArg() < 1 {
  713. return errors.New("Not enough arguments")
  714. }
  715. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  716. return errors.New("No such container")
  717. } else {
  718. changes, err := container.Changes()
  719. if err != nil {
  720. return err
  721. }
  722. for _, change := range changes {
  723. fmt.Fprintln(stdout, change.String())
  724. }
  725. }
  726. return nil
  727. }
  728. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  729. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  730. if err := cmd.Parse(args); err != nil {
  731. return nil
  732. }
  733. if cmd.NArg() != 1 {
  734. cmd.Usage()
  735. return nil
  736. }
  737. name := cmd.Arg(0)
  738. if container := srv.runtime.Get(name); container != nil {
  739. log_stdout, err := container.ReadLog("stdout")
  740. if err != nil {
  741. return err
  742. }
  743. log_stderr, err := container.ReadLog("stderr")
  744. if err != nil {
  745. return err
  746. }
  747. // FIXME: Interpolate stdout and stderr instead of concatenating them
  748. // FIXME: Differentiate stdout and stderr in the remote protocol
  749. if _, err := io.Copy(stdout, log_stdout); err != nil {
  750. return err
  751. }
  752. if _, err := io.Copy(stdout, log_stderr); err != nil {
  753. return err
  754. }
  755. return nil
  756. }
  757. return errors.New("No such container: " + cmd.Arg(0))
  758. }
  759. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  760. cmd := rcli.Subcmd(stdout, "attach", "[OPTIONS]", "Attach to a running container")
  761. fl_i := cmd.Bool("i", false, "Attach to stdin")
  762. fl_o := cmd.Bool("o", true, "Attach to stdout")
  763. fl_e := cmd.Bool("e", true, "Attach to stderr")
  764. if err := cmd.Parse(args); err != nil {
  765. return nil
  766. }
  767. if cmd.NArg() != 1 {
  768. cmd.Usage()
  769. return nil
  770. }
  771. name := cmd.Arg(0)
  772. container := srv.runtime.Get(name)
  773. if container == nil {
  774. return errors.New("No such container: " + name)
  775. }
  776. var wg sync.WaitGroup
  777. if *fl_i {
  778. c_stdin, err := container.StdinPipe()
  779. if err != nil {
  780. return err
  781. }
  782. wg.Add(1)
  783. go func() { io.Copy(c_stdin, stdin); wg.Add(-1) }()
  784. }
  785. if *fl_o {
  786. c_stdout, err := container.StdoutPipe()
  787. if err != nil {
  788. return err
  789. }
  790. wg.Add(1)
  791. go func() { io.Copy(stdout, c_stdout); wg.Add(-1) }()
  792. }
  793. if *fl_e {
  794. c_stderr, err := container.StderrPipe()
  795. if err != nil {
  796. return err
  797. }
  798. wg.Add(1)
  799. go func() { io.Copy(stdout, c_stderr); wg.Add(-1) }()
  800. }
  801. wg.Wait()
  802. return nil
  803. }
  804. // Ports type - Used to parse multiple -p flags
  805. type ports []int
  806. func (p *ports) String() string {
  807. return fmt.Sprint(*p)
  808. }
  809. func (p *ports) Set(value string) error {
  810. port, err := strconv.Atoi(value)
  811. if err != nil {
  812. return fmt.Errorf("Invalid port: %v", value)
  813. }
  814. *p = append(*p, port)
  815. return nil
  816. }
  817. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  818. cmd := rcli.Subcmd(stdout, "run", "[OPTIONS] IMAGE COMMAND [ARG...]", "Run a command in a new container")
  819. fl_user := cmd.String("u", "", "Username or UID")
  820. fl_attach := cmd.Bool("a", false, "Attach stdin and stdout")
  821. fl_stdin := cmd.Bool("i", false, "Keep stdin open even if not attached")
  822. fl_tty := cmd.Bool("t", false, "Allocate a pseudo-tty")
  823. fl_memory := cmd.Int64("m", 0, "Memory limit (in bytes)")
  824. var fl_ports ports
  825. cmd.Var(&fl_ports, "p", "Map a network port to the container")
  826. if err := cmd.Parse(args); err != nil {
  827. return nil
  828. }
  829. name := cmd.Arg(0)
  830. var cmdline []string
  831. if len(cmd.Args()) >= 2 {
  832. cmdline = cmd.Args()[1:]
  833. }
  834. // Choose a default image if needed
  835. if name == "" {
  836. name = "base"
  837. }
  838. // Choose a default command if needed
  839. if len(cmdline) == 0 {
  840. *fl_stdin = true
  841. *fl_tty = true
  842. *fl_attach = true
  843. cmdline = []string{"/bin/bash", "-i"}
  844. }
  845. // Create new container
  846. container, err := srv.runtime.Create(cmdline[0], cmdline[1:], name,
  847. &Config{
  848. Ports: fl_ports,
  849. User: *fl_user,
  850. Tty: *fl_tty,
  851. OpenStdin: *fl_stdin,
  852. Memory: *fl_memory,
  853. })
  854. if err != nil {
  855. return errors.New("Error creating container: " + err.Error())
  856. }
  857. if *fl_stdin {
  858. cmd_stdin, err := container.StdinPipe()
  859. if err != nil {
  860. return err
  861. }
  862. if *fl_attach {
  863. Go(func() error {
  864. _, err := io.Copy(cmd_stdin, stdin)
  865. cmd_stdin.Close()
  866. return err
  867. })
  868. }
  869. }
  870. // Run the container
  871. if *fl_attach {
  872. cmd_stderr, err := container.StderrPipe()
  873. if err != nil {
  874. return err
  875. }
  876. cmd_stdout, err := container.StdoutPipe()
  877. if err != nil {
  878. return err
  879. }
  880. if err := container.Start(); err != nil {
  881. return err
  882. }
  883. sending_stdout := Go(func() error {
  884. _, err := io.Copy(stdout, cmd_stdout)
  885. return err
  886. })
  887. sending_stderr := Go(func() error {
  888. _, err := io.Copy(stdout, cmd_stderr)
  889. return err
  890. })
  891. err_sending_stdout := <-sending_stdout
  892. err_sending_stderr := <-sending_stderr
  893. if err_sending_stdout != nil {
  894. return err_sending_stdout
  895. }
  896. if err_sending_stderr != nil {
  897. return err_sending_stderr
  898. }
  899. container.Wait()
  900. } else {
  901. if err := container.Start(); err != nil {
  902. return err
  903. }
  904. fmt.Fprintln(stdout, container.Id)
  905. }
  906. return nil
  907. }
  908. func NewServer() (*Server, error) {
  909. rand.Seed(time.Now().UTC().UnixNano())
  910. if runtime.GOARCH != "amd64" {
  911. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  912. }
  913. // if err != nil {
  914. // return nil, err
  915. // }
  916. runtime, err := NewRuntime()
  917. if err != nil {
  918. return nil, err
  919. }
  920. srv := &Server{
  921. runtime: runtime,
  922. }
  923. return srv, nil
  924. }
  925. type Server struct {
  926. runtime *Runtime
  927. }