commands.go 28 KB

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