commands.go 53 KB

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