commands.go 31 KB

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