commands.go 45 KB

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