commands.go 29 KB

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