commands.go 52 KB

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