commands.go 44 KB

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