commands.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. package docker
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/dotcloud/docker/auth"
  7. "github.com/dotcloud/docker/rcli"
  8. "io"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "runtime"
  13. "strconv"
  14. "strings"
  15. "text/tabwriter"
  16. "time"
  17. "unicode"
  18. )
  19. const VERSION = "0.1.1"
  20. func (srv *Server) Name() string {
  21. return "docker"
  22. }
  23. // FIXME: Stop violating DRY by repeating usage here and in Subcmd declarations
  24. func (srv *Server) Help() string {
  25. help := "Usage: docker COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n"
  26. for _, cmd := range [][]string{
  27. {"attach", "Attach to a running container"},
  28. {"commit", "Create a new image from a container's changes"},
  29. {"diff", "Inspect changes on a container's filesystem"},
  30. {"export", "Stream the contents of a container as a tar archive"},
  31. {"history", "Show the history of an image"},
  32. {"images", "List images"},
  33. {"import", "Create a new filesystem image from the contents of a tarball"},
  34. {"info", "Display system-wide information"},
  35. {"inspect", "Return low-level information on a container"},
  36. {"kill", "Kill a running container"},
  37. {"login", "Register or Login to the docker registry server"},
  38. {"logs", "Fetch the logs of a container"},
  39. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  40. {"ps", "List containers"},
  41. {"pull", "Pull an image or a repository from the docker registry server"},
  42. {"push", "Push an image or a repository to the docker registry server"},
  43. {"restart", "Restart a running container"},
  44. {"rm", "Remove a container"},
  45. {"rmi", "Remove an image"},
  46. {"run", "Run a command in a new container"},
  47. {"start", "Start a stopped container"},
  48. {"stop", "Stop a running container"},
  49. {"tag", "Tag an image into a repository"},
  50. {"version", "Show the docker version information"},
  51. {"wait", "Block until a container stops, then print its exit code"},
  52. } {
  53. help += fmt.Sprintf(" %-10.10s%s\n", cmd[0], cmd[1])
  54. }
  55. return help
  56. }
  57. // 'docker login': login / register a user to registry service.
  58. func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  59. // Read a line on raw terminal with support for simple backspace
  60. // sequences and echo.
  61. //
  62. // This function is necessary because the login command must be done in a
  63. // raw terminal for two reasons:
  64. // - we have to read a password (without echoing it);
  65. // - the rcli "protocol" only supports cannonical and raw modes and you
  66. // can't tune it once the command as been started.
  67. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  68. char := make([]byte, 1)
  69. buffer := make([]byte, 64)
  70. var i = 0
  71. for i < len(buffer) {
  72. n, err := stdin.Read(char)
  73. if n > 0 {
  74. if char[0] == '\r' || char[0] == '\n' {
  75. stdout.Write([]byte{'\n'})
  76. break
  77. } else if char[0] == 127 || char[0] == '\b' {
  78. if i > 0 {
  79. if echo {
  80. stdout.Write([]byte{'\b', ' ', '\b'})
  81. }
  82. i--
  83. }
  84. } else if !unicode.IsSpace(rune(char[0])) &&
  85. !unicode.IsControl(rune(char[0])) {
  86. if echo {
  87. stdout.Write(char)
  88. }
  89. buffer[i] = char[0]
  90. i++
  91. }
  92. }
  93. if err != nil {
  94. if err != io.EOF {
  95. fmt.Fprint(stdout, "Read error: %v\n", err)
  96. }
  97. break
  98. }
  99. }
  100. return string(buffer[:i])
  101. }
  102. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  103. return readStringOnRawTerminal(stdin, stdout, true)
  104. }
  105. var readString = func(stdin io.Reader, stdout io.Writer) string {
  106. return readStringOnRawTerminal(stdin, stdout, false)
  107. }
  108. cmd := rcli.Subcmd(stdout, "login", "", "Register or Login to the docker registry server")
  109. if err := cmd.Parse(args); err != nil {
  110. return nil
  111. }
  112. var username string
  113. var password string
  114. var email string
  115. fmt.Fprint(stdout, "Username (", srv.runtime.authConfig.Username, "): ")
  116. username = readAndEchoString(stdin, stdout)
  117. if username == "" {
  118. username = srv.runtime.authConfig.Username
  119. }
  120. if username != srv.runtime.authConfig.Username {
  121. fmt.Fprint(stdout, "Password: ")
  122. password = readString(stdin, stdout)
  123. if password == "" {
  124. return fmt.Errorf("Error : Password Required")
  125. }
  126. fmt.Fprint(stdout, "Email (", srv.runtime.authConfig.Email, "): ")
  127. email = readAndEchoString(stdin, stdout)
  128. if email == "" {
  129. email = srv.runtime.authConfig.Email
  130. }
  131. } else {
  132. password = srv.runtime.authConfig.Password
  133. email = srv.runtime.authConfig.Email
  134. }
  135. newAuthConfig := auth.NewAuthConfig(username, password, email, srv.runtime.root)
  136. status, err := auth.Login(newAuthConfig)
  137. if err != nil {
  138. fmt.Fprintln(stdout, "Error:", err)
  139. } else {
  140. srv.runtime.authConfig = newAuthConfig
  141. }
  142. if status != "" {
  143. fmt.Fprint(stdout, status)
  144. }
  145. return nil
  146. }
  147. // 'docker wait': block until a container stops
  148. func (srv *Server) CmdWait(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  149. cmd := rcli.Subcmd(stdout, "wait", "[OPTIONS] NAME", "Block until a container stops, then print its exit code.")
  150. if err := cmd.Parse(args); err != nil {
  151. return nil
  152. }
  153. if cmd.NArg() < 1 {
  154. cmd.Usage()
  155. return nil
  156. }
  157. for _, name := range cmd.Args() {
  158. if container := srv.runtime.Get(name); container != nil {
  159. fmt.Fprintln(stdout, container.Wait())
  160. } else {
  161. return fmt.Errorf("No such container: %s", name)
  162. }
  163. }
  164. return nil
  165. }
  166. // 'docker version': show version information
  167. func (srv *Server) CmdVersion(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  168. fmt.Fprintf(stdout, "Version:%s\n", VERSION)
  169. return nil
  170. }
  171. // 'docker info': display system-wide information.
  172. func (srv *Server) CmdInfo(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  173. images, _ := srv.runtime.graph.All()
  174. var imgcount int
  175. if images == nil {
  176. imgcount = 0
  177. } else {
  178. imgcount = len(images)
  179. }
  180. cmd := rcli.Subcmd(stdout, "info", "", "Display system-wide information.")
  181. if err := cmd.Parse(args); err != nil {
  182. return nil
  183. }
  184. if cmd.NArg() > 0 {
  185. cmd.Usage()
  186. return nil
  187. }
  188. fmt.Fprintf(stdout, "containers: %d\nversion: %s\nimages: %d\n",
  189. len(srv.runtime.List()),
  190. VERSION,
  191. imgcount)
  192. if !rcli.DEBUG_FLAG {
  193. return nil
  194. }
  195. fmt.Fprintln(stdout, "debug mode enabled")
  196. fmt.Fprintf(stdout, "fds: %d\ngoroutines: %d\n", getTotalUsedFds(), runtime.NumGoroutine())
  197. return nil
  198. }
  199. func (srv *Server) CmdStop(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  200. cmd := rcli.Subcmd(stdout, "stop", "[OPTIONS] NAME", "Stop a running container")
  201. if err := cmd.Parse(args); err != nil {
  202. return nil
  203. }
  204. if cmd.NArg() < 1 {
  205. cmd.Usage()
  206. return nil
  207. }
  208. for _, name := range cmd.Args() {
  209. if container := srv.runtime.Get(name); container != nil {
  210. if err := container.Stop(); err != nil {
  211. return err
  212. }
  213. fmt.Fprintln(stdout, container.ShortId())
  214. } else {
  215. return fmt.Errorf("No such container: %s", name)
  216. }
  217. }
  218. return nil
  219. }
  220. func (srv *Server) CmdRestart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  221. cmd := rcli.Subcmd(stdout, "restart", "[OPTIONS] NAME", "Restart a running container")
  222. if err := cmd.Parse(args); err != nil {
  223. return nil
  224. }
  225. if cmd.NArg() < 1 {
  226. cmd.Usage()
  227. return nil
  228. }
  229. for _, name := range cmd.Args() {
  230. if container := srv.runtime.Get(name); container != nil {
  231. if err := container.Restart(); err != nil {
  232. return err
  233. }
  234. fmt.Fprintln(stdout, container.ShortId())
  235. } else {
  236. return fmt.Errorf("No such container: %s", name)
  237. }
  238. }
  239. return nil
  240. }
  241. func (srv *Server) CmdStart(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  242. cmd := rcli.Subcmd(stdout, "start", "[OPTIONS] NAME", "Start a stopped container")
  243. if err := cmd.Parse(args); err != nil {
  244. return nil
  245. }
  246. if cmd.NArg() < 1 {
  247. cmd.Usage()
  248. return nil
  249. }
  250. for _, name := range cmd.Args() {
  251. if container := srv.runtime.Get(name); container != nil {
  252. if err := container.Start(); err != nil {
  253. return err
  254. }
  255. fmt.Fprintln(stdout, container.ShortId())
  256. } else {
  257. return fmt.Errorf("No such container: %s", name)
  258. }
  259. }
  260. return nil
  261. }
  262. func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  263. cmd := rcli.Subcmd(stdout, "inspect", "[OPTIONS] CONTAINER", "Return low-level information on a container")
  264. if err := cmd.Parse(args); err != nil {
  265. return nil
  266. }
  267. if cmd.NArg() < 1 {
  268. cmd.Usage()
  269. return nil
  270. }
  271. name := cmd.Arg(0)
  272. var obj interface{}
  273. if container := srv.runtime.Get(name); container != nil {
  274. obj = container
  275. } else if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
  276. obj = image
  277. } else {
  278. // No output means the object does not exist
  279. // (easier to script since stdout and stderr are not differentiated atm)
  280. return nil
  281. }
  282. data, err := json.Marshal(obj)
  283. if err != nil {
  284. return err
  285. }
  286. indented := new(bytes.Buffer)
  287. if err = json.Indent(indented, data, "", " "); err != nil {
  288. return err
  289. }
  290. if _, err := io.Copy(stdout, indented); err != nil {
  291. return err
  292. }
  293. stdout.Write([]byte{'\n'})
  294. return nil
  295. }
  296. func (srv *Server) CmdPort(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  297. cmd := rcli.Subcmd(stdout, "port", "[OPTIONS] CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  298. if err := cmd.Parse(args); err != nil {
  299. return nil
  300. }
  301. if cmd.NArg() != 2 {
  302. cmd.Usage()
  303. return nil
  304. }
  305. name := cmd.Arg(0)
  306. privatePort := cmd.Arg(1)
  307. if container := srv.runtime.Get(name); container == nil {
  308. return fmt.Errorf("No such container: %s", name)
  309. } else {
  310. if frontend, exists := container.NetworkSettings.PortMapping[privatePort]; !exists {
  311. return fmt.Errorf("No private port '%s' allocated on %s", privatePort, name)
  312. } else {
  313. fmt.Fprintln(stdout, frontend)
  314. }
  315. }
  316. return nil
  317. }
  318. // 'docker rmi NAME' removes all images with the name NAME
  319. func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) (err error) {
  320. cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
  321. if err := cmd.Parse(args); err != nil {
  322. return nil
  323. }
  324. if cmd.NArg() < 1 {
  325. cmd.Usage()
  326. return nil
  327. }
  328. for _, name := range cmd.Args() {
  329. if err := srv.runtime.graph.Delete(name); err != nil {
  330. return err
  331. }
  332. }
  333. return nil
  334. }
  335. func (srv *Server) CmdHistory(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  336. cmd := rcli.Subcmd(stdout, "history", "[OPTIONS] IMAGE", "Show the history of an image")
  337. if err := cmd.Parse(args); err != nil {
  338. return nil
  339. }
  340. if cmd.NArg() != 1 {
  341. cmd.Usage()
  342. return nil
  343. }
  344. image, err := srv.runtime.repositories.LookupImage(cmd.Arg(0))
  345. if err != nil {
  346. return err
  347. }
  348. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  349. defer w.Flush()
  350. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  351. return image.WalkHistory(func(img *Image) error {
  352. fmt.Fprintf(w, "%s\t%s\t%s\n",
  353. srv.runtime.repositories.ImageName(img.ShortId()),
  354. HumanDuration(time.Now().Sub(img.Created))+" ago",
  355. strings.Join(img.ContainerConfig.Cmd, " "),
  356. )
  357. return nil
  358. })
  359. }
  360. func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  361. cmd := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
  362. if err := cmd.Parse(args); err != nil {
  363. return nil
  364. }
  365. for _, name := range cmd.Args() {
  366. container := srv.runtime.Get(name)
  367. if container == nil {
  368. return fmt.Errorf("No such container: %s", name)
  369. }
  370. if err := srv.runtime.Destroy(container); err != nil {
  371. fmt.Fprintln(stdout, "Error destroying container "+name+": "+err.Error())
  372. }
  373. }
  374. return nil
  375. }
  376. // 'docker kill NAME' kills a running container
  377. func (srv *Server) CmdKill(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  378. cmd := rcli.Subcmd(stdout, "kill", "[OPTIONS] CONTAINER [CONTAINER...]", "Kill a running container")
  379. if err := cmd.Parse(args); err != nil {
  380. return nil
  381. }
  382. for _, name := range cmd.Args() {
  383. container := srv.runtime.Get(name)
  384. if container == nil {
  385. return fmt.Errorf("No such container: %s", name)
  386. }
  387. if err := container.Kill(); err != nil {
  388. fmt.Fprintln(stdout, "Error killing container "+name+": "+err.Error())
  389. }
  390. }
  391. return nil
  392. }
  393. func (srv *Server) CmdImport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  394. cmd := rcli.Subcmd(stdout, "import", "[OPTIONS] URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  395. var archive io.Reader
  396. var resp *http.Response
  397. if err := cmd.Parse(args); err != nil {
  398. return nil
  399. }
  400. src := cmd.Arg(0)
  401. if src == "" {
  402. return fmt.Errorf("Not enough arguments")
  403. } else if src == "-" {
  404. archive = stdin
  405. } else {
  406. u, err := url.Parse(src)
  407. if err != nil {
  408. return err
  409. }
  410. if u.Scheme == "" {
  411. u.Scheme = "http"
  412. u.Host = src
  413. u.Path = ""
  414. }
  415. fmt.Fprintln(stdout, "Downloading from", u)
  416. // Download with curl (pretty progress bar)
  417. // If curl is not available, fallback to http.Get()
  418. resp, err = Download(u.String(), stdout)
  419. if err != nil {
  420. return err
  421. }
  422. archive = ProgressReader(resp.Body, int(resp.ContentLength), stdout)
  423. }
  424. img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src)
  425. if err != nil {
  426. return err
  427. }
  428. // Optionally register the image at REPO/TAG
  429. if repository := cmd.Arg(1); repository != "" {
  430. tag := cmd.Arg(2) // Repository will handle an empty tag properly
  431. if err := srv.runtime.repositories.Set(repository, tag, img.Id, true); err != nil {
  432. return err
  433. }
  434. }
  435. fmt.Fprintln(stdout, img.ShortId())
  436. return nil
  437. }
  438. func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  439. cmd := rcli.Subcmd(stdout, "push", "NAME", "Push an image or a repository to the registry")
  440. if err := cmd.Parse(args); err != nil {
  441. return nil
  442. }
  443. local := cmd.Arg(0)
  444. if local == "" {
  445. cmd.Usage()
  446. return nil
  447. }
  448. // If the login failed, abort
  449. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  450. if err := srv.CmdLogin(stdin, stdout, args...); err != nil {
  451. return err
  452. }
  453. if srv.runtime.authConfig == nil || srv.runtime.authConfig.Username == "" {
  454. return fmt.Errorf("Please login prior to push. ('docker login')")
  455. }
  456. }
  457. var remote string
  458. tmp := strings.SplitN(local, "/", 2)
  459. if len(tmp) == 1 {
  460. return fmt.Errorf(
  461. "Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)",
  462. srv.runtime.authConfig.Username, local)
  463. } else {
  464. remote = local
  465. }
  466. Debugf("Pushing [%s] to [%s]\n", local, remote)
  467. // Try to get the image
  468. // FIXME: Handle lookup
  469. // FIXME: Also push the tags in case of ./docker push myrepo:mytag
  470. // img, err := srv.runtime.LookupImage(cmd.Arg(0))
  471. img, err := srv.runtime.graph.Get(local)
  472. if err != nil {
  473. Debugf("The push refers to a repository [%s] (len: %d)\n", local, len(srv.runtime.repositories.Repositories[local]))
  474. // If it fails, try to get the repository
  475. if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
  476. if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
  477. return err
  478. }
  479. return nil
  480. } else {
  481. return err
  482. }
  483. return nil
  484. }
  485. err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
  486. if err != nil {
  487. return err
  488. }
  489. return nil
  490. }
  491. func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  492. cmd := rcli.Subcmd(stdout, "pull", "NAME", "Pull an image or a repository from the registry")
  493. if err := cmd.Parse(args); err != nil {
  494. return nil
  495. }
  496. remote := cmd.Arg(0)
  497. if remote == "" {
  498. cmd.Usage()
  499. return nil
  500. }
  501. // FIXME: CmdPull should be a wrapper around Runtime.Pull()
  502. if srv.runtime.graph.LookupRemoteImage(remote, srv.runtime.authConfig) {
  503. if err := srv.runtime.graph.PullImage(stdout, remote, srv.runtime.authConfig); err != nil {
  504. return err
  505. }
  506. return nil
  507. }
  508. // FIXME: Allow pull repo:tag
  509. if err := srv.runtime.graph.PullRepository(stdout, remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
  510. return err
  511. }
  512. return nil
  513. }
  514. func (srv *Server) CmdImages(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  515. cmd := rcli.Subcmd(stdout, "images", "[OPTIONS] [NAME]", "List images")
  516. //limit := cmd.Int("l", 0, "Only show the N most recent versions of each image")
  517. quiet := cmd.Bool("q", false, "only show numeric IDs")
  518. flAll := cmd.Bool("a", false, "show all images")
  519. if err := cmd.Parse(args); err != nil {
  520. return nil
  521. }
  522. if cmd.NArg() > 1 {
  523. cmd.Usage()
  524. return nil
  525. }
  526. var nameFilter string
  527. if cmd.NArg() == 1 {
  528. nameFilter = cmd.Arg(0)
  529. }
  530. w := tabwriter.NewWriter(stdout, 20, 1, 3, ' ', 0)
  531. if !*quiet {
  532. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tPARENT")
  533. }
  534. var allImages map[string]*Image
  535. var err error
  536. if *flAll {
  537. allImages, err = srv.runtime.graph.Map()
  538. } else {
  539. allImages, err = srv.runtime.graph.Heads()
  540. }
  541. if err != nil {
  542. return err
  543. }
  544. for name, repository := range srv.runtime.repositories.Repositories {
  545. if nameFilter != "" && name != nameFilter {
  546. continue
  547. }
  548. for tag, id := range repository {
  549. image, err := srv.runtime.graph.Get(id)
  550. if err != nil {
  551. log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
  552. continue
  553. }
  554. delete(allImages, id)
  555. if !*quiet {
  556. for idx, field := range []string{
  557. /* REPOSITORY */ name,
  558. /* TAG */ tag,
  559. /* ID */ TruncateId(id),
  560. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  561. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  562. } {
  563. if idx == 0 {
  564. w.Write([]byte(field))
  565. } else {
  566. w.Write([]byte("\t" + field))
  567. }
  568. }
  569. w.Write([]byte{'\n'})
  570. } else {
  571. stdout.Write([]byte(image.ShortId() + "\n"))
  572. }
  573. }
  574. }
  575. // Display images which aren't part of a
  576. if nameFilter == "" {
  577. for id, image := range allImages {
  578. if !*quiet {
  579. for idx, field := range []string{
  580. /* REPOSITORY */ "<none>",
  581. /* TAG */ "<none>",
  582. /* ID */ TruncateId(id),
  583. /* CREATED */ HumanDuration(time.Now().Sub(image.Created)) + " ago",
  584. /* PARENT */ srv.runtime.repositories.ImageName(image.Parent),
  585. } {
  586. if idx == 0 {
  587. w.Write([]byte(field))
  588. } else {
  589. w.Write([]byte("\t" + field))
  590. }
  591. }
  592. w.Write([]byte{'\n'})
  593. } else {
  594. stdout.Write([]byte(image.ShortId() + "\n"))
  595. }
  596. }
  597. }
  598. if !*quiet {
  599. w.Flush()
  600. }
  601. return nil
  602. }
  603. func (srv *Server) CmdPs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  604. cmd := rcli.Subcmd(stdout,
  605. "ps", "[OPTIONS]", "List containers")
  606. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  607. flAll := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  608. flFull := cmd.Bool("notrunc", false, "Don't truncate output")
  609. if err := cmd.Parse(args); err != nil {
  610. return nil
  611. }
  612. w := tabwriter.NewWriter(stdout, 12, 1, 3, ' ', 0)
  613. if !*quiet {
  614. fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tCOMMENT")
  615. }
  616. for _, container := range srv.runtime.List() {
  617. if !container.State.Running && !*flAll {
  618. continue
  619. }
  620. if !*quiet {
  621. command := fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
  622. if !*flFull {
  623. command = Trunc(command, 20)
  624. }
  625. for idx, field := range []string{
  626. /* ID */ container.ShortId(),
  627. /* IMAGE */ srv.runtime.repositories.ImageName(container.Image),
  628. /* COMMAND */ command,
  629. /* CREATED */ HumanDuration(time.Now().Sub(container.Created)) + " ago",
  630. /* STATUS */ container.State.String(),
  631. /* COMMENT */ "",
  632. } {
  633. if idx == 0 {
  634. w.Write([]byte(field))
  635. } else {
  636. w.Write([]byte("\t" + field))
  637. }
  638. }
  639. w.Write([]byte{'\n'})
  640. } else {
  641. stdout.Write([]byte(container.ShortId() + "\n"))
  642. }
  643. }
  644. if !*quiet {
  645. w.Flush()
  646. }
  647. return nil
  648. }
  649. func (srv *Server) CmdCommit(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  650. cmd := rcli.Subcmd(stdout,
  651. "commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]",
  652. "Create a new image from a container's changes")
  653. flComment := cmd.String("m", "", "Commit message")
  654. if err := cmd.Parse(args); err != nil {
  655. return nil
  656. }
  657. containerName, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  658. if containerName == "" {
  659. cmd.Usage()
  660. return nil
  661. }
  662. img, err := srv.runtime.Commit(containerName, repository, tag, *flComment)
  663. if err != nil {
  664. return err
  665. }
  666. fmt.Fprintln(stdout, img.ShortId())
  667. return nil
  668. }
  669. func (srv *Server) CmdExport(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  670. cmd := rcli.Subcmd(stdout,
  671. "export", "CONTAINER",
  672. "Export the contents of a filesystem as a tar archive")
  673. if err := cmd.Parse(args); err != nil {
  674. return nil
  675. }
  676. name := cmd.Arg(0)
  677. if container := srv.runtime.Get(name); container != nil {
  678. data, err := container.Export()
  679. if err != nil {
  680. return err
  681. }
  682. // Stream the entire contents of the container (basically a volatile snapshot)
  683. if _, err := io.Copy(stdout, data); err != nil {
  684. return err
  685. }
  686. return nil
  687. }
  688. return fmt.Errorf("No such container: %s", name)
  689. }
  690. func (srv *Server) CmdDiff(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  691. cmd := rcli.Subcmd(stdout,
  692. "diff", "CONTAINER [OPTIONS]",
  693. "Inspect changes on a container's filesystem")
  694. if err := cmd.Parse(args); err != nil {
  695. return nil
  696. }
  697. if cmd.NArg() < 1 {
  698. return fmt.Errorf("Not enough arguments")
  699. }
  700. if container := srv.runtime.Get(cmd.Arg(0)); container == nil {
  701. return fmt.Errorf("No such container")
  702. } else {
  703. changes, err := container.Changes()
  704. if err != nil {
  705. return err
  706. }
  707. for _, change := range changes {
  708. fmt.Fprintln(stdout, change.String())
  709. }
  710. }
  711. return nil
  712. }
  713. func (srv *Server) CmdLogs(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  714. cmd := rcli.Subcmd(stdout, "logs", "[OPTIONS] CONTAINER", "Fetch the logs of a container")
  715. if err := cmd.Parse(args); err != nil {
  716. return nil
  717. }
  718. if cmd.NArg() != 1 {
  719. cmd.Usage()
  720. return nil
  721. }
  722. name := cmd.Arg(0)
  723. if container := srv.runtime.Get(name); container != nil {
  724. logStdout, err := container.ReadLog("stdout")
  725. if err != nil {
  726. return err
  727. }
  728. logStderr, err := container.ReadLog("stderr")
  729. if err != nil {
  730. return err
  731. }
  732. // FIXME: Interpolate stdout and stderr instead of concatenating them
  733. // FIXME: Differentiate stdout and stderr in the remote protocol
  734. if _, err := io.Copy(stdout, logStdout); err != nil {
  735. return err
  736. }
  737. if _, err := io.Copy(stdout, logStderr); err != nil {
  738. return err
  739. }
  740. return nil
  741. }
  742. return fmt.Errorf("No such container: %s", cmd.Arg(0))
  743. }
  744. func (srv *Server) CmdAttach(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  745. cmd := rcli.Subcmd(stdout, "attach", "CONTAINER", "Attach to a running container")
  746. if err := cmd.Parse(args); err != nil {
  747. return nil
  748. }
  749. if cmd.NArg() != 1 {
  750. cmd.Usage()
  751. return nil
  752. }
  753. name := cmd.Arg(0)
  754. container := srv.runtime.Get(name)
  755. if container == nil {
  756. return fmt.Errorf("No such container: %s", name)
  757. }
  758. return <-container.Attach(stdin, stdout, stdout)
  759. }
  760. // Ports type - Used to parse multiple -p flags
  761. type ports []int
  762. func (p *ports) String() string {
  763. return fmt.Sprint(*p)
  764. }
  765. func (p *ports) Set(value string) error {
  766. port, err := strconv.Atoi(value)
  767. if err != nil {
  768. return fmt.Errorf("Invalid port: %v", value)
  769. }
  770. *p = append(*p, port)
  771. return nil
  772. }
  773. // ListOpts type
  774. type ListOpts []string
  775. func (opts *ListOpts) String() string {
  776. return fmt.Sprint(*opts)
  777. }
  778. func (opts *ListOpts) Set(value string) error {
  779. *opts = append(*opts, value)
  780. return nil
  781. }
  782. func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  783. cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  784. force := cmd.Bool("f", false, "Force")
  785. if err := cmd.Parse(args); err != nil {
  786. return nil
  787. }
  788. if cmd.NArg() < 2 {
  789. cmd.Usage()
  790. return nil
  791. }
  792. return srv.runtime.repositories.Set(cmd.Arg(1), cmd.Arg(2), cmd.Arg(0), *force)
  793. }
  794. func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
  795. config, err := ParseRun(args, stdout)
  796. if err != nil {
  797. return err
  798. }
  799. if config.Image == "" {
  800. fmt.Fprintln(stdout, "Error: Image not specified")
  801. return fmt.Errorf("Image not specified")
  802. }
  803. if len(config.Cmd) == 0 {
  804. fmt.Fprintln(stdout, "Error: Command not specified")
  805. return fmt.Errorf("Command not specified")
  806. }
  807. // Create new container
  808. container, err := srv.runtime.Create(config)
  809. if err != nil {
  810. // If container not found, try to pull it
  811. if srv.runtime.graph.IsNotExist(err) {
  812. fmt.Fprintf(stdout, "Image %s not found, trying to pull it from registry.\n", config.Image)
  813. if err = srv.CmdPull(stdin, stdout, config.Image); err != nil {
  814. return err
  815. }
  816. if container, err = srv.runtime.Create(config); err != nil {
  817. return err
  818. }
  819. } else {
  820. return err
  821. }
  822. }
  823. // Run the container
  824. if !config.Detach {
  825. var attachErr chan error
  826. if config.OpenStdin {
  827. config.StdinOnce = true
  828. Debugf("Attaching with stdin\n")
  829. attachErr = container.Attach(stdin, stdout, stdout)
  830. } else {
  831. Debugf("Attaching without stdin\n")
  832. attachErr = container.Attach(nil, stdout, nil)
  833. }
  834. Debugf("Starting\n")
  835. if err := container.Start(); err != nil {
  836. return err
  837. }
  838. Debugf("Waiting for attach to return\n")
  839. return <-attachErr
  840. }
  841. if err := container.Start(); err != nil {
  842. return err
  843. }
  844. fmt.Fprintln(stdout, container.ShortId())
  845. return nil
  846. }
  847. func NewServer() (*Server, error) {
  848. if runtime.GOARCH != "amd64" {
  849. log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
  850. }
  851. runtime, err := NewRuntime()
  852. if err != nil {
  853. return nil, err
  854. }
  855. srv := &Server{
  856. runtime: runtime,
  857. }
  858. return srv, nil
  859. }
  860. type Server struct {
  861. runtime *Runtime
  862. }