commands.go 53 KB

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