commands.go 43 KB

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