commands.go 52 KB

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