commands.go 59 KB

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