commands.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  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/archive"
  12. "github.com/dotcloud/docker/auth"
  13. "github.com/dotcloud/docker/registry"
  14. "github.com/dotcloud/docker/term"
  15. "github.com/dotcloud/docker/utils"
  16. "io"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/http/httputil"
  21. "net/url"
  22. "os"
  23. "os/signal"
  24. "path/filepath"
  25. "reflect"
  26. "regexp"
  27. "runtime"
  28. "sort"
  29. "strconv"
  30. "strings"
  31. "syscall"
  32. "text/tabwriter"
  33. "time"
  34. )
  35. var (
  36. GITCOMMIT string
  37. VERSION string
  38. )
  39. var (
  40. ErrConnectionRefused = errors.New("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  41. )
  42. func (cli *DockerCli) getMethod(name string) (func(...string) error, bool) {
  43. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  44. method := reflect.ValueOf(cli).MethodByName(methodName)
  45. if !method.IsValid() {
  46. return nil, false
  47. }
  48. return method.Interface().(func(...string) error), true
  49. }
  50. func ParseCommands(proto, addr string, args ...string) error {
  51. cli := NewDockerCli(os.Stdin, os.Stdout, os.Stderr, proto, addr)
  52. if len(args) > 0 {
  53. method, exists := cli.getMethod(args[0])
  54. if !exists {
  55. fmt.Println("Error: Command not found:", args[0])
  56. return cli.CmdHelp(args[1:]...)
  57. }
  58. return method(args[1:]...)
  59. }
  60. return cli.CmdHelp(args...)
  61. }
  62. func (cli *DockerCli) CmdHelp(args ...string) error {
  63. if len(args) > 0 {
  64. method, exists := cli.getMethod(args[0])
  65. if !exists {
  66. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  67. } else {
  68. method("--help")
  69. return nil
  70. }
  71. }
  72. 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)
  73. for _, command := range [][]string{
  74. {"attach", "Attach to a running container"},
  75. {"build", "Build a container from a Dockerfile"},
  76. {"commit", "Create a new image from a container's changes"},
  77. {"cp", "Copy files/folders from the containers filesystem to the host path"},
  78. {"diff", "Inspect changes on a container's filesystem"},
  79. {"events", "Get real time events from the server"},
  80. {"export", "Stream the contents of a container as a tar archive"},
  81. {"history", "Show the history of an image"},
  82. {"images", "List images"},
  83. {"import", "Create a new filesystem image from the contents of a tarball"},
  84. {"info", "Display system-wide information"},
  85. {"insert", "Insert a file in an image"},
  86. {"inspect", "Return low-level information on a container"},
  87. {"kill", "Kill a running container"},
  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.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.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 = archive.Tar(cmd.Arg(0), archive.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 (Send SIGTERM, and then SIGKILL after grace period)")
  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) chan os.Signal {
  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. return sigc
  508. }
  509. func (cli *DockerCli) CmdStart(args ...string) error {
  510. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  511. attach := cmd.Bool("a", false, "Attach container's stdout/stderr and forward all signals to the process")
  512. openStdin := cmd.Bool("i", false, "Attach container's stdin")
  513. if err := cmd.Parse(args); err != nil {
  514. return nil
  515. }
  516. if cmd.NArg() < 1 {
  517. cmd.Usage()
  518. return nil
  519. }
  520. var cErr chan error
  521. if *attach || *openStdin {
  522. if cmd.NArg() > 1 {
  523. return fmt.Errorf("Impossible to start and attach multiple containers at once.")
  524. }
  525. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  526. if err != nil {
  527. return err
  528. }
  529. container := &Container{}
  530. err = json.Unmarshal(body, container)
  531. if err != nil {
  532. return err
  533. }
  534. if !container.Config.Tty {
  535. sigc := cli.forwardAllSignals(cmd.Arg(0))
  536. defer utils.StopCatch(sigc)
  537. }
  538. if container.Config.Tty && cli.isTerminal {
  539. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  540. return err
  541. }
  542. }
  543. var in io.ReadCloser
  544. v := url.Values{}
  545. v.Set("stream", "1")
  546. if *openStdin && container.Config.OpenStdin {
  547. v.Set("stdin", "1")
  548. in = cli.in
  549. }
  550. v.Set("stdout", "1")
  551. v.Set("stderr", "1")
  552. cErr = utils.Go(func() error {
  553. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil)
  554. })
  555. }
  556. var encounteredError error
  557. for _, name := range cmd.Args() {
  558. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  559. if err != nil {
  560. if !*attach || !*openStdin {
  561. fmt.Fprintf(cli.err, "%s\n", err)
  562. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  563. }
  564. } else {
  565. if !*attach || !*openStdin {
  566. fmt.Fprintf(cli.out, "%s\n", name)
  567. }
  568. }
  569. }
  570. if encounteredError != nil {
  571. if *openStdin || *attach {
  572. cli.in.Close()
  573. <-cErr
  574. }
  575. return encounteredError
  576. }
  577. if *openStdin || *attach {
  578. return <-cErr
  579. }
  580. return nil
  581. }
  582. func (cli *DockerCli) CmdInspect(args ...string) error {
  583. cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  584. if err := cmd.Parse(args); err != nil {
  585. return nil
  586. }
  587. if cmd.NArg() < 1 {
  588. cmd.Usage()
  589. return nil
  590. }
  591. indented := new(bytes.Buffer)
  592. status := 0
  593. for _, name := range args {
  594. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  595. if err != nil {
  596. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  597. if err != nil {
  598. fmt.Fprintf(cli.err, "No such image or container: %s\n", name)
  599. status = 1
  600. continue
  601. }
  602. }
  603. if err = json.Indent(indented, obj, "", " "); err != nil {
  604. fmt.Fprintf(cli.err, "%s\n", err)
  605. status = 1
  606. continue
  607. }
  608. indented.WriteString(",")
  609. }
  610. // Remove trailling ','
  611. indented.Truncate(indented.Len() - 1)
  612. fmt.Fprintf(cli.out, "[")
  613. if _, err := io.Copy(cli.out, indented); err != nil {
  614. return err
  615. }
  616. fmt.Fprintf(cli.out, "]")
  617. if status != 0 {
  618. return &utils.StatusError{Status: status}
  619. }
  620. return nil
  621. }
  622. func (cli *DockerCli) CmdTop(args ...string) error {
  623. cmd := Subcmd("top", "CONTAINER [ps OPTIONS]", "Lookup the running processes of a container")
  624. if err := cmd.Parse(args); err != nil {
  625. return nil
  626. }
  627. if cmd.NArg() == 0 {
  628. cmd.Usage()
  629. return nil
  630. }
  631. val := url.Values{}
  632. if cmd.NArg() > 1 {
  633. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  634. }
  635. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  636. if err != nil {
  637. return err
  638. }
  639. procs := APITop{}
  640. err = json.Unmarshal(body, &procs)
  641. if err != nil {
  642. return err
  643. }
  644. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  645. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  646. for _, proc := range procs.Processes {
  647. fmt.Fprintln(w, strings.Join(proc, "\t"))
  648. }
  649. w.Flush()
  650. return nil
  651. }
  652. func (cli *DockerCli) CmdPort(args ...string) error {
  653. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  654. if err := cmd.Parse(args); err != nil {
  655. return nil
  656. }
  657. if cmd.NArg() != 2 {
  658. cmd.Usage()
  659. return nil
  660. }
  661. port := cmd.Arg(1)
  662. proto := "tcp"
  663. parts := strings.SplitN(port, "/", 2)
  664. if len(parts) == 2 && len(parts[1]) != 0 {
  665. port = parts[0]
  666. proto = parts[1]
  667. }
  668. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  669. if err != nil {
  670. return err
  671. }
  672. var out Container
  673. err = json.Unmarshal(body, &out)
  674. if err != nil {
  675. return err
  676. }
  677. if frontends, exists := out.NetworkSettings.Ports[Port(port+"/"+proto)]; exists {
  678. if frontends == nil {
  679. fmt.Fprintf(cli.out, "%s\n", port)
  680. } else {
  681. for _, frontend := range frontends {
  682. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  683. }
  684. }
  685. } else {
  686. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  687. }
  688. return nil
  689. }
  690. // 'docker rmi IMAGE' removes all images with the name IMAGE
  691. func (cli *DockerCli) CmdRmi(args ...string) error {
  692. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  693. if err := cmd.Parse(args); err != nil {
  694. return nil
  695. }
  696. if cmd.NArg() < 1 {
  697. cmd.Usage()
  698. return nil
  699. }
  700. for _, name := range cmd.Args() {
  701. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  702. if err != nil {
  703. fmt.Fprintf(cli.err, "%s", err)
  704. } else {
  705. var outs []APIRmi
  706. err = json.Unmarshal(body, &outs)
  707. if err != nil {
  708. return err
  709. }
  710. for _, out := range outs {
  711. if out.Deleted != "" {
  712. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  713. } else {
  714. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  715. }
  716. }
  717. }
  718. }
  719. return nil
  720. }
  721. func (cli *DockerCli) CmdHistory(args ...string) error {
  722. cmd := Subcmd("history", "[OPTIONS] IMAGE", "Show the history of an image")
  723. quiet := cmd.Bool("q", false, "only show numeric IDs")
  724. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  725. if err := cmd.Parse(args); err != nil {
  726. return nil
  727. }
  728. if cmd.NArg() != 1 {
  729. cmd.Usage()
  730. return nil
  731. }
  732. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  733. if err != nil {
  734. return err
  735. }
  736. var outs []APIHistory
  737. err = json.Unmarshal(body, &outs)
  738. if err != nil {
  739. return err
  740. }
  741. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  742. if !*quiet {
  743. fmt.Fprintln(w, "ID\tCREATED\tCREATED BY\tSIZE")
  744. }
  745. for _, out := range outs {
  746. if !*quiet {
  747. if *noTrunc {
  748. fmt.Fprintf(w, "%s\t", out.ID)
  749. } else {
  750. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  751. }
  752. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  753. if *noTrunc {
  754. fmt.Fprintf(w, "%s\t", out.CreatedBy)
  755. } else {
  756. fmt.Fprintf(w, "%s\t", utils.Trunc(out.CreatedBy, 45))
  757. }
  758. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  759. } else {
  760. if *noTrunc {
  761. fmt.Fprintln(w, out.ID)
  762. } else {
  763. fmt.Fprintln(w, utils.TruncateID(out.ID))
  764. }
  765. }
  766. }
  767. w.Flush()
  768. return nil
  769. }
  770. func (cli *DockerCli) CmdRm(args ...string) error {
  771. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  772. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  773. link := cmd.Bool("link", false, "Remove the specified link and not the underlying container")
  774. if err := cmd.Parse(args); err != nil {
  775. return nil
  776. }
  777. if cmd.NArg() < 1 {
  778. cmd.Usage()
  779. return nil
  780. }
  781. val := url.Values{}
  782. if *v {
  783. val.Set("v", "1")
  784. }
  785. if *link {
  786. val.Set("link", "1")
  787. }
  788. for _, name := range cmd.Args() {
  789. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  790. if err != nil {
  791. fmt.Fprintf(cli.err, "%s\n", err)
  792. } else {
  793. fmt.Fprintf(cli.out, "%s\n", name)
  794. }
  795. }
  796. return nil
  797. }
  798. // 'docker kill NAME' kills a running container
  799. func (cli *DockerCli) CmdKill(args ...string) error {
  800. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container (send SIGKILL)")
  801. if err := cmd.Parse(args); err != nil {
  802. return nil
  803. }
  804. if cmd.NArg() < 1 {
  805. cmd.Usage()
  806. return nil
  807. }
  808. for _, name := range args {
  809. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  810. if err != nil {
  811. fmt.Fprintf(cli.err, "%s\n", err)
  812. } else {
  813. fmt.Fprintf(cli.out, "%s\n", name)
  814. }
  815. }
  816. return nil
  817. }
  818. func (cli *DockerCli) CmdImport(args ...string) error {
  819. 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).")
  820. if err := cmd.Parse(args); err != nil {
  821. return nil
  822. }
  823. if cmd.NArg() < 1 {
  824. cmd.Usage()
  825. return nil
  826. }
  827. src, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  828. v := url.Values{}
  829. v.Set("repo", repository)
  830. v.Set("tag", tag)
  831. v.Set("fromSrc", src)
  832. var in io.Reader
  833. if src == "-" {
  834. in = cli.in
  835. }
  836. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  837. }
  838. func (cli *DockerCli) CmdPush(args ...string) error {
  839. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  840. if err := cmd.Parse(args); err != nil {
  841. return nil
  842. }
  843. name := cmd.Arg(0)
  844. if name == "" {
  845. cmd.Usage()
  846. return nil
  847. }
  848. cli.LoadConfigFile()
  849. // Resolve the Repository name from fqn to endpoint + name
  850. endpoint, _, err := registry.ResolveRepositoryName(name)
  851. if err != nil {
  852. return err
  853. }
  854. // Resolve the Auth config relevant for this server
  855. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  856. // If we're not using a custom registry, we know the restrictions
  857. // applied to repository names and can warn the user in advance.
  858. // Custom repositories can have different rules, and we must also
  859. // allow pushing by image ID.
  860. if len(strings.SplitN(name, "/", 2)) == 1 {
  861. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  862. if username == "" {
  863. username = "<user>"
  864. }
  865. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  866. }
  867. v := url.Values{}
  868. push := func(authConfig auth.AuthConfig) error {
  869. buf, err := json.Marshal(authConfig)
  870. if err != nil {
  871. return err
  872. }
  873. registryAuthHeader := []string{
  874. base64.URLEncoding.EncodeToString(buf),
  875. }
  876. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  877. "X-Registry-Auth": registryAuthHeader,
  878. })
  879. }
  880. if err := push(authConfig); err != nil {
  881. if err.Error() == registry.ErrLoginRequired.Error() {
  882. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  883. if err := cli.CmdLogin(endpoint); err != nil {
  884. return err
  885. }
  886. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  887. return push(authConfig)
  888. }
  889. return err
  890. }
  891. return nil
  892. }
  893. func (cli *DockerCli) CmdPull(args ...string) error {
  894. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  895. tag := cmd.String("t", "", "Download tagged image in repository")
  896. if err := cmd.Parse(args); err != nil {
  897. return nil
  898. }
  899. if cmd.NArg() != 1 {
  900. cmd.Usage()
  901. return nil
  902. }
  903. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  904. if *tag == "" {
  905. *tag = parsedTag
  906. }
  907. // Resolve the Repository name from fqn to endpoint + name
  908. endpoint, _, err := registry.ResolveRepositoryName(remote)
  909. if err != nil {
  910. return err
  911. }
  912. cli.LoadConfigFile()
  913. // Resolve the Auth config relevant for this server
  914. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  915. v := url.Values{}
  916. v.Set("fromImage", remote)
  917. v.Set("tag", *tag)
  918. pull := func(authConfig auth.AuthConfig) error {
  919. buf, err := json.Marshal(authConfig)
  920. if err != nil {
  921. return err
  922. }
  923. registryAuthHeader := []string{
  924. base64.URLEncoding.EncodeToString(buf),
  925. }
  926. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  927. "X-Registry-Auth": registryAuthHeader,
  928. })
  929. }
  930. if err := pull(authConfig); err != nil {
  931. if err.Error() == registry.ErrLoginRequired.Error() {
  932. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  933. if err := cli.CmdLogin(endpoint); err != nil {
  934. return err
  935. }
  936. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  937. return pull(authConfig)
  938. }
  939. return err
  940. }
  941. return nil
  942. }
  943. func (cli *DockerCli) CmdImages(args ...string) error {
  944. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  945. quiet := cmd.Bool("q", false, "only show numeric IDs")
  946. all := cmd.Bool("a", false, "show all images")
  947. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  948. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  949. if err := cmd.Parse(args); err != nil {
  950. return nil
  951. }
  952. if cmd.NArg() > 1 {
  953. cmd.Usage()
  954. return nil
  955. }
  956. if *flViz {
  957. body, _, err := cli.call("GET", "/images/viz", false)
  958. if err != nil {
  959. return err
  960. }
  961. fmt.Fprintf(cli.out, "%s", body)
  962. } else {
  963. v := url.Values{}
  964. if cmd.NArg() == 1 {
  965. v.Set("filter", cmd.Arg(0))
  966. }
  967. if *all {
  968. v.Set("all", "1")
  969. }
  970. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  971. if err != nil {
  972. return err
  973. }
  974. var outs []APIImages
  975. err = json.Unmarshal(body, &outs)
  976. if err != nil {
  977. return err
  978. }
  979. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  980. if !*quiet {
  981. fmt.Fprintln(w, "REPOSITORY\tTAG\tID\tCREATED\tSIZE")
  982. }
  983. for _, out := range outs {
  984. if out.Repository == "" {
  985. out.Repository = "<none>"
  986. }
  987. if out.Tag == "" {
  988. out.Tag = "<none>"
  989. }
  990. if !*noTrunc {
  991. out.ID = utils.TruncateID(out.ID)
  992. }
  993. if !*quiet {
  994. 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))))
  995. if out.VirtualSize > 0 {
  996. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  997. } else {
  998. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  999. }
  1000. } else {
  1001. fmt.Fprintln(w, out.ID)
  1002. }
  1003. }
  1004. if !*quiet {
  1005. w.Flush()
  1006. }
  1007. }
  1008. return nil
  1009. }
  1010. func displayablePorts(ports []APIPort) string {
  1011. result := []string{}
  1012. for _, port := range ports {
  1013. if port.IP == "" {
  1014. result = append(result, fmt.Sprintf("%d/%s", port.PublicPort, port.Type))
  1015. } else {
  1016. result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
  1017. }
  1018. }
  1019. sort.Strings(result)
  1020. return strings.Join(result, ", ")
  1021. }
  1022. func (cli *DockerCli) CmdPs(args ...string) error {
  1023. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  1024. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  1025. size := cmd.Bool("s", false, "Display sizes")
  1026. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  1027. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1028. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  1029. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  1030. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  1031. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  1032. if err := cmd.Parse(args); err != nil {
  1033. return nil
  1034. }
  1035. v := url.Values{}
  1036. if *last == -1 && *nLatest {
  1037. *last = 1
  1038. }
  1039. if *all {
  1040. v.Set("all", "1")
  1041. }
  1042. if *last != -1 {
  1043. v.Set("limit", strconv.Itoa(*last))
  1044. }
  1045. if *since != "" {
  1046. v.Set("since", *since)
  1047. }
  1048. if *before != "" {
  1049. v.Set("before", *before)
  1050. }
  1051. if *size {
  1052. v.Set("size", "1")
  1053. }
  1054. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  1055. if err != nil {
  1056. return err
  1057. }
  1058. var outs []APIContainers
  1059. err = json.Unmarshal(body, &outs)
  1060. if err != nil {
  1061. return err
  1062. }
  1063. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1064. if !*quiet {
  1065. fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1066. if *size {
  1067. fmt.Fprintln(w, "\tSIZE")
  1068. } else {
  1069. fmt.Fprint(w, "\n")
  1070. }
  1071. }
  1072. for _, out := range outs {
  1073. if !*noTrunc {
  1074. out.ID = utils.TruncateID(out.ID)
  1075. }
  1076. // Remove the leading / from the names
  1077. for i := 0; i < len(out.Names); i++ {
  1078. out.Names[i] = out.Names[i][1:]
  1079. }
  1080. if !*quiet {
  1081. if !*noTrunc {
  1082. out.Command = utils.Trunc(out.Command, 20)
  1083. }
  1084. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\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, ","))
  1085. if *size {
  1086. if out.SizeRootFs > 0 {
  1087. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  1088. } else {
  1089. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1090. }
  1091. } else {
  1092. fmt.Fprint(w, "\n")
  1093. }
  1094. } else {
  1095. fmt.Fprintln(w, out.ID)
  1096. }
  1097. }
  1098. if !*quiet {
  1099. w.Flush()
  1100. }
  1101. return nil
  1102. }
  1103. func (cli *DockerCli) CmdCommit(args ...string) error {
  1104. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY [TAG]]", "Create a new image from a container's changes")
  1105. flComment := cmd.String("m", "", "Commit message")
  1106. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1107. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1108. if err := cmd.Parse(args); err != nil {
  1109. return nil
  1110. }
  1111. name, repository, tag := cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1112. if name == "" {
  1113. cmd.Usage()
  1114. return nil
  1115. }
  1116. v := url.Values{}
  1117. v.Set("container", name)
  1118. v.Set("repo", repository)
  1119. v.Set("tag", tag)
  1120. v.Set("comment", *flComment)
  1121. v.Set("author", *flAuthor)
  1122. var config *Config
  1123. if *flConfig != "" {
  1124. config = &Config{}
  1125. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1126. return err
  1127. }
  1128. }
  1129. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1130. if err != nil {
  1131. return err
  1132. }
  1133. apiID := &APIID{}
  1134. err = json.Unmarshal(body, apiID)
  1135. if err != nil {
  1136. return err
  1137. }
  1138. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1139. return nil
  1140. }
  1141. func (cli *DockerCli) CmdEvents(args ...string) error {
  1142. cmd := Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1143. since := cmd.String("since", "", "Show events previously created (used for polling).")
  1144. if err := cmd.Parse(args); err != nil {
  1145. return nil
  1146. }
  1147. if cmd.NArg() != 0 {
  1148. cmd.Usage()
  1149. return nil
  1150. }
  1151. v := url.Values{}
  1152. if *since != "" {
  1153. v.Set("since", *since)
  1154. }
  1155. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1156. return err
  1157. }
  1158. return nil
  1159. }
  1160. func (cli *DockerCli) CmdExport(args ...string) error {
  1161. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  1162. if err := cmd.Parse(args); err != nil {
  1163. return nil
  1164. }
  1165. if cmd.NArg() != 1 {
  1166. cmd.Usage()
  1167. return nil
  1168. }
  1169. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1170. return err
  1171. }
  1172. return nil
  1173. }
  1174. func (cli *DockerCli) CmdDiff(args ...string) error {
  1175. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1176. if err := cmd.Parse(args); err != nil {
  1177. return nil
  1178. }
  1179. if cmd.NArg() != 1 {
  1180. cmd.Usage()
  1181. return nil
  1182. }
  1183. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1184. if err != nil {
  1185. return err
  1186. }
  1187. changes := []Change{}
  1188. err = json.Unmarshal(body, &changes)
  1189. if err != nil {
  1190. return err
  1191. }
  1192. for _, change := range changes {
  1193. fmt.Fprintf(cli.out, "%s\n", change.String())
  1194. }
  1195. return nil
  1196. }
  1197. func (cli *DockerCli) CmdLogs(args ...string) error {
  1198. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1199. if err := cmd.Parse(args); err != nil {
  1200. return nil
  1201. }
  1202. if cmd.NArg() != 1 {
  1203. cmd.Usage()
  1204. return nil
  1205. }
  1206. name := cmd.Arg(0)
  1207. if err := cli.hijack("POST", "/containers/"+name+"/attach?logs=1&stdout=1&stderr=1", false, nil, cli.out, cli.err, nil); err != nil {
  1208. return err
  1209. }
  1210. return nil
  1211. }
  1212. func (cli *DockerCli) CmdAttach(args ...string) error {
  1213. cmd := Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1214. noStdin := cmd.Bool("nostdin", false, "Do not attach stdin")
  1215. proxy := cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1216. if err := cmd.Parse(args); err != nil {
  1217. return nil
  1218. }
  1219. if cmd.NArg() != 1 {
  1220. cmd.Usage()
  1221. return nil
  1222. }
  1223. name := cmd.Arg(0)
  1224. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1225. if err != nil {
  1226. return err
  1227. }
  1228. container := &Container{}
  1229. err = json.Unmarshal(body, container)
  1230. if err != nil {
  1231. return err
  1232. }
  1233. if !container.State.Running {
  1234. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1235. }
  1236. if container.Config.Tty && cli.isTerminal {
  1237. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1238. utils.Debugf("Error monitoring TTY size: %s", err)
  1239. }
  1240. }
  1241. var in io.ReadCloser
  1242. v := url.Values{}
  1243. v.Set("stream", "1")
  1244. if !*noStdin && container.Config.OpenStdin {
  1245. v.Set("stdin", "1")
  1246. in = cli.in
  1247. }
  1248. v.Set("stdout", "1")
  1249. v.Set("stderr", "1")
  1250. if *proxy && !container.Config.Tty {
  1251. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1252. defer utils.StopCatch(sigc)
  1253. }
  1254. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1255. return err
  1256. }
  1257. return nil
  1258. }
  1259. func (cli *DockerCli) CmdSearch(args ...string) error {
  1260. cmd := Subcmd("search", "NAME", "Search the docker index for images")
  1261. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1262. if err := cmd.Parse(args); err != nil {
  1263. return nil
  1264. }
  1265. if cmd.NArg() != 1 {
  1266. cmd.Usage()
  1267. return nil
  1268. }
  1269. v := url.Values{}
  1270. v.Set("term", cmd.Arg(0))
  1271. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1272. if err != nil {
  1273. return err
  1274. }
  1275. outs := []APISearch{}
  1276. err = json.Unmarshal(body, &outs)
  1277. if err != nil {
  1278. return err
  1279. }
  1280. fmt.Fprintf(cli.out, "Found %d results matching your query (\"%s\")\n", len(outs), cmd.Arg(0))
  1281. w := tabwriter.NewWriter(cli.out, 33, 1, 3, ' ', 0)
  1282. fmt.Fprintf(w, "NAME\tDESCRIPTION\n")
  1283. _, width := cli.getTtySize()
  1284. if width == 0 {
  1285. width = 45
  1286. } else {
  1287. width = width - 33 //remote the first column
  1288. }
  1289. for _, out := range outs {
  1290. desc := strings.Replace(out.Description, "\n", " ", -1)
  1291. desc = strings.Replace(desc, "\r", " ", -1)
  1292. if !*noTrunc && len(desc) > width {
  1293. desc = utils.Trunc(desc, width-3) + "..."
  1294. }
  1295. fmt.Fprintf(w, "%s\t%s\n", out.Name, desc)
  1296. }
  1297. w.Flush()
  1298. return nil
  1299. }
  1300. // Ports type - Used to parse multiple -p flags
  1301. type ports []int
  1302. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1303. type AttachOpts map[string]bool
  1304. func NewAttachOpts() AttachOpts {
  1305. return make(AttachOpts)
  1306. }
  1307. func (opts AttachOpts) String() string {
  1308. // Cast to underlying map type to avoid infinite recursion
  1309. return fmt.Sprintf("%v", map[string]bool(opts))
  1310. }
  1311. func (opts AttachOpts) Set(val string) error {
  1312. if val != "stdin" && val != "stdout" && val != "stderr" {
  1313. return fmt.Errorf("Unsupported stream name: %s", val)
  1314. }
  1315. opts[val] = true
  1316. return nil
  1317. }
  1318. func (opts AttachOpts) Get(val string) bool {
  1319. if res, exists := opts[val]; exists {
  1320. return res
  1321. }
  1322. return false
  1323. }
  1324. // PathOpts stores a unique set of absolute paths
  1325. type PathOpts map[string]struct{}
  1326. func NewPathOpts() PathOpts {
  1327. return make(PathOpts)
  1328. }
  1329. func (opts PathOpts) String() string {
  1330. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1331. }
  1332. func (opts PathOpts) Set(val string) error {
  1333. var containerPath string
  1334. splited := strings.SplitN(val, ":", 2)
  1335. if len(splited) == 1 {
  1336. containerPath = splited[0]
  1337. val = filepath.Clean(splited[0])
  1338. } else {
  1339. containerPath = splited[1]
  1340. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1341. }
  1342. if !filepath.IsAbs(containerPath) {
  1343. utils.Debugf("%s is not an absolute path", containerPath)
  1344. return fmt.Errorf("%s is not an absolute path", containerPath)
  1345. }
  1346. opts[val] = struct{}{}
  1347. return nil
  1348. }
  1349. func (cli *DockerCli) CmdTag(args ...string) error {
  1350. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
  1351. force := cmd.Bool("f", false, "Force")
  1352. if err := cmd.Parse(args); err != nil {
  1353. return nil
  1354. }
  1355. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1356. cmd.Usage()
  1357. return nil
  1358. }
  1359. v := url.Values{}
  1360. v.Set("repo", cmd.Arg(1))
  1361. if cmd.NArg() == 3 {
  1362. v.Set("tag", cmd.Arg(2))
  1363. }
  1364. if *force {
  1365. v.Set("force", "1")
  1366. }
  1367. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1368. return err
  1369. }
  1370. return nil
  1371. }
  1372. func (cli *DockerCli) CmdRun(args ...string) error {
  1373. config, hostConfig, cmd, err := ParseRun(args, nil)
  1374. if err != nil {
  1375. return err
  1376. }
  1377. if config.Image == "" {
  1378. cmd.Usage()
  1379. return nil
  1380. }
  1381. flRm := cmd.Lookup("rm")
  1382. autoRemove, _ := strconv.ParseBool(flRm.Value.String())
  1383. flSigProxy := cmd.Lookup("sig-proxy")
  1384. sigProxy, _ := strconv.ParseBool(flSigProxy.Value.String())
  1385. flName := cmd.Lookup("name")
  1386. if config.Tty {
  1387. sigProxy = false
  1388. }
  1389. var containerIDFile *os.File
  1390. if len(hostConfig.ContainerIDFile) > 0 {
  1391. if _, err := ioutil.ReadFile(hostConfig.ContainerIDFile); err == nil {
  1392. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1393. }
  1394. containerIDFile, err = os.Create(hostConfig.ContainerIDFile)
  1395. if err != nil {
  1396. return fmt.Errorf("failed to create the container ID file: %s", err)
  1397. }
  1398. defer containerIDFile.Close()
  1399. }
  1400. containerValues := url.Values{}
  1401. name := flName.Value.String()
  1402. if name != "" {
  1403. containerValues.Set("name", name)
  1404. }
  1405. //create the container
  1406. body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1407. //if image not found try to pull it
  1408. if statusCode == 404 {
  1409. _, tag := utils.ParseRepositoryTag(config.Image)
  1410. if tag == "" {
  1411. tag = DEFAULTTAG
  1412. }
  1413. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1414. v := url.Values{}
  1415. repos, tag := utils.ParseRepositoryTag(config.Image)
  1416. v.Set("fromImage", repos)
  1417. v.Set("tag", tag)
  1418. // Resolve the Repository name from fqn to endpoint + name
  1419. var endpoint string
  1420. endpoint, _, err = registry.ResolveRepositoryName(repos)
  1421. if err != nil {
  1422. return err
  1423. }
  1424. // Load the auth config file, to be able to pull the image
  1425. cli.LoadConfigFile()
  1426. // Resolve the Auth config relevant for this server
  1427. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1428. buf, err := json.Marshal(authConfig)
  1429. if err != nil {
  1430. return err
  1431. }
  1432. registryAuthHeader := []string{
  1433. base64.URLEncoding.EncodeToString(buf),
  1434. }
  1435. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{
  1436. "X-Registry-Auth": registryAuthHeader,
  1437. })
  1438. if err != nil {
  1439. return err
  1440. }
  1441. body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1442. if err != nil {
  1443. return err
  1444. }
  1445. }
  1446. if err != nil {
  1447. return err
  1448. }
  1449. runResult := &APIRun{}
  1450. err = json.Unmarshal(body, runResult)
  1451. if err != nil {
  1452. return err
  1453. }
  1454. for _, warning := range runResult.Warnings {
  1455. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1456. }
  1457. if len(hostConfig.ContainerIDFile) > 0 {
  1458. if _, err = containerIDFile.WriteString(runResult.ID); err != nil {
  1459. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1460. }
  1461. }
  1462. if sigProxy {
  1463. sigc := cli.forwardAllSignals(runResult.ID)
  1464. defer utils.StopCatch(sigc)
  1465. }
  1466. var (
  1467. wait chan struct{}
  1468. errCh chan error
  1469. )
  1470. if !config.AttachStdout && !config.AttachStderr {
  1471. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1472. wait = make(chan struct{})
  1473. go func() {
  1474. defer close(wait)
  1475. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1476. }()
  1477. }
  1478. hijacked := make(chan bool)
  1479. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1480. v := url.Values{}
  1481. v.Set("stream", "1")
  1482. var out, stderr io.Writer
  1483. var in io.ReadCloser
  1484. if config.AttachStdin {
  1485. v.Set("stdin", "1")
  1486. in = cli.in
  1487. }
  1488. if config.AttachStdout {
  1489. v.Set("stdout", "1")
  1490. out = cli.out
  1491. }
  1492. if config.AttachStderr {
  1493. v.Set("stderr", "1")
  1494. if config.Tty {
  1495. stderr = cli.out
  1496. } else {
  1497. stderr = cli.err
  1498. }
  1499. }
  1500. errCh = utils.Go(func() error {
  1501. return cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1502. })
  1503. } else {
  1504. close(hijacked)
  1505. }
  1506. // Acknowledge the hijack before starting
  1507. select {
  1508. case <-hijacked:
  1509. case err := <-errCh:
  1510. if err != nil {
  1511. utils.Debugf("Error hijack: %s", err)
  1512. return err
  1513. }
  1514. }
  1515. //start the container
  1516. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1517. return err
  1518. }
  1519. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1520. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1521. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1522. }
  1523. }
  1524. if errCh != nil {
  1525. if err := <-errCh; err != nil {
  1526. utils.Debugf("Error hijack: %s", err)
  1527. return err
  1528. }
  1529. }
  1530. if !config.AttachStdout && !config.AttachStderr {
  1531. // Detached mode
  1532. <-wait
  1533. } else {
  1534. running, status, err := getExitCode(cli, runResult.ID)
  1535. if err != nil {
  1536. return err
  1537. }
  1538. if autoRemove {
  1539. if running {
  1540. return fmt.Errorf("Impossible to auto-remove a detached container")
  1541. }
  1542. // Wait for the process to
  1543. if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
  1544. return err
  1545. }
  1546. if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
  1547. return err
  1548. }
  1549. }
  1550. if status != 0 {
  1551. return &utils.StatusError{Status: status}
  1552. }
  1553. }
  1554. return nil
  1555. }
  1556. func (cli *DockerCli) CmdCp(args ...string) error {
  1557. cmd := Subcmd("cp", "CONTAINER:RESOURCE HOSTPATH", "Copy files/folders from the RESOURCE to the HOSTPATH")
  1558. if err := cmd.Parse(args); err != nil {
  1559. return nil
  1560. }
  1561. if cmd.NArg() != 2 {
  1562. cmd.Usage()
  1563. return nil
  1564. }
  1565. var copyData APICopy
  1566. info := strings.Split(cmd.Arg(0), ":")
  1567. if len(info) != 2 {
  1568. return fmt.Errorf("Error: Resource not specified")
  1569. }
  1570. copyData.Resource = info[1]
  1571. copyData.HostPath = cmd.Arg(1)
  1572. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1573. if err != nil {
  1574. return err
  1575. }
  1576. if statusCode == 200 {
  1577. r := bytes.NewReader(data)
  1578. if err := archive.Untar(r, copyData.HostPath); err != nil {
  1579. return err
  1580. }
  1581. }
  1582. return nil
  1583. }
  1584. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1585. var params io.Reader
  1586. if data != nil {
  1587. buf, err := json.Marshal(data)
  1588. if err != nil {
  1589. return nil, -1, err
  1590. }
  1591. params = bytes.NewBuffer(buf)
  1592. }
  1593. // fixme: refactor client to support redirect
  1594. re := regexp.MustCompile("/+")
  1595. path = re.ReplaceAllString(path, "/")
  1596. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1597. if err != nil {
  1598. return nil, -1, err
  1599. }
  1600. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1601. req.Host = cli.addr
  1602. if data != nil {
  1603. req.Header.Set("Content-Type", "application/json")
  1604. } else if method == "POST" {
  1605. req.Header.Set("Content-Type", "plain/text")
  1606. }
  1607. dial, err := net.Dial(cli.proto, cli.addr)
  1608. if err != nil {
  1609. if strings.Contains(err.Error(), "connection refused") {
  1610. return nil, -1, ErrConnectionRefused
  1611. }
  1612. return nil, -1, err
  1613. }
  1614. clientconn := httputil.NewClientConn(dial, nil)
  1615. resp, err := clientconn.Do(req)
  1616. defer clientconn.Close()
  1617. if err != nil {
  1618. if strings.Contains(err.Error(), "connection refused") {
  1619. return nil, -1, ErrConnectionRefused
  1620. }
  1621. return nil, -1, err
  1622. }
  1623. defer resp.Body.Close()
  1624. body, err := ioutil.ReadAll(resp.Body)
  1625. if err != nil {
  1626. return nil, -1, err
  1627. }
  1628. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1629. if len(body) == 0 {
  1630. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1631. }
  1632. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1633. }
  1634. return body, resp.StatusCode, nil
  1635. }
  1636. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1637. if (method == "POST" || method == "PUT") && in == nil {
  1638. in = bytes.NewReader([]byte{})
  1639. }
  1640. // fixme: refactor client to support redirect
  1641. re := regexp.MustCompile("/+")
  1642. path = re.ReplaceAllString(path, "/")
  1643. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1644. if err != nil {
  1645. return err
  1646. }
  1647. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1648. req.Host = cli.addr
  1649. if method == "POST" {
  1650. req.Header.Set("Content-Type", "plain/text")
  1651. }
  1652. if headers != nil {
  1653. for k, v := range headers {
  1654. req.Header[k] = v
  1655. }
  1656. }
  1657. dial, err := net.Dial(cli.proto, cli.addr)
  1658. if err != nil {
  1659. if strings.Contains(err.Error(), "connection refused") {
  1660. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1661. }
  1662. return err
  1663. }
  1664. clientconn := httputil.NewClientConn(dial, nil)
  1665. resp, err := clientconn.Do(req)
  1666. defer clientconn.Close()
  1667. if err != nil {
  1668. if strings.Contains(err.Error(), "connection refused") {
  1669. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1670. }
  1671. return err
  1672. }
  1673. defer resp.Body.Close()
  1674. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1675. body, err := ioutil.ReadAll(resp.Body)
  1676. if err != nil {
  1677. return err
  1678. }
  1679. if len(body) == 0 {
  1680. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1681. }
  1682. return fmt.Errorf("Error: %s", body)
  1683. }
  1684. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1685. return utils.DisplayJSONMessagesStream(resp.Body, out)
  1686. } else {
  1687. if _, err := io.Copy(out, resp.Body); err != nil {
  1688. return err
  1689. }
  1690. }
  1691. return nil
  1692. }
  1693. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan bool) error {
  1694. // fixme: refactor client to support redirect
  1695. re := regexp.MustCompile("/+")
  1696. path = re.ReplaceAllString(path, "/")
  1697. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1698. if err != nil {
  1699. return err
  1700. }
  1701. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1702. req.Header.Set("Content-Type", "plain/text")
  1703. req.Host = cli.addr
  1704. dial, err := net.Dial(cli.proto, cli.addr)
  1705. if err != nil {
  1706. if strings.Contains(err.Error(), "connection refused") {
  1707. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1708. }
  1709. return err
  1710. }
  1711. clientconn := httputil.NewClientConn(dial, nil)
  1712. defer clientconn.Close()
  1713. // Server hijacks the connection, error 'connection closed' expected
  1714. clientconn.Do(req)
  1715. rwc, br := clientconn.Hijack()
  1716. defer rwc.Close()
  1717. if started != nil {
  1718. started <- true
  1719. }
  1720. var receiveStdout chan error
  1721. if stdout != nil {
  1722. receiveStdout = utils.Go(func() (err error) {
  1723. // When TTY is ON, use regular copy
  1724. if setRawTerminal {
  1725. _, err = io.Copy(stdout, br)
  1726. } else {
  1727. _, err = utils.StdCopy(stdout, stderr, br)
  1728. }
  1729. utils.Debugf("[hijack] End of stdout")
  1730. return err
  1731. })
  1732. }
  1733. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1734. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1735. if err != nil {
  1736. return err
  1737. }
  1738. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1739. }
  1740. sendStdin := utils.Go(func() error {
  1741. if in != nil {
  1742. io.Copy(rwc, in)
  1743. utils.Debugf("[hijack] End of stdin")
  1744. }
  1745. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1746. if err := tcpc.CloseWrite(); err != nil {
  1747. utils.Errorf("Couldn't send EOF: %s\n", err)
  1748. }
  1749. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1750. if err := unixc.CloseWrite(); err != nil {
  1751. utils.Errorf("Couldn't send EOF: %s\n", err)
  1752. }
  1753. }
  1754. // Discard errors due to pipe interruption
  1755. return nil
  1756. })
  1757. if stdout != nil {
  1758. if err := <-receiveStdout; err != nil {
  1759. utils.Errorf("Error receiveStdout: %s", err)
  1760. return err
  1761. }
  1762. }
  1763. if !cli.isTerminal {
  1764. if err := <-sendStdin; err != nil {
  1765. utils.Errorf("Error sendStdin: %s", err)
  1766. return err
  1767. }
  1768. }
  1769. return nil
  1770. }
  1771. func (cli *DockerCli) getTtySize() (int, int) {
  1772. if !cli.isTerminal {
  1773. return 0, 0
  1774. }
  1775. ws, err := term.GetWinsize(cli.terminalFd)
  1776. if err != nil {
  1777. utils.Errorf("Error getting size: %s", err)
  1778. if ws == nil {
  1779. return 0, 0
  1780. }
  1781. }
  1782. return int(ws.Height), int(ws.Width)
  1783. }
  1784. func (cli *DockerCli) resizeTty(id string) {
  1785. height, width := cli.getTtySize()
  1786. if height == 0 && width == 0 {
  1787. return
  1788. }
  1789. v := url.Values{}
  1790. v.Set("h", strconv.Itoa(height))
  1791. v.Set("w", strconv.Itoa(width))
  1792. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1793. utils.Errorf("Error resize: %s", err)
  1794. }
  1795. }
  1796. func (cli *DockerCli) monitorTtySize(id string) error {
  1797. cli.resizeTty(id)
  1798. sigchan := make(chan os.Signal, 1)
  1799. signal.Notify(sigchan, syscall.SIGWINCH)
  1800. go func() {
  1801. for _ = range sigchan {
  1802. cli.resizeTty(id)
  1803. }
  1804. }()
  1805. return nil
  1806. }
  1807. func Subcmd(name, signature, description string) *flag.FlagSet {
  1808. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1809. flags.Usage = func() {
  1810. // FIXME: use custom stdout or return error
  1811. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1812. flags.PrintDefaults()
  1813. }
  1814. return flags
  1815. }
  1816. func (cli *DockerCli) LoadConfigFile() (err error) {
  1817. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  1818. if err != nil {
  1819. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  1820. }
  1821. return err
  1822. }
  1823. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  1824. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  1825. if err != nil {
  1826. // If we can't connect, then the daemon probably died.
  1827. if err != ErrConnectionRefused {
  1828. return -1, err
  1829. }
  1830. return -1, nil
  1831. }
  1832. var out APIWait
  1833. if err := json.Unmarshal(body, &out); err != nil {
  1834. return -1, err
  1835. }
  1836. return out.StatusCode, nil
  1837. }
  1838. // getExitCode perform an inspect on the container. It returns
  1839. // the running state and the exit code.
  1840. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  1841. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  1842. if err != nil {
  1843. // If we can't connect, then the daemon probably died.
  1844. if err != ErrConnectionRefused {
  1845. return false, -1, err
  1846. }
  1847. return false, -1, nil
  1848. }
  1849. c := &Container{}
  1850. if err := json.Unmarshal(body, c); err != nil {
  1851. return false, -1, err
  1852. }
  1853. return c.State.Running, c.State.ExitCode, nil
  1854. }
  1855. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1856. var (
  1857. isTerminal = false
  1858. terminalFd uintptr
  1859. )
  1860. if in != nil {
  1861. if file, ok := in.(*os.File); ok {
  1862. terminalFd = file.Fd()
  1863. isTerminal = term.IsTerminal(terminalFd)
  1864. }
  1865. }
  1866. if err == nil {
  1867. err = out
  1868. }
  1869. return &DockerCli{
  1870. proto: proto,
  1871. addr: addr,
  1872. in: in,
  1873. out: out,
  1874. err: err,
  1875. isTerminal: isTerminal,
  1876. terminalFd: terminalFd,
  1877. }
  1878. }
  1879. type DockerCli struct {
  1880. proto string
  1881. addr string
  1882. configFile *auth.ConfigFile
  1883. in io.ReadCloser
  1884. out io.Writer
  1885. err io.Writer
  1886. isTerminal bool
  1887. terminalFd uintptr
  1888. }