commands.go 53 KB

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