commands.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "github.com/dotcloud/docker/auth"
  9. "github.com/dotcloud/docker/term"
  10. "github.com/dotcloud/docker/utils"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "net/http"
  15. "net/http/httputil"
  16. "net/url"
  17. "os"
  18. "os/signal"
  19. "path/filepath"
  20. "reflect"
  21. "strconv"
  22. "strings"
  23. "syscall"
  24. "text/tabwriter"
  25. "time"
  26. "unicode"
  27. )
  28. const VERSION = "0.5.0-dev"
  29. var (
  30. GITCOMMIT string
  31. )
  32. func (cli *DockerCli) getMethod(name string) (reflect.Method, bool) {
  33. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  34. return reflect.TypeOf(cli).MethodByName(methodName)
  35. }
  36. func ParseCommands(proto, addr string, args ...string) error {
  37. cli := NewDockerCli(os.Stdin, os.Stdout, os.Stderr, proto, addr)
  38. if len(args) > 0 {
  39. method, exists := cli.getMethod(args[0])
  40. if !exists {
  41. fmt.Println("Error: Command not found:", args[0])
  42. return cli.CmdHelp(args[1:]...)
  43. }
  44. ret := method.Func.CallSlice([]reflect.Value{
  45. reflect.ValueOf(cli),
  46. reflect.ValueOf(args[1:]),
  47. })[0].Interface()
  48. if ret == nil {
  49. return nil
  50. }
  51. return ret.(error)
  52. }
  53. return cli.CmdHelp(args...)
  54. }
  55. func (cli *DockerCli) CmdHelp(args ...string) error {
  56. if len(args) > 0 {
  57. method, exists := cli.getMethod(args[0])
  58. if !exists {
  59. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  60. } else {
  61. method.Func.CallSlice([]reflect.Value{
  62. reflect.ValueOf(cli),
  63. reflect.ValueOf([]string{"--help"}),
  64. })[0].Interface()
  65. return nil
  66. }
  67. }
  68. help := fmt.Sprintf("Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[tcp://%s:%d]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nCommands:\n", DEFAULTHTTPHOST, DEFAULTHTTPPORT)
  69. for _, command := range [][]string{
  70. {"attach", "Attach to a running container"},
  71. {"build", "Build a container from a Dockerfile"},
  72. {"commit", "Create a new image from a container's changes"},
  73. {"diff", "Inspect changes on a container's filesystem"},
  74. {"export", "Stream the contents of a container as a tar archive"},
  75. {"history", "Show the history of an image"},
  76. {"images", "List images"},
  77. {"import", "Create a new filesystem image from the contents of a tarball"},
  78. {"info", "Display system-wide information"},
  79. {"insert", "Insert a file in an image"},
  80. {"inspect", "Return low-level information on a container"},
  81. {"kill", "Kill a running container"},
  82. {"login", "Register or Login to the docker registry server"},
  83. {"logs", "Fetch the logs of a container"},
  84. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  85. {"top", "Lookup the running processes of a container"},
  86. {"ps", "List containers"},
  87. {"pull", "Pull an image or a repository from the docker registry server"},
  88. {"push", "Push an image or a repository to the docker registry server"},
  89. {"restart", "Restart a running container"},
  90. {"rm", "Remove one or more containers"},
  91. {"rmi", "Remove one or more images"},
  92. {"run", "Run a command in a new container"},
  93. {"search", "Search for an image in the docker index"},
  94. {"start", "Start a stopped container"},
  95. {"stop", "Stop a running container"},
  96. {"tag", "Tag an image into a repository"},
  97. {"version", "Show the docker version information"},
  98. {"wait", "Block until a container stops, then print its exit code"},
  99. } {
  100. help += fmt.Sprintf(" %-10.10s%s\n", command[0], command[1])
  101. }
  102. fmt.Fprintf(cli.err, "%s\n", help)
  103. return nil
  104. }
  105. func (cli *DockerCli) CmdInsert(args ...string) error {
  106. cmd := Subcmd("insert", "IMAGE URL PATH", "Insert a file from URL in the IMAGE at PATH")
  107. if err := cmd.Parse(args); err != nil {
  108. return nil
  109. }
  110. if cmd.NArg() != 3 {
  111. cmd.Usage()
  112. return nil
  113. }
  114. v := url.Values{}
  115. v.Set("url", cmd.Arg(1))
  116. v.Set("path", cmd.Arg(2))
  117. if err := cli.stream("POST", "/images/"+cmd.Arg(0)+"/insert?"+v.Encode(), nil, cli.out); err != nil {
  118. return err
  119. }
  120. return nil
  121. }
  122. // mkBuildContext returns an archive of an empty context with the contents
  123. // of `dockerfile` at the path ./Dockerfile
  124. func mkBuildContext(dockerfile string, files [][2]string) (Archive, error) {
  125. buf := new(bytes.Buffer)
  126. tw := tar.NewWriter(buf)
  127. files = append(files, [2]string{"Dockerfile", dockerfile})
  128. for _, file := range files {
  129. name, content := file[0], file[1]
  130. hdr := &tar.Header{
  131. Name: name,
  132. Size: int64(len(content)),
  133. }
  134. if err := tw.WriteHeader(hdr); err != nil {
  135. return nil, err
  136. }
  137. if _, err := tw.Write([]byte(content)); err != nil {
  138. return nil, err
  139. }
  140. }
  141. if err := tw.Close(); err != nil {
  142. return nil, err
  143. }
  144. return buf, nil
  145. }
  146. func (cli *DockerCli) CmdBuild(args ...string) error {
  147. cmd := Subcmd("build", "[OPTIONS] PATH | URL | -", "Build a new container image from the source code at PATH")
  148. tag := cmd.String("t", "", "Tag to be applied to the resulting image in case of success")
  149. suppressOutput := cmd.Bool("q", false, "Suppress verbose build output")
  150. if err := cmd.Parse(args); err != nil {
  151. return nil
  152. }
  153. if cmd.NArg() != 1 {
  154. cmd.Usage()
  155. return nil
  156. }
  157. var (
  158. context Archive
  159. isRemote bool
  160. err error
  161. )
  162. if cmd.Arg(0) == "-" {
  163. // As a special case, 'docker build -' will build from an empty context with the
  164. // contents of stdin as a Dockerfile
  165. dockerfile, err := ioutil.ReadAll(cli.in)
  166. if err != nil {
  167. return err
  168. }
  169. context, err = mkBuildContext(string(dockerfile), nil)
  170. } else if utils.IsURL(cmd.Arg(0)) || utils.IsGIT(cmd.Arg(0)) {
  171. isRemote = true
  172. } else {
  173. context, err = Tar(cmd.Arg(0), Uncompressed)
  174. }
  175. var body io.Reader
  176. // Setup an upload progress bar
  177. // FIXME: ProgressReader shouldn't be this annoyning to use
  178. if context != nil {
  179. sf := utils.NewStreamFormatter(false)
  180. body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf.FormatProgress("Uploading context", "%v bytes%0.0s%0.0s"), sf)
  181. }
  182. // Upload the build context
  183. v := &url.Values{}
  184. v.Set("t", *tag)
  185. if *suppressOutput {
  186. v.Set("q", "1")
  187. }
  188. if isRemote {
  189. v.Set("remote", cmd.Arg(0))
  190. }
  191. req, err := http.NewRequest("POST", fmt.Sprintf("/v%g/build?%s", APIVERSION, v.Encode()), body)
  192. if err != nil {
  193. return err
  194. }
  195. if context != nil {
  196. req.Header.Set("Content-Type", "application/tar")
  197. }
  198. dial, err := net.Dial(cli.proto, cli.addr)
  199. if err != nil {
  200. return err
  201. }
  202. clientconn := httputil.NewClientConn(dial, nil)
  203. resp, err := clientconn.Do(req)
  204. defer clientconn.Close()
  205. if err != nil {
  206. return err
  207. }
  208. defer resp.Body.Close()
  209. // Check for errors
  210. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  211. body, err := ioutil.ReadAll(resp.Body)
  212. if err != nil {
  213. return err
  214. }
  215. if len(body) == 0 {
  216. return fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  217. }
  218. return fmt.Errorf("Error: %s", body)
  219. }
  220. // Output the result
  221. if _, err := io.Copy(cli.out, resp.Body); err != nil {
  222. return err
  223. }
  224. return nil
  225. }
  226. // 'docker login': login / register a user to registry service.
  227. func (cli *DockerCli) CmdLogin(args ...string) error {
  228. var readStringOnRawTerminal = func(stdin io.Reader, stdout io.Writer, echo bool) string {
  229. char := make([]byte, 1)
  230. buffer := make([]byte, 64)
  231. var i = 0
  232. for i < len(buffer) {
  233. n, err := stdin.Read(char)
  234. if n > 0 {
  235. if char[0] == '\r' || char[0] == '\n' {
  236. stdout.Write([]byte{'\r', '\n'})
  237. break
  238. } else if char[0] == 127 || char[0] == '\b' {
  239. if i > 0 {
  240. if echo {
  241. stdout.Write([]byte{'\b', ' ', '\b'})
  242. }
  243. i--
  244. }
  245. } else if !unicode.IsSpace(rune(char[0])) &&
  246. !unicode.IsControl(rune(char[0])) {
  247. if echo {
  248. stdout.Write(char)
  249. }
  250. buffer[i] = char[0]
  251. i++
  252. }
  253. }
  254. if err != nil {
  255. if err != io.EOF {
  256. fmt.Fprintf(stdout, "Read error: %v\r\n", err)
  257. }
  258. break
  259. }
  260. }
  261. return string(buffer[:i])
  262. }
  263. var readAndEchoString = func(stdin io.Reader, stdout io.Writer) string {
  264. return readStringOnRawTerminal(stdin, stdout, true)
  265. }
  266. var readString = func(stdin io.Reader, stdout io.Writer) string {
  267. return readStringOnRawTerminal(stdin, stdout, false)
  268. }
  269. cmd := Subcmd("login", "[OPTIONS]", "Register or Login to the docker registry server")
  270. flUsername := cmd.String("u", "", "username")
  271. flPassword := cmd.String("p", "", "password")
  272. flEmail := cmd.String("e", "", "email")
  273. err := cmd.Parse(args)
  274. if err != nil {
  275. return nil
  276. }
  277. var oldState *term.State
  278. if *flUsername == "" || *flPassword == "" || *flEmail == "" {
  279. oldState, err = term.SetRawTerminal(cli.terminalFd)
  280. if err != nil {
  281. return err
  282. }
  283. defer term.RestoreTerminal(cli.terminalFd, oldState)
  284. }
  285. var (
  286. username string
  287. password string
  288. email string
  289. )
  290. if *flUsername == "" {
  291. fmt.Fprintf(cli.out, "Username (%s): ", cli.authConfig.Username)
  292. username = readAndEchoString(cli.in, cli.out)
  293. if username == "" {
  294. username = cli.authConfig.Username
  295. }
  296. } else {
  297. username = *flUsername
  298. }
  299. if username != cli.authConfig.Username {
  300. if *flPassword == "" {
  301. fmt.Fprintf(cli.out, "Password: ")
  302. password = readString(cli.in, cli.out)
  303. if password == "" {
  304. return fmt.Errorf("Error : Password Required")
  305. }
  306. } else {
  307. password = *flPassword
  308. }
  309. if *flEmail == "" {
  310. fmt.Fprintf(cli.out, "Email (%s): ", cli.authConfig.Email)
  311. email = readAndEchoString(cli.in, cli.out)
  312. if email == "" {
  313. email = cli.authConfig.Email
  314. }
  315. } else {
  316. email = *flEmail
  317. }
  318. } else {
  319. password = cli.authConfig.Password
  320. email = cli.authConfig.Email
  321. }
  322. if oldState != nil {
  323. term.RestoreTerminal(cli.terminalFd, oldState)
  324. }
  325. cli.authConfig.Username = username
  326. cli.authConfig.Password = password
  327. cli.authConfig.Email = email
  328. body, statusCode, err := cli.call("POST", "/auth", cli.authConfig)
  329. if statusCode == 401 {
  330. cli.authConfig.Username = ""
  331. cli.authConfig.Password = ""
  332. cli.authConfig.Email = ""
  333. auth.SaveConfig(cli.authConfig)
  334. return err
  335. }
  336. if err != nil {
  337. return err
  338. }
  339. var out2 APIAuth
  340. err = json.Unmarshal(body, &out2)
  341. if err != nil {
  342. auth.LoadConfig(os.Getenv("HOME"))
  343. return err
  344. }
  345. auth.SaveConfig(cli.authConfig)
  346. if out2.Status != "" {
  347. fmt.Fprintf(cli.out, "%s\n", out2.Status)
  348. }
  349. return nil
  350. }
  351. // 'docker wait': block until a container stops
  352. func (cli *DockerCli) CmdWait(args ...string) error {
  353. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  354. if err := cmd.Parse(args); err != nil {
  355. return nil
  356. }
  357. if cmd.NArg() < 1 {
  358. cmd.Usage()
  359. return nil
  360. }
  361. for _, name := range cmd.Args() {
  362. body, _, err := cli.call("POST", "/containers/"+name+"/wait", nil)
  363. if err != nil {
  364. fmt.Fprintf(cli.err, "%s", err)
  365. } else {
  366. var out APIWait
  367. err = json.Unmarshal(body, &out)
  368. if err != nil {
  369. return err
  370. }
  371. fmt.Fprintf(cli.out, "%d\n", out.StatusCode)
  372. }
  373. }
  374. return nil
  375. }
  376. // 'docker version': show version information
  377. func (cli *DockerCli) CmdVersion(args ...string) error {
  378. cmd := Subcmd("version", "", "Show the docker version information.")
  379. if err := cmd.Parse(args); err != nil {
  380. return nil
  381. }
  382. if cmd.NArg() > 0 {
  383. cmd.Usage()
  384. return nil
  385. }
  386. body, _, err := cli.call("GET", "/version", nil)
  387. if err != nil {
  388. return err
  389. }
  390. var out APIVersion
  391. err = json.Unmarshal(body, &out)
  392. if err != nil {
  393. utils.Debugf("Error unmarshal: body: %s, err: %s\n", body, err)
  394. return err
  395. }
  396. fmt.Fprintf(cli.out, "Client version: %s\n", VERSION)
  397. fmt.Fprintf(cli.out, "Server version: %s\n", out.Version)
  398. if out.GitCommit != "" {
  399. fmt.Fprintf(cli.out, "Git commit: %s\n", out.GitCommit)
  400. }
  401. if out.GoVersion != "" {
  402. fmt.Fprintf(cli.out, "Go version: %s\n", out.GoVersion)
  403. }
  404. return nil
  405. }
  406. // 'docker info': display system-wide information.
  407. func (cli *DockerCli) CmdInfo(args ...string) error {
  408. cmd := Subcmd("info", "", "Display system-wide information")
  409. if err := cmd.Parse(args); err != nil {
  410. return nil
  411. }
  412. if cmd.NArg() > 0 {
  413. cmd.Usage()
  414. return nil
  415. }
  416. body, _, err := cli.call("GET", "/info", nil)
  417. if err != nil {
  418. return err
  419. }
  420. var out APIInfo
  421. if err := json.Unmarshal(body, &out); err != nil {
  422. return err
  423. }
  424. fmt.Fprintf(cli.out, "Containers: %d\n", out.Containers)
  425. fmt.Fprintf(cli.out, "Images: %d\n", out.Images)
  426. if out.Debug || os.Getenv("DEBUG") != "" {
  427. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", out.Debug)
  428. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  429. fmt.Fprintf(cli.out, "Fds: %d\n", out.NFd)
  430. fmt.Fprintf(cli.out, "Goroutines: %d\n", out.NGoroutines)
  431. }
  432. if !out.MemoryLimit {
  433. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  434. }
  435. if !out.SwapLimit {
  436. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  437. }
  438. return nil
  439. }
  440. func (cli *DockerCli) CmdStop(args ...string) error {
  441. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container")
  442. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  443. if err := cmd.Parse(args); err != nil {
  444. return nil
  445. }
  446. if cmd.NArg() < 1 {
  447. cmd.Usage()
  448. return nil
  449. }
  450. v := url.Values{}
  451. v.Set("t", strconv.Itoa(*nSeconds))
  452. for _, name := range cmd.Args() {
  453. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  454. if err != nil {
  455. fmt.Fprintf(cli.err, "%s\n", err)
  456. } else {
  457. fmt.Fprintf(cli.out, "%s\n", name)
  458. }
  459. }
  460. return nil
  461. }
  462. func (cli *DockerCli) CmdRestart(args ...string) error {
  463. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  464. nSeconds := cmd.Int("t", 10, "Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default=10")
  465. if err := cmd.Parse(args); err != nil {
  466. return nil
  467. }
  468. if cmd.NArg() < 1 {
  469. cmd.Usage()
  470. return nil
  471. }
  472. v := url.Values{}
  473. v.Set("t", strconv.Itoa(*nSeconds))
  474. for _, name := range cmd.Args() {
  475. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  476. if err != nil {
  477. fmt.Fprintf(cli.err, "%s\n", err)
  478. } else {
  479. fmt.Fprintf(cli.out, "%s\n", name)
  480. }
  481. }
  482. return nil
  483. }
  484. func (cli *DockerCli) CmdStart(args ...string) error {
  485. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  486. if err := cmd.Parse(args); err != nil {
  487. return nil
  488. }
  489. if cmd.NArg() < 1 {
  490. cmd.Usage()
  491. return nil
  492. }
  493. for _, name := range args {
  494. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  495. if err != nil {
  496. fmt.Fprintf(cli.err, "%s\n", err)
  497. } else {
  498. fmt.Fprintf(cli.out, "%s\n", name)
  499. }
  500. }
  501. return nil
  502. }
  503. func (cli *DockerCli) CmdInspect(args ...string) error {
  504. cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  505. if err := cmd.Parse(args); err != nil {
  506. return nil
  507. }
  508. if cmd.NArg() < 1 {
  509. cmd.Usage()
  510. return nil
  511. }
  512. fmt.Fprintf(cli.out, "[")
  513. for i, name := range args {
  514. if i > 0 {
  515. fmt.Fprintf(cli.out, ",")
  516. }
  517. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  518. if err != nil {
  519. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  520. if err != nil {
  521. fmt.Fprintf(cli.err, "%s\n", err)
  522. continue
  523. }
  524. }
  525. indented := new(bytes.Buffer)
  526. if err = json.Indent(indented, obj, "", " "); err != nil {
  527. fmt.Fprintf(cli.err, "%s\n", err)
  528. continue
  529. }
  530. if _, err := io.Copy(cli.out, indented); err != nil {
  531. fmt.Fprintf(cli.err, "%s\n", err)
  532. }
  533. }
  534. fmt.Fprintf(cli.out, "]")
  535. return nil
  536. }
  537. func (cli *DockerCli) CmdTop(args ...string) error {
  538. cmd := Subcmd("top", "CONTAINER", "Lookup the running processes of a container")
  539. if err := cmd.Parse(args); err != nil {
  540. return nil
  541. }
  542. if cmd.NArg() != 1 {
  543. cmd.Usage()
  544. return nil
  545. }
  546. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top", nil)
  547. if err != nil {
  548. return err
  549. }
  550. var procs []APITop
  551. err = json.Unmarshal(body, &procs)
  552. if err != nil {
  553. return err
  554. }
  555. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  556. fmt.Fprintln(w, "PID\tTTY\tTIME\tCMD")
  557. for _, proc := range procs {
  558. fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", proc.PID, proc.Tty, proc.Time, proc.Cmd)
  559. }
  560. w.Flush()
  561. return nil
  562. }
  563. func (cli *DockerCli) CmdPort(args ...string) error {
  564. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  565. if err := cmd.Parse(args); err != nil {
  566. return nil
  567. }
  568. if cmd.NArg() != 2 {
  569. cmd.Usage()
  570. return nil
  571. }
  572. port := cmd.Arg(1)
  573. proto := "Tcp"
  574. parts := strings.SplitN(port, "/", 2)
  575. if len(parts) == 2 && len(parts[1]) != 0 {
  576. port = parts[0]
  577. proto = strings.ToUpper(parts[1][:1]) + strings.ToLower(parts[1][1:])
  578. }
  579. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  580. if err != nil {
  581. return err
  582. }
  583. var out Container
  584. err = json.Unmarshal(body, &out)
  585. if err != nil {
  586. return err
  587. }
  588. if frontend, exists := out.NetworkSettings.PortMapping[proto][port]; exists {
  589. fmt.Fprintf(cli.out, "%s\n", frontend)
  590. } else {
  591. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  592. }
  593. return nil
  594. }
  595. // 'docker rmi IMAGE' removes all images with the name IMAGE
  596. func (cli *DockerCli) CmdRmi(args ...string) error {
  597. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  598. if err := cmd.Parse(args); err != nil {
  599. return nil
  600. }
  601. if cmd.NArg() < 1 {
  602. cmd.Usage()
  603. return nil
  604. }
  605. for _, name := range cmd.Args() {
  606. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  607. if err != nil {
  608. fmt.Fprintf(cli.err, "%s", err)
  609. } else {
  610. var outs []APIRmi
  611. err = json.Unmarshal(body, &outs)
  612. if err != nil {
  613. return err
  614. }
  615. for _, out := range outs {
  616. if out.Deleted != "" {
  617. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  618. } else {
  619. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  620. }
  621. }
  622. }
  623. }
  624. return nil
  625. }
  626. func (cli *DockerCli) CmdHistory(args ...string) error {
  627. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  628. if err := cmd.Parse(args); err != nil {
  629. return nil
  630. }
  631. if cmd.NArg() != 1 {
  632. cmd.Usage()
  633. return nil
  634. }
  635. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  636. if err != nil {
  637. return err
  638. }
  639. var outs []APIHistory
  640. err = json.Unmarshal(body, &outs)
  641. if err != nil {
  642. return err
  643. }
  644. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  645. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  646. for _, out := range outs {
  647. if out.Tags != nil {
  648. out.ID = out.Tags[0]
  649. }
  650. fmt.Fprintf(w, "%s \t%s ago\t%s\n", out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  651. }
  652. w.Flush()
  653. return nil
  654. }
  655. func (cli *DockerCli) CmdRm(args ...string) error {
  656. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  657. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  658. if err := cmd.Parse(args); err != nil {
  659. return nil
  660. }
  661. if cmd.NArg() < 1 {
  662. cmd.Usage()
  663. return nil
  664. }
  665. val := url.Values{}
  666. if *v {
  667. val.Set("v", "1")
  668. }
  669. for _, name := range cmd.Args() {
  670. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  671. if err != nil {
  672. fmt.Fprintf(cli.err, "%s\n", err)
  673. } else {
  674. fmt.Fprintf(cli.out, "%s\n", name)
  675. }
  676. }
  677. return nil
  678. }
  679. // 'docker kill NAME' kills a running container
  680. func (cli *DockerCli) CmdKill(args ...string) error {
  681. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  682. if err := cmd.Parse(args); err != nil {
  683. return nil
  684. }
  685. if cmd.NArg() < 1 {
  686. cmd.Usage()
  687. return nil
  688. }
  689. for _, name := range args {
  690. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  691. if err != nil {
  692. fmt.Fprintf(cli.err, "%s\n", err)
  693. } else {
  694. fmt.Fprintf(cli.out, "%s\n", name)
  695. }
  696. }
  697. return nil
  698. }
  699. func (cli *DockerCli) CmdImport(args ...string) error {
  700. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  701. if err := cmd.Parse(args); err != nil {
  702. return nil
  703. }
  704. if cmd.NArg() < 1 {
  705. cmd.Usage()
  706. return nil
  707. }
  708. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  709. v := url.Values{}
  710. v.Set("repo", repository)
  711. v.Set("tag", tag)
  712. v.Set("fromSrc", src)
  713. err := cli.stream("POST", "/images/create?"+v.Encode(), cli.in, cli.out)
  714. if err != nil {
  715. return err
  716. }
  717. return nil
  718. }
  719. func (cli *DockerCli) CmdPush(args ...string) error {
  720. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  721. if err := cmd.Parse(args); err != nil {
  722. return nil
  723. }
  724. name := cmd.Arg(0)
  725. if name == "" {
  726. cmd.Usage()
  727. return nil
  728. }
  729. if err := cli.checkIfLogged("push"); err != nil {
  730. return err
  731. }
  732. // If we're not using a custom registry, we know the restrictions
  733. // applied to repository names and can warn the user in advance.
  734. // Custom repositories can have different rules, and we must also
  735. // allow pushing by image ID.
  736. if len(strings.SplitN(name, "/", 2)) == 1 {
  737. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
  738. }
  739. buf, err := json.Marshal(cli.authConfig)
  740. if err != nil {
  741. return err
  742. }
  743. v := url.Values{}
  744. if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), bytes.NewBuffer(buf), cli.out); err != nil {
  745. return err
  746. }
  747. return nil
  748. }
  749. func (cli *DockerCli) CmdPull(args ...string) error {
  750. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  751. tag := cmd.String("t", "", "Download tagged image in repository")
  752. if err := cmd.Parse(args); err != nil {
  753. return nil
  754. }
  755. if cmd.NArg() != 1 {
  756. cmd.Usage()
  757. return nil
  758. }
  759. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  760. if *tag == "" {
  761. *tag = parsedTag
  762. }
  763. v := url.Values{}
  764. v.Set("fromImage", remote)
  765. v.Set("tag", *tag)
  766. if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out); err != nil {
  767. return err
  768. }
  769. return nil
  770. }
  771. func (cli *DockerCli) CmdImages(args ...string) error {
  772. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  773. quiet := cmd.Bool("q", false, "only show numeric IDs")
  774. all := cmd.Bool("a", false, "show all images")
  775. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  776. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  777. if err := cmd.Parse(args); err != nil {
  778. return nil
  779. }
  780. if cmd.NArg() > 1 {
  781. cmd.Usage()
  782. return nil
  783. }
  784. if *flViz {
  785. body, _, err := cli.call("GET", "/images/viz", false)
  786. if err != nil {
  787. return err
  788. }
  789. fmt.Fprintf(cli.out, "%s", body)
  790. } else {
  791. v := url.Values{}
  792. if cmd.NArg() == 1 {
  793. v.Set("filter", cmd.Arg(0))
  794. }
  795. if *all {
  796. v.Set("all", "1")
  797. }
  798. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  799. if err != nil {
  800. return err
  801. }
  802. var outs []APIImages
  803. err = json.Unmarshal(body, &outs)
  804. if err != nil {
  805. return err
  806. }
  807. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  808. if !*quiet {
  809. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  810. }
  811. for _, out := range outs {
  812. if out.Repository == "" {
  813. out.Repository = "<none>"
  814. }
  815. if out.Tag == "" {
  816. out.Tag = "<none>"
  817. }
  818. if !*quiet {
  819. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  820. if *noTrunc {
  821. fmt.Fprintf(w, "%s\t", out.ID)
  822. } else {
  823. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  824. }
  825. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  826. if out.VirtualSize > 0 {
  827. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  828. } else {
  829. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  830. }
  831. } else {
  832. if *noTrunc {
  833. fmt.Fprintln(w, out.ID)
  834. } else {
  835. fmt.Fprintln(w, utils.TruncateID(out.ID))
  836. }
  837. }
  838. }
  839. if !*quiet {
  840. w.Flush()
  841. }
  842. }
  843. return nil
  844. }
  845. func (cli *DockerCli) CmdPs(args ...string) error {
  846. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  847. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  848. size := cmd.Bool("s", false, "Display sizes")
  849. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  850. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  851. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  852. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  853. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  854. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  855. if err := cmd.Parse(args); err != nil {
  856. return nil
  857. }
  858. v := url.Values{}
  859. if *last == -1 && *nLatest {
  860. *last = 1
  861. }
  862. if *all {
  863. v.Set("all", "1")
  864. }
  865. if *last != -1 {
  866. v.Set("limit", strconv.Itoa(*last))
  867. }
  868. if *since != "" {
  869. v.Set("since", *since)
  870. }
  871. if *before != "" {
  872. v.Set("before", *before)
  873. }
  874. if *size {
  875. v.Set("size", "1")
  876. }
  877. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  878. if err != nil {
  879. return err
  880. }
  881. var outs []APIContainers
  882. err = json.Unmarshal(body, &outs)
  883. if err != nil {
  884. return err
  885. }
  886. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  887. if !*quiet {
  888. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  889. if *size {
  890. fmt.Fprintln(w, "\tSIZE")
  891. } else {
  892. fmt.Fprint(w, "\n")
  893. }
  894. }
  895. for _, out := range outs {
  896. if !*quiet {
  897. if *noTrunc {
  898. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t", out.ID, out.Image, out.Command, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
  899. } else {
  900. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t", utils.TruncateID(out.ID), out.Image, utils.Trunc(out.Command, 20), utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports)
  901. }
  902. if *size {
  903. if out.SizeRootFs > 0 {
  904. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  905. } else {
  906. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  907. }
  908. } else {
  909. fmt.Fprint(w, "\n")
  910. }
  911. } else {
  912. if *noTrunc {
  913. fmt.Fprintln(w, out.ID)
  914. } else {
  915. fmt.Fprintln(w, utils.TruncateID(out.ID))
  916. }
  917. }
  918. }
  919. if !*quiet {
  920. w.Flush()
  921. }
  922. return nil
  923. }
  924. func (cli *DockerCli) CmdCommit(args ...string) error {
  925. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  926. flComment := cmd.String("m", "", "Commit message")
  927. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  928. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  929. if err := cmd.Parse(args); err != nil {
  930. return nil
  931. }
  932. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  933. if name == "" {
  934. cmd.Usage()
  935. return nil
  936. }
  937. v := url.Values{}
  938. v.Set("container", name)
  939. v.Set("repo", repository)
  940. v.Set("tag", tag)
  941. v.Set("comment", *flComment)
  942. v.Set("author", *flAuthor)
  943. var config *Config
  944. if *flConfig != "" {
  945. config = &Config{}
  946. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  947. return err
  948. }
  949. }
  950. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  951. if err != nil {
  952. return err
  953. }
  954. apiID := &APIID{}
  955. err = json.Unmarshal(body, apiID)
  956. if err != nil {
  957. return err
  958. }
  959. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  960. return nil
  961. }
  962. func (cli *DockerCli) CmdExport(args ...string) error {
  963. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  964. if err := cmd.Parse(args); err != nil {
  965. return nil
  966. }
  967. if cmd.NArg() != 1 {
  968. cmd.Usage()
  969. return nil
  970. }
  971. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out); err != nil {
  972. return err
  973. }
  974. return nil
  975. }
  976. func (cli *DockerCli) CmdDiff(args ...string) error {
  977. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  978. if err := cmd.Parse(args); err != nil {
  979. return nil
  980. }
  981. if cmd.NArg() != 1 {
  982. cmd.Usage()
  983. return nil
  984. }
  985. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  986. if err != nil {
  987. return err
  988. }
  989. changes := []Change{}
  990. err = json.Unmarshal(body, &changes)
  991. if err != nil {
  992. return err
  993. }
  994. for _, change := range changes {
  995. fmt.Fprintf(cli.out, "%s\n", change.String())
  996. }
  997. return nil
  998. }
  999. func (cli *DockerCli) CmdLogs(args ...string) error {
  1000. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1001. if err := cmd.Parse(args); err != nil {
  1002. return nil
  1003. }
  1004. if cmd.NArg() != 1 {
  1005. cmd.Usage()
  1006. return nil
  1007. }
  1008. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out); err != nil {
  1009. return err
  1010. }
  1011. return nil
  1012. }
  1013. func (cli *DockerCli) CmdAttach(args ...string) error {
  1014. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  1015. if err := cmd.Parse(args); err != nil {
  1016. return nil
  1017. }
  1018. if cmd.NArg() != 1 {
  1019. cmd.Usage()
  1020. return nil
  1021. }
  1022. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  1023. if err != nil {
  1024. return err
  1025. }
  1026. container := &Container{}
  1027. err = json.Unmarshal(body, container)
  1028. if err != nil {
  1029. return err
  1030. }
  1031. if !container.State.Running {
  1032. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1033. }
  1034. if container.Config.Tty {
  1035. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1036. return err
  1037. }
  1038. }
  1039. v := url.Values{}
  1040. v.Set("stream", "1")
  1041. v.Set("stdin", "1")
  1042. v.Set("stdout", "1")
  1043. v.Set("stderr", "1")
  1044. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, cli.in, cli.out); err != nil {
  1045. return err
  1046. }
  1047. return nil
  1048. }
  1049. func (cli *DockerCli) CmdSearch(args ...string) error {
  1050. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  1051. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1052. if err := cmd.Parse(args); err != nil {
  1053. return nil
  1054. }
  1055. if cmd.NArg() != 1 {
  1056. cmd.Usage()
  1057. return nil
  1058. }
  1059. v := url.Values{}
  1060. v.Set("term", cmd.Arg(0))
  1061. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1062. if err != nil {
  1063. return err
  1064. }
  1065. outs := []APISearch{}
  1066. err = json.Unmarshal(body, &outs)
  1067. if err != nil {
  1068. return err
  1069. }
  1070. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1071. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1072. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1073. _, width := cli.getTtySize()
  1074. if width == 0 {
  1075. width = 45
  1076. } else {
  1077. width = width - 33 //remote the first column
  1078. }
  1079. for _, out := range outs {
  1080. desc := strings.Replace(out.Description, "\n", " ", -1)
  1081. desc = strings.Replace(desc, "\r", " ", -1)
  1082. if !*noTrunc && len(desc) > width {
  1083. desc = utils.Trunc(desc, width-3) + "..."
  1084. }
  1085. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1086. }
  1087. w.Flush()
  1088. return nil
  1089. }
  1090. // Ports type - Used to parse multiple -p flags
  1091. type ports []int
  1092. // ListOpts type
  1093. type ListOpts []string
  1094. func (opts *ListOpts) String() string {
  1095. return fmt.Sprint(*opts)
  1096. }
  1097. func (opts *ListOpts) Set(value string) error {
  1098. *opts = append(*opts, value)
  1099. return nil
  1100. }
  1101. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1102. type AttachOpts map[string]bool
  1103. func NewAttachOpts() AttachOpts {
  1104. return make(AttachOpts)
  1105. }
  1106. func (opts AttachOpts) String() string {
  1107. // Cast to underlying map type to avoid infinite recursion
  1108. return fmt.Sprintf("%v", map[string]bool(opts))
  1109. }
  1110. func (opts AttachOpts) Set(val string) error {
  1111. if val != "stdin" && val != "stdout" && val != "stderr" {
  1112. return fmt.Errorf("Unsupported stream name: %s", val)
  1113. }
  1114. opts[val] = true
  1115. return nil
  1116. }
  1117. func (opts AttachOpts) Get(val string) bool {
  1118. if res, exists := opts[val]; exists {
  1119. return res
  1120. }
  1121. return false
  1122. }
  1123. // PathOpts stores a unique set of absolute paths
  1124. type PathOpts map[string]struct{}
  1125. func NewPathOpts() PathOpts {
  1126. return make(PathOpts)
  1127. }
  1128. func (opts PathOpts) String() string {
  1129. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1130. }
  1131. func (opts PathOpts) Set(val string) error {
  1132. var containerPath string
  1133. splited := strings.SplitN(val, ":", 2)
  1134. if len(splited) == 1 {
  1135. containerPath = splited[0]
  1136. val = filepath.Clean(splited[0])
  1137. } else {
  1138. containerPath = splited[1]
  1139. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1140. }
  1141. if !filepath.IsAbs(containerPath) {
  1142. utils.Debugf("%s is not an absolute path", containerPath)
  1143. return fmt.Errorf("%s is not an absolute path", containerPath)
  1144. }
  1145. opts[val] = struct{}{}
  1146. return nil
  1147. }
  1148. func (cli *DockerCli) CmdTag(args ...string) error {
  1149. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1150. force := cmd.Bool("f", false, "Force")
  1151. if err := cmd.Parse(args); err != nil {
  1152. return nil
  1153. }
  1154. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1155. cmd.Usage()
  1156. return nil
  1157. }
  1158. v := url.Values{}
  1159. v.Set("repo", cmd.Arg(1))
  1160. if cmd.NArg() == 3 {
  1161. v.Set("tag", cmd.Arg(2))
  1162. }
  1163. if *force {
  1164. v.Set("force", "1")
  1165. }
  1166. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1167. return err
  1168. }
  1169. return nil
  1170. }
  1171. func (cli *DockerCli) CmdRun(args ...string) error {
  1172. config, hostConfig, cmd, err := ParseRun(args, nil)
  1173. if err != nil {
  1174. return err
  1175. }
  1176. if config.Image == "" {
  1177. cmd.Usage()
  1178. return nil
  1179. }
  1180. var containerIDFile *os.File
  1181. if len(hostConfig.ContainerIDFile) > 0 {
  1182. if _, err := ioutil.ReadFile(hostConfig.ContainerIDFile); err == nil {
  1183. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1184. }
  1185. containerIDFile, err = os.Create(hostConfig.ContainerIDFile)
  1186. if err != nil {
  1187. return fmt.Errorf("failed to create the container ID file: %s", err)
  1188. }
  1189. defer containerIDFile.Close()
  1190. }
  1191. //create the container
  1192. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1193. //if image not found try to pull it
  1194. if statusCode == 404 {
  1195. v := url.Values{}
  1196. repos, tag := utils.ParseRepositoryTag(config.Image)
  1197. v.Set("fromImage", repos)
  1198. v.Set("tag", tag)
  1199. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err)
  1200. if err != nil {
  1201. return err
  1202. }
  1203. body, _, err = cli.call("POST", "/containers/create", config)
  1204. if err != nil {
  1205. return err
  1206. }
  1207. }
  1208. if err != nil {
  1209. return err
  1210. }
  1211. runResult := &APIRun{}
  1212. err = json.Unmarshal(body, runResult)
  1213. if err != nil {
  1214. return err
  1215. }
  1216. for _, warning := range runResult.Warnings {
  1217. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1218. }
  1219. if len(hostConfig.ContainerIDFile) > 0 {
  1220. if _, err = containerIDFile.WriteString(runResult.ID); err != nil {
  1221. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1222. }
  1223. }
  1224. //start the container
  1225. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1226. return err
  1227. }
  1228. var wait chan struct{}
  1229. if !config.AttachStdout && !config.AttachStderr {
  1230. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1231. wait = make(chan struct{})
  1232. go func() {
  1233. defer close(wait)
  1234. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1235. }()
  1236. }
  1237. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1238. if config.Tty {
  1239. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1240. return err
  1241. }
  1242. }
  1243. v := url.Values{}
  1244. v.Set("logs", "1")
  1245. v.Set("stream", "1")
  1246. if config.AttachStdin {
  1247. v.Set("stdin", "1")
  1248. }
  1249. if config.AttachStdout {
  1250. v.Set("stdout", "1")
  1251. }
  1252. if config.AttachStderr {
  1253. v.Set("stderr", "1")
  1254. }
  1255. if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, cli.out); err != nil {
  1256. utils.Debugf("Error hijack: %s", err)
  1257. return err
  1258. }
  1259. }
  1260. if !config.AttachStdout && !config.AttachStderr {
  1261. <-wait
  1262. }
  1263. return nil
  1264. }
  1265. func (cli *DockerCli) checkIfLogged(action string) error {
  1266. // If condition AND the login failed
  1267. if cli.authConfig.Username == "" {
  1268. if err := cli.CmdLogin(""); err != nil {
  1269. return err
  1270. }
  1271. if cli.authConfig.Username == "" {
  1272. return fmt.Errorf("Please login prior to %s. ('docker login')", action)
  1273. }
  1274. }
  1275. return nil
  1276. }
  1277. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1278. var params io.Reader
  1279. if data != nil {
  1280. buf, err := json.Marshal(data)
  1281. if err != nil {
  1282. return nil, -1, err
  1283. }
  1284. params = bytes.NewBuffer(buf)
  1285. }
  1286. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1287. if err != nil {
  1288. return nil, -1, err
  1289. }
  1290. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1291. if data != nil {
  1292. req.Header.Set("Content-Type", "application/json")
  1293. } else if method == "POST" {
  1294. req.Header.Set("Content-Type", "plain/text")
  1295. }
  1296. dial, err := net.Dial(cli.proto, cli.addr)
  1297. if err != nil {
  1298. return nil, -1, err
  1299. }
  1300. clientconn := httputil.NewClientConn(dial, nil)
  1301. resp, err := clientconn.Do(req)
  1302. defer clientconn.Close()
  1303. if err != nil {
  1304. if strings.Contains(err.Error(), "connection refused") {
  1305. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1306. }
  1307. return nil, -1, err
  1308. }
  1309. defer resp.Body.Close()
  1310. body, err := ioutil.ReadAll(resp.Body)
  1311. if err != nil {
  1312. return nil, -1, err
  1313. }
  1314. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1315. if len(body) == 0 {
  1316. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1317. }
  1318. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1319. }
  1320. return body, resp.StatusCode, nil
  1321. }
  1322. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1323. if (method == "POST" || method == "PUT") && in == nil {
  1324. in = bytes.NewReader([]byte{})
  1325. }
  1326. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1327. if err != nil {
  1328. return err
  1329. }
  1330. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1331. if method == "POST" {
  1332. req.Header.Set("Content-Type", "plain/text")
  1333. }
  1334. dial, err := net.Dial(cli.proto, cli.addr)
  1335. if err != nil {
  1336. return err
  1337. }
  1338. clientconn := httputil.NewClientConn(dial, nil)
  1339. resp, err := clientconn.Do(req)
  1340. defer clientconn.Close()
  1341. if err != nil {
  1342. if strings.Contains(err.Error(), "connection refused") {
  1343. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1344. }
  1345. return err
  1346. }
  1347. defer resp.Body.Close()
  1348. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1349. body, err := ioutil.ReadAll(resp.Body)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. if len(body) == 0 {
  1354. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1355. }
  1356. return fmt.Errorf("Error: %s", body)
  1357. }
  1358. if resp.Header.Get("Content-Type") == "application/json" {
  1359. dec := json.NewDecoder(resp.Body)
  1360. for {
  1361. var m utils.JSONMessage
  1362. if err := dec.Decode(&m); err == io.EOF {
  1363. break
  1364. } else if err != nil {
  1365. return err
  1366. }
  1367. if m.Progress != "" {
  1368. fmt.Fprintf(out, "%s %s\r", m.Status, m.Progress)
  1369. } else if m.Error != "" {
  1370. return fmt.Errorf(m.Error)
  1371. } else {
  1372. fmt.Fprintf(out, "%s\n", m.Status)
  1373. }
  1374. }
  1375. } else {
  1376. if _, err := io.Copy(out, resp.Body); err != nil {
  1377. return err
  1378. }
  1379. }
  1380. return nil
  1381. }
  1382. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, out io.Writer) error {
  1383. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1384. if err != nil {
  1385. return err
  1386. }
  1387. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1388. req.Header.Set("Content-Type", "plain/text")
  1389. dial, err := net.Dial(cli.proto, cli.addr)
  1390. if err != nil {
  1391. return err
  1392. }
  1393. clientconn := httputil.NewClientConn(dial, nil)
  1394. defer clientconn.Close()
  1395. // Server hijacks the connection, error 'connection closed' expected
  1396. clientconn.Do(req)
  1397. rwc, br := clientconn.Hijack()
  1398. defer rwc.Close()
  1399. receiveStdout := utils.Go(func() error {
  1400. _, err := io.Copy(out, br)
  1401. return err
  1402. })
  1403. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1404. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1405. if err != nil {
  1406. return err
  1407. }
  1408. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1409. }
  1410. sendStdin := utils.Go(func() error {
  1411. if in != nil {
  1412. io.Copy(rwc, in)
  1413. }
  1414. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1415. if err := tcpc.CloseWrite(); err != nil {
  1416. utils.Debugf("Couldn't send EOF: %s\n", err)
  1417. }
  1418. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1419. if err := unixc.CloseWrite(); err != nil {
  1420. utils.Debugf("Couldn't send EOF: %s\n", err)
  1421. }
  1422. }
  1423. // Discard errors due to pipe interruption
  1424. return nil
  1425. })
  1426. if err := <-receiveStdout; err != nil {
  1427. utils.Debugf("Error receiveStdout: %s", err)
  1428. return err
  1429. }
  1430. if !cli.isTerminal {
  1431. if err := <-sendStdin; err != nil {
  1432. utils.Debugf("Error sendStdin: %s", err)
  1433. return err
  1434. }
  1435. }
  1436. return nil
  1437. }
  1438. func (cli *DockerCli) getTtySize() (int, int) {
  1439. if !cli.isTerminal {
  1440. return 0, 0
  1441. }
  1442. ws, err := term.GetWinsize(cli.terminalFd)
  1443. if err != nil {
  1444. utils.Debugf("Error getting size: %s", err)
  1445. if ws == nil {
  1446. return 0, 0
  1447. }
  1448. }
  1449. return int(ws.Height), int(ws.Width)
  1450. }
  1451. func (cli *DockerCli) resizeTty(id string) {
  1452. height, width := cli.getTtySize()
  1453. if height == 0 && width == 0 {
  1454. return
  1455. }
  1456. v := url.Values{}
  1457. v.Set("h", strconv.Itoa(height))
  1458. v.Set("w", strconv.Itoa(width))
  1459. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1460. utils.Debugf("Error resize: %s", err)
  1461. }
  1462. }
  1463. func (cli *DockerCli) monitorTtySize(id string) error {
  1464. if !cli.isTerminal {
  1465. return fmt.Errorf("Impossible to monitor size on non-tty")
  1466. }
  1467. cli.resizeTty(id)
  1468. c := make(chan os.Signal, 1)
  1469. signal.Notify(c, syscall.SIGWINCH)
  1470. go func() {
  1471. for sig := range c {
  1472. if sig == syscall.SIGWINCH {
  1473. cli.resizeTty(id)
  1474. }
  1475. }
  1476. }()
  1477. return nil
  1478. }
  1479. func Subcmd(name, signature, description string) *flag.FlagSet {
  1480. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1481. flags.Usage = func() {
  1482. // FIXME: use custom stdout or return error
  1483. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1484. flags.PrintDefaults()
  1485. }
  1486. return flags
  1487. }
  1488. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1489. var (
  1490. isTerminal = false
  1491. terminalFd uintptr
  1492. )
  1493. if in != nil {
  1494. if file, ok := in.(*os.File); ok {
  1495. terminalFd = file.Fd()
  1496. isTerminal = term.IsTerminal(terminalFd)
  1497. }
  1498. }
  1499. if err == nil {
  1500. err = out
  1501. }
  1502. authConfig, _ := auth.LoadConfig(os.Getenv("HOME"))
  1503. return &DockerCli{
  1504. proto: proto,
  1505. addr: addr,
  1506. authConfig: authConfig,
  1507. in: in,
  1508. out: out,
  1509. err: err,
  1510. isTerminal: isTerminal,
  1511. terminalFd: terminalFd,
  1512. }
  1513. }
  1514. type DockerCli struct {
  1515. proto string
  1516. addr string
  1517. authConfig *auth.AuthConfig
  1518. in io.ReadCloser
  1519. out io.Writer
  1520. err io.Writer
  1521. isTerminal bool
  1522. terminalFd uintptr
  1523. }