commands.go 45 KB

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