commands.go 43 KB

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