commands.go 46 KB

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