commands.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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 try to stop for before killing the container. Default=10")
  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() == 0 {
  543. cmd.Usage()
  544. return nil
  545. }
  546. val := url.Values{}
  547. if cmd.NArg() > 1 {
  548. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  549. }
  550. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  551. if err != nil {
  552. return err
  553. }
  554. procs := APITop{}
  555. err = json.Unmarshal(body, &procs)
  556. if err != nil {
  557. return err
  558. }
  559. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  560. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  561. for _, proc := range procs.Processes {
  562. fmt.Fprintln(w, strings.Join(proc, "\t"))
  563. }
  564. w.Flush()
  565. return nil
  566. }
  567. func (cli *DockerCli) CmdPort(args ...string) error {
  568. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  569. if err := cmd.Parse(args); err != nil {
  570. return nil
  571. }
  572. if cmd.NArg() != 2 {
  573. cmd.Usage()
  574. return nil
  575. }
  576. port := cmd.Arg(1)
  577. proto := "Tcp"
  578. parts := strings.SplitN(port, "/", 2)
  579. if len(parts) == 2 && len(parts[1]) != 0 {
  580. port = parts[0]
  581. proto = strings.ToUpper(parts[1][:1]) + strings.ToLower(parts[1][1:])
  582. }
  583. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  584. if err != nil {
  585. return err
  586. }
  587. var out Container
  588. err = json.Unmarshal(body, &out)
  589. if err != nil {
  590. return err
  591. }
  592. if frontend, exists := out.NetworkSettings.PortMapping[proto][port]; exists {
  593. fmt.Fprintf(cli.out, "%s\n", frontend)
  594. } else {
  595. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  596. }
  597. return nil
  598. }
  599. // 'docker rmi IMAGE' removes all images with the name IMAGE
  600. func (cli *DockerCli) CmdRmi(args ...string) error {
  601. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  602. if err := cmd.Parse(args); err != nil {
  603. return nil
  604. }
  605. if cmd.NArg() < 1 {
  606. cmd.Usage()
  607. return nil
  608. }
  609. for _, name := range cmd.Args() {
  610. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  611. if err != nil {
  612. fmt.Fprintf(cli.err, "%s", err)
  613. } else {
  614. var outs []APIRmi
  615. err = json.Unmarshal(body, &outs)
  616. if err != nil {
  617. return err
  618. }
  619. for _, out := range outs {
  620. if out.Deleted != "" {
  621. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  622. } else {
  623. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  624. }
  625. }
  626. }
  627. }
  628. return nil
  629. }
  630. func (cli *DockerCli) CmdHistory(args ...string) error {
  631. cmd := Subcmd("history", "IMAGE", "Show the history of an image")
  632. if err := cmd.Parse(args); err != nil {
  633. return nil
  634. }
  635. if cmd.NArg() != 1 {
  636. cmd.Usage()
  637. return nil
  638. }
  639. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  640. if err != nil {
  641. return err
  642. }
  643. var outs []APIHistory
  644. err = json.Unmarshal(body, &outs)
  645. if err != nil {
  646. return err
  647. }
  648. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  649. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY")
  650. for _, out := range outs {
  651. if out.Tags != nil {
  652. out.ID = out.Tags[0]
  653. }
  654. fmt.Fprintf(w, "%s \t%s ago\t%s\n", out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.CreatedBy)
  655. }
  656. w.Flush()
  657. return nil
  658. }
  659. func (cli *DockerCli) CmdRm(args ...string) error {
  660. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  661. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  662. if err := cmd.Parse(args); err != nil {
  663. return nil
  664. }
  665. if cmd.NArg() < 1 {
  666. cmd.Usage()
  667. return nil
  668. }
  669. val := url.Values{}
  670. if *v {
  671. val.Set("v", "1")
  672. }
  673. for _, name := range cmd.Args() {
  674. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  675. if err != nil {
  676. fmt.Fprintf(cli.err, "%s\n", err)
  677. } else {
  678. fmt.Fprintf(cli.out, "%s\n", name)
  679. }
  680. }
  681. return nil
  682. }
  683. // 'docker kill NAME' kills a running container
  684. func (cli *DockerCli) CmdKill(args ...string) error {
  685. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container")
  686. if err := cmd.Parse(args); err != nil {
  687. return nil
  688. }
  689. if cmd.NArg() < 1 {
  690. cmd.Usage()
  691. return nil
  692. }
  693. for _, name := range args {
  694. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  695. if err != nil {
  696. fmt.Fprintf(cli.err, "%s\n", err)
  697. } else {
  698. fmt.Fprintf(cli.out, "%s\n", name)
  699. }
  700. }
  701. return nil
  702. }
  703. func (cli *DockerCli) CmdImport(args ...string) error {
  704. cmd := Subcmd("import", "URL|- [REPOSITORY [TAG]]", "Create a new filesystem image from the contents of a tarball")
  705. if err := cmd.Parse(args); err != nil {
  706. return nil
  707. }
  708. if cmd.NArg() < 1 {
  709. cmd.Usage()
  710. return nil
  711. }
  712. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  713. v := url.Values{}
  714. v.Set("repo", repository)
  715. v.Set("tag", tag)
  716. v.Set("fromSrc", src)
  717. err := cli.stream("POST", "/images/create?"+v.Encode(), cli.in, cli.out)
  718. if err != nil {
  719. return err
  720. }
  721. return nil
  722. }
  723. func (cli *DockerCli) CmdPush(args ...string) error {
  724. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  725. if err := cmd.Parse(args); err != nil {
  726. return nil
  727. }
  728. name := cmd.Arg(0)
  729. if name == "" {
  730. cmd.Usage()
  731. return nil
  732. }
  733. if err := cli.checkIfLogged("push"); err != nil {
  734. return err
  735. }
  736. // If we're not using a custom registry, we know the restrictions
  737. // applied to repository names and can warn the user in advance.
  738. // Custom repositories can have different rules, and we must also
  739. // allow pushing by image ID.
  740. if len(strings.SplitN(name, "/", 2)) == 1 {
  741. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
  742. }
  743. buf, err := json.Marshal(cli.authConfig)
  744. if err != nil {
  745. return err
  746. }
  747. v := url.Values{}
  748. if err := cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), bytes.NewBuffer(buf), cli.out); err != nil {
  749. return err
  750. }
  751. return nil
  752. }
  753. func (cli *DockerCli) CmdPull(args ...string) error {
  754. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  755. tag := cmd.String("t", "", "Download tagged image in repository")
  756. if err := cmd.Parse(args); err != nil {
  757. return nil
  758. }
  759. if cmd.NArg() != 1 {
  760. cmd.Usage()
  761. return nil
  762. }
  763. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  764. if *tag == "" {
  765. *tag = parsedTag
  766. }
  767. v := url.Values{}
  768. v.Set("fromImage", remote)
  769. v.Set("tag", *tag)
  770. if err := cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out); err != nil {
  771. return err
  772. }
  773. return nil
  774. }
  775. func (cli *DockerCli) CmdImages(args ...string) error {
  776. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  777. quiet := cmd.Bool("q", false, "only show numeric IDs")
  778. all := cmd.Bool("a", false, "show all images")
  779. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  780. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  781. if err := cmd.Parse(args); err != nil {
  782. return nil
  783. }
  784. if cmd.NArg() > 1 {
  785. cmd.Usage()
  786. return nil
  787. }
  788. if *flViz {
  789. body, _, err := cli.call("GET", "/images/viz", false)
  790. if err != nil {
  791. return err
  792. }
  793. fmt.Fprintf(cli.out, "%s", body)
  794. } else {
  795. v := url.Values{}
  796. if cmd.NArg() == 1 {
  797. v.Set("filter", cmd.Arg(0))
  798. }
  799. if *all {
  800. v.Set("all", "1")
  801. }
  802. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  803. if err != nil {
  804. return err
  805. }
  806. var outs []APIImages
  807. err = json.Unmarshal(body, &outs)
  808. if err != nil {
  809. return err
  810. }
  811. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  812. if !*quiet {
  813. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  814. }
  815. for _, out := range outs {
  816. if out.Repository == "" {
  817. out.Repository = "<none>"
  818. }
  819. if out.Tag == "" {
  820. out.Tag = "<none>"
  821. }
  822. if !*quiet {
  823. fmt.Fprintf(w, "%s\t%s\t", out.Repository, out.Tag)
  824. if *noTrunc {
  825. fmt.Fprintf(w, "%s\t", out.ID)
  826. } else {
  827. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  828. }
  829. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  830. if out.VirtualSize > 0 {
  831. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  832. } else {
  833. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  834. }
  835. } else {
  836. if *noTrunc {
  837. fmt.Fprintln(w, out.ID)
  838. } else {
  839. fmt.Fprintln(w, utils.TruncateID(out.ID))
  840. }
  841. }
  842. }
  843. if !*quiet {
  844. w.Flush()
  845. }
  846. }
  847. return nil
  848. }
  849. func (cli *DockerCli) CmdPs(args ...string) error {
  850. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  851. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  852. size := cmd.Bool("s", false, "Display sizes")
  853. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  854. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  855. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  856. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  857. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  858. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  859. if err := cmd.Parse(args); err != nil {
  860. return nil
  861. }
  862. v := url.Values{}
  863. if *last == -1 && *nLatest {
  864. *last = 1
  865. }
  866. if *all {
  867. v.Set("all", "1")
  868. }
  869. if *last != -1 {
  870. v.Set("limit", strconv.Itoa(*last))
  871. }
  872. if *since != "" {
  873. v.Set("since", *since)
  874. }
  875. if *before != "" {
  876. v.Set("before", *before)
  877. }
  878. if *size {
  879. v.Set("size", "1")
  880. }
  881. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  882. if err != nil {
  883. return err
  884. }
  885. var outs []APIContainers
  886. err = json.Unmarshal(body, &outs)
  887. if err != nil {
  888. return err
  889. }
  890. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  891. if !*quiet {
  892. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS")
  893. if *size {
  894. fmt.Fprintln(w, "\tSIZE")
  895. } else {
  896. fmt.Fprint(w, "\n")
  897. }
  898. }
  899. for _, out := range outs {
  900. if !*quiet {
  901. if *noTrunc {
  902. 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)
  903. } else {
  904. 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)
  905. }
  906. if *size {
  907. if out.SizeRootFs > 0 {
  908. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  909. } else {
  910. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  911. }
  912. } else {
  913. fmt.Fprint(w, "\n")
  914. }
  915. } else {
  916. if *noTrunc {
  917. fmt.Fprintln(w, out.ID)
  918. } else {
  919. fmt.Fprintln(w, utils.TruncateID(out.ID))
  920. }
  921. }
  922. }
  923. if !*quiet {
  924. w.Flush()
  925. }
  926. return nil
  927. }
  928. func (cli *DockerCli) CmdCommit(args ...string) error {
  929. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  930. flComment := cmd.String("m", "", "Commit message")
  931. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  932. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  933. if err := cmd.Parse(args); err != nil {
  934. return nil
  935. }
  936. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  937. if name == "" {
  938. cmd.Usage()
  939. return nil
  940. }
  941. v := url.Values{}
  942. v.Set("container", name)
  943. v.Set("repo", repository)
  944. v.Set("tag", tag)
  945. v.Set("comment", *flComment)
  946. v.Set("author", *flAuthor)
  947. var config *Config
  948. if *flConfig != "" {
  949. config = &Config{}
  950. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  951. return err
  952. }
  953. }
  954. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  955. if err != nil {
  956. return err
  957. }
  958. apiID := &APIID{}
  959. err = json.Unmarshal(body, apiID)
  960. if err != nil {
  961. return err
  962. }
  963. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  964. return nil
  965. }
  966. func (cli *DockerCli) CmdExport(args ...string) error {
  967. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  968. if err := cmd.Parse(args); err != nil {
  969. return nil
  970. }
  971. if cmd.NArg() != 1 {
  972. cmd.Usage()
  973. return nil
  974. }
  975. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out); err != nil {
  976. return err
  977. }
  978. return nil
  979. }
  980. func (cli *DockerCli) CmdDiff(args ...string) error {
  981. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  982. if err := cmd.Parse(args); err != nil {
  983. return nil
  984. }
  985. if cmd.NArg() != 1 {
  986. cmd.Usage()
  987. return nil
  988. }
  989. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  990. if err != nil {
  991. return err
  992. }
  993. changes := []Change{}
  994. err = json.Unmarshal(body, &changes)
  995. if err != nil {
  996. return err
  997. }
  998. for _, change := range changes {
  999. fmt.Fprintf(cli.out, "%s\n", change.String())
  1000. }
  1001. return nil
  1002. }
  1003. func (cli *DockerCli) CmdLogs(args ...string) error {
  1004. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1005. if err := cmd.Parse(args); err != nil {
  1006. return nil
  1007. }
  1008. if cmd.NArg() != 1 {
  1009. cmd.Usage()
  1010. return nil
  1011. }
  1012. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stdout=1", false, nil, cli.out); err != nil {
  1013. return err
  1014. }
  1015. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?logs=1&stderr=1", false, nil, cli.err); err != nil {
  1016. return err
  1017. }
  1018. return nil
  1019. }
  1020. func (cli *DockerCli) CmdAttach(args ...string) error {
  1021. cmd := Subcmd("attach", "CONTAINER", "Attach to a running container")
  1022. if err := cmd.Parse(args); err != nil {
  1023. return nil
  1024. }
  1025. if cmd.NArg() != 1 {
  1026. cmd.Usage()
  1027. return nil
  1028. }
  1029. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  1030. if err != nil {
  1031. return err
  1032. }
  1033. container := &Container{}
  1034. err = json.Unmarshal(body, container)
  1035. if err != nil {
  1036. return err
  1037. }
  1038. if !container.State.Running {
  1039. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1040. }
  1041. if container.Config.Tty {
  1042. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1043. return err
  1044. }
  1045. }
  1046. v := url.Values{}
  1047. v.Set("stream", "1")
  1048. v.Set("stdin", "1")
  1049. v.Set("stdout", "1")
  1050. v.Set("stderr", "1")
  1051. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, cli.in, cli.out); err != nil {
  1052. return err
  1053. }
  1054. return nil
  1055. }
  1056. func (cli *DockerCli) CmdSearch(args ...string) error {
  1057. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  1058. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1059. if err := cmd.Parse(args); err != nil {
  1060. return nil
  1061. }
  1062. if cmd.NArg() != 1 {
  1063. cmd.Usage()
  1064. return nil
  1065. }
  1066. v := url.Values{}
  1067. v.Set("term", cmd.Arg(0))
  1068. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1069. if err != nil {
  1070. return err
  1071. }
  1072. outs := []APISearch{}
  1073. err = json.Unmarshal(body, &outs)
  1074. if err != nil {
  1075. return err
  1076. }
  1077. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1078. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1079. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1080. _, width := cli.getTtySize()
  1081. if width == 0 {
  1082. width = 45
  1083. } else {
  1084. width = width - 33 //remote the first column
  1085. }
  1086. for _, out := range outs {
  1087. desc := strings.Replace(out.Description, "\n", " ", -1)
  1088. desc = strings.Replace(desc, "\r", " ", -1)
  1089. if !*noTrunc && len(desc) > width {
  1090. desc = utils.Trunc(desc, width-3) + "..."
  1091. }
  1092. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1093. }
  1094. w.Flush()
  1095. return nil
  1096. }
  1097. // Ports type - Used to parse multiple -p flags
  1098. type ports []int
  1099. // ListOpts type
  1100. type ListOpts []string
  1101. func (opts *ListOpts) String() string {
  1102. return fmt.Sprint(*opts)
  1103. }
  1104. func (opts *ListOpts) Set(value string) error {
  1105. *opts = append(*opts, value)
  1106. return nil
  1107. }
  1108. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1109. type AttachOpts map[string]bool
  1110. func NewAttachOpts() AttachOpts {
  1111. return make(AttachOpts)
  1112. }
  1113. func (opts AttachOpts) String() string {
  1114. // Cast to underlying map type to avoid infinite recursion
  1115. return fmt.Sprintf("%v", map[string]bool(opts))
  1116. }
  1117. func (opts AttachOpts) Set(val string) error {
  1118. if val != "stdin" && val != "stdout" && val != "stderr" {
  1119. return fmt.Errorf("Unsupported stream name: %s", val)
  1120. }
  1121. opts[val] = true
  1122. return nil
  1123. }
  1124. func (opts AttachOpts) Get(val string) bool {
  1125. if res, exists := opts[val]; exists {
  1126. return res
  1127. }
  1128. return false
  1129. }
  1130. // PathOpts stores a unique set of absolute paths
  1131. type PathOpts map[string]struct{}
  1132. func NewPathOpts() PathOpts {
  1133. return make(PathOpts)
  1134. }
  1135. func (opts PathOpts) String() string {
  1136. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1137. }
  1138. func (opts PathOpts) Set(val string) error {
  1139. var containerPath string
  1140. splited := strings.SplitN(val, ":", 2)
  1141. if len(splited) == 1 {
  1142. containerPath = splited[0]
  1143. val = filepath.Clean(splited[0])
  1144. } else {
  1145. containerPath = splited[1]
  1146. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1147. }
  1148. if !filepath.IsAbs(containerPath) {
  1149. utils.Debugf("%s is not an absolute path", containerPath)
  1150. return fmt.Errorf("%s is not an absolute path", containerPath)
  1151. }
  1152. opts[val] = struct{}{}
  1153. return nil
  1154. }
  1155. func (cli *DockerCli) CmdTag(args ...string) error {
  1156. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1157. force := cmd.Bool("f", false, "Force")
  1158. if err := cmd.Parse(args); err != nil {
  1159. return nil
  1160. }
  1161. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1162. cmd.Usage()
  1163. return nil
  1164. }
  1165. v := url.Values{}
  1166. v.Set("repo", cmd.Arg(1))
  1167. if cmd.NArg() == 3 {
  1168. v.Set("tag", cmd.Arg(2))
  1169. }
  1170. if *force {
  1171. v.Set("force", "1")
  1172. }
  1173. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1174. return err
  1175. }
  1176. return nil
  1177. }
  1178. func (cli *DockerCli) CmdRun(args ...string) error {
  1179. config, hostConfig, cmd, err := ParseRun(args, nil)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. if config.Image == "" {
  1184. cmd.Usage()
  1185. return nil
  1186. }
  1187. //create the container
  1188. body, statusCode, err := cli.call("POST", "/containers/create", config)
  1189. //if image not found try to pull it
  1190. if statusCode == 404 {
  1191. v := url.Values{}
  1192. repos, tag := utils.ParseRepositoryTag(config.Image)
  1193. v.Set("fromImage", repos)
  1194. v.Set("tag", tag)
  1195. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err)
  1196. if err != nil {
  1197. return err
  1198. }
  1199. body, _, err = cli.call("POST", "/containers/create", config)
  1200. if err != nil {
  1201. return err
  1202. }
  1203. }
  1204. if err != nil {
  1205. return err
  1206. }
  1207. runResult := &APIRun{}
  1208. err = json.Unmarshal(body, runResult)
  1209. if err != nil {
  1210. return err
  1211. }
  1212. for _, warning := range runResult.Warnings {
  1213. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1214. }
  1215. //start the container
  1216. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1217. return err
  1218. }
  1219. var wait chan struct{}
  1220. if !config.AttachStdout && !config.AttachStderr {
  1221. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1222. wait = make(chan struct{})
  1223. go func() {
  1224. defer close(wait)
  1225. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1226. }()
  1227. }
  1228. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1229. if config.Tty {
  1230. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1231. return err
  1232. }
  1233. }
  1234. v := url.Values{}
  1235. v.Set("logs", "1")
  1236. v.Set("stream", "1")
  1237. if config.AttachStdin {
  1238. v.Set("stdin", "1")
  1239. }
  1240. if config.AttachStdout {
  1241. v.Set("stdout", "1")
  1242. }
  1243. if config.AttachStderr {
  1244. v.Set("stderr", "1")
  1245. }
  1246. if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, cli.out); err != nil {
  1247. utils.Debugf("Error hijack: %s", err)
  1248. return err
  1249. }
  1250. }
  1251. if !config.AttachStdout && !config.AttachStderr {
  1252. <-wait
  1253. }
  1254. return nil
  1255. }
  1256. func (cli *DockerCli) checkIfLogged(action string) error {
  1257. // If condition AND the login failed
  1258. if cli.authConfig.Username == "" {
  1259. if err := cli.CmdLogin(""); err != nil {
  1260. return err
  1261. }
  1262. if cli.authConfig.Username == "" {
  1263. return fmt.Errorf("Please login prior to %s. ('docker login')", action)
  1264. }
  1265. }
  1266. return nil
  1267. }
  1268. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1269. var params io.Reader
  1270. if data != nil {
  1271. buf, err := json.Marshal(data)
  1272. if err != nil {
  1273. return nil, -1, err
  1274. }
  1275. params = bytes.NewBuffer(buf)
  1276. }
  1277. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1278. if err != nil {
  1279. return nil, -1, err
  1280. }
  1281. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1282. if data != nil {
  1283. req.Header.Set("Content-Type", "application/json")
  1284. } else if method == "POST" {
  1285. req.Header.Set("Content-Type", "plain/text")
  1286. }
  1287. dial, err := net.Dial(cli.proto, cli.addr)
  1288. if err != nil {
  1289. return nil, -1, err
  1290. }
  1291. clientconn := httputil.NewClientConn(dial, nil)
  1292. resp, err := clientconn.Do(req)
  1293. defer clientconn.Close()
  1294. if err != nil {
  1295. if strings.Contains(err.Error(), "connection refused") {
  1296. return nil, -1, fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1297. }
  1298. return nil, -1, err
  1299. }
  1300. defer resp.Body.Close()
  1301. body, err := ioutil.ReadAll(resp.Body)
  1302. if err != nil {
  1303. return nil, -1, err
  1304. }
  1305. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1306. if len(body) == 0 {
  1307. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1308. }
  1309. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1310. }
  1311. return body, resp.StatusCode, nil
  1312. }
  1313. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) error {
  1314. if (method == "POST" || method == "PUT") && in == nil {
  1315. in = bytes.NewReader([]byte{})
  1316. }
  1317. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1318. if err != nil {
  1319. return err
  1320. }
  1321. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1322. if method == "POST" {
  1323. req.Header.Set("Content-Type", "plain/text")
  1324. }
  1325. dial, err := net.Dial(cli.proto, cli.addr)
  1326. if err != nil {
  1327. return err
  1328. }
  1329. clientconn := httputil.NewClientConn(dial, nil)
  1330. resp, err := clientconn.Do(req)
  1331. defer clientconn.Close()
  1332. if err != nil {
  1333. if strings.Contains(err.Error(), "connection refused") {
  1334. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1335. }
  1336. return err
  1337. }
  1338. defer resp.Body.Close()
  1339. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1340. body, err := ioutil.ReadAll(resp.Body)
  1341. if err != nil {
  1342. return err
  1343. }
  1344. if len(body) == 0 {
  1345. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1346. }
  1347. return fmt.Errorf("Error: %s", body)
  1348. }
  1349. if resp.Header.Get("Content-Type") == "application/json" {
  1350. dec := json.NewDecoder(resp.Body)
  1351. for {
  1352. var m utils.JSONMessage
  1353. if err := dec.Decode(&m); err == io.EOF {
  1354. break
  1355. } else if err != nil {
  1356. return err
  1357. }
  1358. if m.Progress != "" {
  1359. fmt.Fprintf(out, "%s %s\r", m.Status, m.Progress)
  1360. } else if m.Error != "" {
  1361. return fmt.Errorf(m.Error)
  1362. } else {
  1363. fmt.Fprintf(out, "%s\n", m.Status)
  1364. }
  1365. }
  1366. } else {
  1367. if _, err := io.Copy(out, resp.Body); err != nil {
  1368. return err
  1369. }
  1370. }
  1371. return nil
  1372. }
  1373. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, out io.Writer) error {
  1374. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1375. if err != nil {
  1376. return err
  1377. }
  1378. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1379. req.Header.Set("Content-Type", "plain/text")
  1380. dial, err := net.Dial(cli.proto, cli.addr)
  1381. if err != nil {
  1382. return err
  1383. }
  1384. clientconn := httputil.NewClientConn(dial, nil)
  1385. defer clientconn.Close()
  1386. // Server hijacks the connection, error 'connection closed' expected
  1387. clientconn.Do(req)
  1388. rwc, br := clientconn.Hijack()
  1389. defer rwc.Close()
  1390. receiveStdout := utils.Go(func() error {
  1391. _, err := io.Copy(out, br)
  1392. return err
  1393. })
  1394. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1395. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1396. if err != nil {
  1397. return err
  1398. }
  1399. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1400. }
  1401. sendStdin := utils.Go(func() error {
  1402. if in != nil {
  1403. io.Copy(rwc, in)
  1404. }
  1405. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1406. if err := tcpc.CloseWrite(); err != nil {
  1407. utils.Debugf("Couldn't send EOF: %s\n", err)
  1408. }
  1409. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1410. if err := unixc.CloseWrite(); err != nil {
  1411. utils.Debugf("Couldn't send EOF: %s\n", err)
  1412. }
  1413. }
  1414. // Discard errors due to pipe interruption
  1415. return nil
  1416. })
  1417. if err := <-receiveStdout; err != nil {
  1418. utils.Debugf("Error receiveStdout: %s", err)
  1419. return err
  1420. }
  1421. if !cli.isTerminal {
  1422. if err := <-sendStdin; err != nil {
  1423. utils.Debugf("Error sendStdin: %s", err)
  1424. return err
  1425. }
  1426. }
  1427. return nil
  1428. }
  1429. func (cli *DockerCli) getTtySize() (int, int) {
  1430. if !cli.isTerminal {
  1431. return 0, 0
  1432. }
  1433. ws, err := term.GetWinsize(cli.terminalFd)
  1434. if err != nil {
  1435. utils.Debugf("Error getting size: %s", err)
  1436. if ws == nil {
  1437. return 0, 0
  1438. }
  1439. }
  1440. return int(ws.Height), int(ws.Width)
  1441. }
  1442. func (cli *DockerCli) resizeTty(id string) {
  1443. height, width := cli.getTtySize()
  1444. if height == 0 && width == 0 {
  1445. return
  1446. }
  1447. v := url.Values{}
  1448. v.Set("h", strconv.Itoa(height))
  1449. v.Set("w", strconv.Itoa(width))
  1450. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1451. utils.Debugf("Error resize: %s", err)
  1452. }
  1453. }
  1454. func (cli *DockerCli) monitorTtySize(id string) error {
  1455. if !cli.isTerminal {
  1456. return fmt.Errorf("Impossible to monitor size on non-tty")
  1457. }
  1458. cli.resizeTty(id)
  1459. c := make(chan os.Signal, 1)
  1460. signal.Notify(c, syscall.SIGWINCH)
  1461. go func() {
  1462. for sig := range c {
  1463. if sig == syscall.SIGWINCH {
  1464. cli.resizeTty(id)
  1465. }
  1466. }
  1467. }()
  1468. return nil
  1469. }
  1470. func Subcmd(name, signature, description string) *flag.FlagSet {
  1471. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1472. flags.Usage = func() {
  1473. // FIXME: use custom stdout or return error
  1474. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1475. flags.PrintDefaults()
  1476. }
  1477. return flags
  1478. }
  1479. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1480. var (
  1481. isTerminal = false
  1482. terminalFd uintptr
  1483. )
  1484. if in != nil {
  1485. if file, ok := in.(*os.File); ok {
  1486. terminalFd = file.Fd()
  1487. isTerminal = term.IsTerminal(terminalFd)
  1488. }
  1489. }
  1490. if err == nil {
  1491. err = out
  1492. }
  1493. authConfig, _ := auth.LoadConfig(os.Getenv("HOME"))
  1494. return &DockerCli{
  1495. proto: proto,
  1496. addr: addr,
  1497. authConfig: authConfig,
  1498. in: in,
  1499. out: out,
  1500. err: err,
  1501. isTerminal: isTerminal,
  1502. terminalFd: terminalFd,
  1503. }
  1504. }
  1505. type DockerCli struct {
  1506. proto string
  1507. addr string
  1508. authConfig *auth.AuthConfig
  1509. in io.ReadCloser
  1510. out io.Writer
  1511. err io.Writer
  1512. isTerminal bool
  1513. terminalFd uintptr
  1514. }