commands.go 31 KB

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