commands.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511
  1. package client
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "path"
  15. "path/filepath"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "syscall"
  20. "text/tabwriter"
  21. "text/template"
  22. "time"
  23. "github.com/docker/docker/api"
  24. "github.com/docker/docker/archive"
  25. "github.com/docker/docker/dockerversion"
  26. "github.com/docker/docker/engine"
  27. "github.com/docker/docker/graph"
  28. "github.com/docker/docker/nat"
  29. "github.com/docker/docker/opts"
  30. "github.com/docker/docker/pkg/log"
  31. flag "github.com/docker/docker/pkg/mflag"
  32. "github.com/docker/docker/pkg/parsers"
  33. "github.com/docker/docker/pkg/parsers/filters"
  34. "github.com/docker/docker/pkg/signal"
  35. "github.com/docker/docker/pkg/term"
  36. "github.com/docker/docker/pkg/timeutils"
  37. "github.com/docker/docker/pkg/units"
  38. "github.com/docker/docker/registry"
  39. "github.com/docker/docker/runconfig"
  40. "github.com/docker/docker/utils"
  41. )
  42. const (
  43. tarHeaderSize = 512
  44. )
  45. func (cli *DockerCli) CmdHelp(args ...string) error {
  46. if len(args) > 1 {
  47. method, exists := cli.getMethod(args[:2]...)
  48. if exists {
  49. method("--help")
  50. return nil
  51. }
  52. }
  53. if len(args) > 0 {
  54. method, exists := cli.getMethod(args[0])
  55. if !exists {
  56. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  57. } else {
  58. method("--help")
  59. return nil
  60. }
  61. }
  62. flag.Usage()
  63. return nil
  64. }
  65. func (cli *DockerCli) CmdBuild(args ...string) error {
  66. cmd := cli.Subcmd("build", "PATH | URL | -", "Build a new image from the source code at PATH")
  67. tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) to be applied to the resulting image in case of success")
  68. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
  69. noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image")
  70. rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build")
  71. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers, even after unsuccessful builds")
  72. if err := cmd.Parse(args); err != nil {
  73. return nil
  74. }
  75. if cmd.NArg() != 1 {
  76. cmd.Usage()
  77. return nil
  78. }
  79. var (
  80. context archive.Archive
  81. isRemote bool
  82. err error
  83. )
  84. _, err = exec.LookPath("git")
  85. hasGit := err == nil
  86. if cmd.Arg(0) == "-" {
  87. // As a special case, 'docker build -' will build from either an empty context with the
  88. // contents of stdin as a Dockerfile, or a tar-ed context from stdin.
  89. buf := bufio.NewReader(cli.in)
  90. magic, err := buf.Peek(tarHeaderSize)
  91. if err != nil && err != io.EOF {
  92. return fmt.Errorf("failed to peek context header from STDIN: %v", err)
  93. }
  94. if !archive.IsArchive(magic) {
  95. dockerfile, err := ioutil.ReadAll(buf)
  96. if err != nil {
  97. return fmt.Errorf("failed to read Dockerfile from STDIN: %v", err)
  98. }
  99. context, err = archive.Generate("Dockerfile", string(dockerfile))
  100. } else {
  101. context = ioutil.NopCloser(buf)
  102. }
  103. } else if utils.IsURL(cmd.Arg(0)) && (!utils.IsGIT(cmd.Arg(0)) || !hasGit) {
  104. isRemote = true
  105. } else {
  106. root := cmd.Arg(0)
  107. if utils.IsGIT(root) {
  108. remoteURL := cmd.Arg(0)
  109. if !strings.HasPrefix(remoteURL, "git://") && !strings.HasPrefix(remoteURL, "git@") && !utils.IsURL(remoteURL) {
  110. remoteURL = "https://" + remoteURL
  111. }
  112. root, err = ioutil.TempDir("", "docker-build-git")
  113. if err != nil {
  114. return err
  115. }
  116. defer os.RemoveAll(root)
  117. if output, err := exec.Command("git", "clone", "--recursive", remoteURL, root).CombinedOutput(); err != nil {
  118. return fmt.Errorf("Error trying to use git: %s (%s)", err, output)
  119. }
  120. }
  121. if _, err := os.Stat(root); err != nil {
  122. return err
  123. }
  124. filename := path.Join(root, "Dockerfile")
  125. if _, err = os.Stat(filename); os.IsNotExist(err) {
  126. return fmt.Errorf("no Dockerfile found in %s", cmd.Arg(0))
  127. }
  128. var excludes []string
  129. ignore, err := ioutil.ReadFile(path.Join(root, ".dockerignore"))
  130. if err != nil && !os.IsNotExist(err) {
  131. return fmt.Errorf("Error reading .dockerignore: '%s'", err)
  132. }
  133. for _, pattern := range strings.Split(string(ignore), "\n") {
  134. ok, err := filepath.Match(pattern, "Dockerfile")
  135. if err != nil {
  136. return fmt.Errorf("Bad .dockerignore pattern: '%s', error: %s", pattern, err)
  137. }
  138. if ok {
  139. return fmt.Errorf("Dockerfile was excluded by .dockerignore pattern '%s'", pattern)
  140. }
  141. excludes = append(excludes, pattern)
  142. }
  143. if err = utils.ValidateContextDirectory(root, excludes); err != nil {
  144. return fmt.Errorf("Error checking context is accessible: '%s'. Please check permissions and try again.", err)
  145. }
  146. options := &archive.TarOptions{
  147. Compression: archive.Uncompressed,
  148. Excludes: excludes,
  149. }
  150. context, err = archive.TarWithOptions(root, options)
  151. if err != nil {
  152. return err
  153. }
  154. }
  155. var body io.Reader
  156. // Setup an upload progress bar
  157. // FIXME: ProgressReader shouldn't be this annoying to use
  158. if context != nil {
  159. sf := utils.NewStreamFormatter(false)
  160. body = utils.ProgressReader(context, 0, cli.err, sf, true, "", "Sending build context to Docker daemon")
  161. }
  162. // Send the build context
  163. v := &url.Values{}
  164. //Check if the given image name can be resolved
  165. if *tag != "" {
  166. repository, tag := parsers.ParseRepositoryTag(*tag)
  167. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  168. return err
  169. }
  170. if len(tag) > 0 {
  171. if err := graph.ValidateTagName(tag); err != nil {
  172. return err
  173. }
  174. }
  175. }
  176. v.Set("t", *tag)
  177. if *suppressOutput {
  178. v.Set("q", "1")
  179. }
  180. if isRemote {
  181. v.Set("remote", cmd.Arg(0))
  182. }
  183. if *noCache {
  184. v.Set("nocache", "1")
  185. }
  186. if *rm {
  187. v.Set("rm", "1")
  188. } else {
  189. v.Set("rm", "0")
  190. }
  191. if *forceRm {
  192. v.Set("forcerm", "1")
  193. }
  194. cli.LoadConfigFile()
  195. headers := http.Header(make(map[string][]string))
  196. buf, err := json.Marshal(cli.configFile)
  197. if err != nil {
  198. return err
  199. }
  200. headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf))
  201. if context != nil {
  202. headers.Set("Content-Type", "application/tar")
  203. }
  204. err = cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), body, cli.out, headers)
  205. if jerr, ok := err.(*utils.JSONError); ok {
  206. // If no error code is set, default to 1
  207. if jerr.Code == 0 {
  208. jerr.Code = 1
  209. }
  210. return &utils.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  211. }
  212. return err
  213. }
  214. // 'docker login': login / register a user to registry service.
  215. func (cli *DockerCli) CmdLogin(args ...string) error {
  216. cmd := cli.Subcmd("login", "[SERVER]", "Register or log in to a Docker registry server, if no server is specified \""+registry.IndexServerAddress()+"\" is the default.")
  217. var username, password, email string
  218. cmd.StringVar(&username, []string{"u", "-username"}, "", "Username")
  219. cmd.StringVar(&password, []string{"p", "-password"}, "", "Password")
  220. cmd.StringVar(&email, []string{"e", "-email"}, "", "Email")
  221. err := cmd.Parse(args)
  222. if err != nil {
  223. return nil
  224. }
  225. serverAddress := registry.IndexServerAddress()
  226. if len(cmd.Args()) > 0 {
  227. serverAddress = cmd.Arg(0)
  228. }
  229. promptDefault := func(prompt string, configDefault string) {
  230. if configDefault == "" {
  231. fmt.Fprintf(cli.out, "%s: ", prompt)
  232. } else {
  233. fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault)
  234. }
  235. }
  236. readInput := func(in io.Reader, out io.Writer) string {
  237. reader := bufio.NewReader(in)
  238. line, _, err := reader.ReadLine()
  239. if err != nil {
  240. fmt.Fprintln(out, err.Error())
  241. os.Exit(1)
  242. }
  243. return string(line)
  244. }
  245. cli.LoadConfigFile()
  246. authconfig, ok := cli.configFile.Configs[serverAddress]
  247. if !ok {
  248. authconfig = registry.AuthConfig{}
  249. }
  250. if username == "" {
  251. promptDefault("Username", authconfig.Username)
  252. username = readInput(cli.in, cli.out)
  253. if username == "" {
  254. username = authconfig.Username
  255. }
  256. }
  257. // Assume that a different username means they may not want to use
  258. // the password or email from the config file, so prompt them
  259. if username != authconfig.Username {
  260. if password == "" {
  261. oldState, _ := term.SaveState(cli.inFd)
  262. fmt.Fprintf(cli.out, "Password: ")
  263. term.DisableEcho(cli.inFd, oldState)
  264. password = readInput(cli.in, cli.out)
  265. fmt.Fprint(cli.out, "\n")
  266. term.RestoreTerminal(cli.inFd, oldState)
  267. if password == "" {
  268. return fmt.Errorf("Error : Password Required")
  269. }
  270. }
  271. if email == "" {
  272. promptDefault("Email", authconfig.Email)
  273. email = readInput(cli.in, cli.out)
  274. if email == "" {
  275. email = authconfig.Email
  276. }
  277. }
  278. } else {
  279. // However, if they don't override the username use the
  280. // password or email from the cmd line if specified. IOW, allow
  281. // then to change/overide them. And if not specified, just
  282. // use what's in the config file
  283. if password == "" {
  284. password = authconfig.Password
  285. }
  286. if email == "" {
  287. email = authconfig.Email
  288. }
  289. }
  290. authconfig.Username = username
  291. authconfig.Password = password
  292. authconfig.Email = email
  293. authconfig.ServerAddress = serverAddress
  294. cli.configFile.Configs[serverAddress] = authconfig
  295. stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], false)
  296. if statusCode == 401 {
  297. delete(cli.configFile.Configs, serverAddress)
  298. registry.SaveConfig(cli.configFile)
  299. return err
  300. }
  301. if err != nil {
  302. return err
  303. }
  304. var out2 engine.Env
  305. err = out2.Decode(stream)
  306. if err != nil {
  307. cli.configFile, _ = registry.LoadConfig(os.Getenv("HOME"))
  308. return err
  309. }
  310. registry.SaveConfig(cli.configFile)
  311. if out2.Get("Status") != "" {
  312. fmt.Fprintf(cli.out, "%s\n", out2.Get("Status"))
  313. }
  314. return nil
  315. }
  316. // log out from a Docker registry
  317. func (cli *DockerCli) CmdLogout(args ...string) error {
  318. cmd := cli.Subcmd("logout", "[SERVER]", "Log out from a Docker registry, if no server is specified \""+registry.IndexServerAddress()+"\" is the default.")
  319. if err := cmd.Parse(args); err != nil {
  320. return nil
  321. }
  322. serverAddress := registry.IndexServerAddress()
  323. if len(cmd.Args()) > 0 {
  324. serverAddress = cmd.Arg(0)
  325. }
  326. cli.LoadConfigFile()
  327. if _, ok := cli.configFile.Configs[serverAddress]; !ok {
  328. fmt.Fprintf(cli.out, "Not logged in to %s\n", serverAddress)
  329. } else {
  330. fmt.Fprintf(cli.out, "Remove login credentials for %s\n", serverAddress)
  331. delete(cli.configFile.Configs, serverAddress)
  332. if err := registry.SaveConfig(cli.configFile); err != nil {
  333. return fmt.Errorf("Failed to save docker config: %v", err)
  334. }
  335. }
  336. return nil
  337. }
  338. // 'docker wait': block until a container stops
  339. func (cli *DockerCli) CmdWait(args ...string) error {
  340. cmd := cli.Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  341. if err := cmd.Parse(args); err != nil {
  342. return nil
  343. }
  344. if cmd.NArg() < 1 {
  345. cmd.Usage()
  346. return nil
  347. }
  348. var encounteredError error
  349. for _, name := range cmd.Args() {
  350. status, err := waitForExit(cli, name)
  351. if err != nil {
  352. fmt.Fprintf(cli.err, "%s\n", err)
  353. encounteredError = fmt.Errorf("Error: failed to wait one or more containers")
  354. } else {
  355. fmt.Fprintf(cli.out, "%d\n", status)
  356. }
  357. }
  358. return encounteredError
  359. }
  360. // 'docker version': show version information
  361. func (cli *DockerCli) CmdVersion(args ...string) error {
  362. cmd := cli.Subcmd("version", "", "Show the Docker version information.")
  363. if err := cmd.Parse(args); err != nil {
  364. return nil
  365. }
  366. if cmd.NArg() > 0 {
  367. cmd.Usage()
  368. return nil
  369. }
  370. if dockerversion.VERSION != "" {
  371. fmt.Fprintf(cli.out, "Client version: %s\n", dockerversion.VERSION)
  372. }
  373. fmt.Fprintf(cli.out, "Client API version: %s\n", api.APIVERSION)
  374. fmt.Fprintf(cli.out, "Go version (client): %s\n", runtime.Version())
  375. if dockerversion.GITCOMMIT != "" {
  376. fmt.Fprintf(cli.out, "Git commit (client): %s\n", dockerversion.GITCOMMIT)
  377. }
  378. fmt.Fprintf(cli.out, "OS/Arch (client): %s/%s\n", runtime.GOOS, runtime.GOARCH)
  379. body, _, err := readBody(cli.call("GET", "/version", nil, false))
  380. if err != nil {
  381. return err
  382. }
  383. out := engine.NewOutput()
  384. remoteVersion, err := out.AddEnv()
  385. if err != nil {
  386. log.Errorf("Error reading remote version: %s", err)
  387. return err
  388. }
  389. if _, err := out.Write(body); err != nil {
  390. log.Errorf("Error reading remote version: %s", err)
  391. return err
  392. }
  393. out.Close()
  394. fmt.Fprintf(cli.out, "Server version: %s\n", remoteVersion.Get("Version"))
  395. if apiVersion := remoteVersion.Get("ApiVersion"); apiVersion != "" {
  396. fmt.Fprintf(cli.out, "Server API version: %s\n", apiVersion)
  397. }
  398. fmt.Fprintf(cli.out, "Go version (server): %s\n", remoteVersion.Get("GoVersion"))
  399. fmt.Fprintf(cli.out, "Git commit (server): %s\n", remoteVersion.Get("GitCommit"))
  400. return nil
  401. }
  402. // 'docker info': display system-wide information.
  403. func (cli *DockerCli) CmdInfo(args ...string) error {
  404. cmd := cli.Subcmd("info", "", "Display system-wide information")
  405. if err := cmd.Parse(args); err != nil {
  406. return nil
  407. }
  408. if cmd.NArg() > 0 {
  409. cmd.Usage()
  410. return nil
  411. }
  412. body, _, err := readBody(cli.call("GET", "/info", nil, false))
  413. if err != nil {
  414. return err
  415. }
  416. out := engine.NewOutput()
  417. remoteInfo, err := out.AddEnv()
  418. if err != nil {
  419. return err
  420. }
  421. if _, err := out.Write(body); err != nil {
  422. log.Errorf("Error reading remote info: %s", err)
  423. return err
  424. }
  425. out.Close()
  426. fmt.Fprintf(cli.out, "Containers: %d\n", remoteInfo.GetInt("Containers"))
  427. fmt.Fprintf(cli.out, "Images: %d\n", remoteInfo.GetInt("Images"))
  428. fmt.Fprintf(cli.out, "Storage Driver: %s\n", remoteInfo.Get("Driver"))
  429. var driverStatus [][2]string
  430. if err := remoteInfo.GetJson("DriverStatus", &driverStatus); err != nil {
  431. return err
  432. }
  433. for _, pair := range driverStatus {
  434. fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1])
  435. }
  436. fmt.Fprintf(cli.out, "Execution Driver: %s\n", remoteInfo.Get("ExecutionDriver"))
  437. fmt.Fprintf(cli.out, "Kernel Version: %s\n", remoteInfo.Get("KernelVersion"))
  438. fmt.Fprintf(cli.out, "Operating System: %s\n", remoteInfo.Get("OperatingSystem"))
  439. if remoteInfo.GetBool("Debug") || os.Getenv("DEBUG") != "" {
  440. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", remoteInfo.GetBool("Debug"))
  441. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  442. fmt.Fprintf(cli.out, "Fds: %d\n", remoteInfo.GetInt("NFd"))
  443. fmt.Fprintf(cli.out, "Goroutines: %d\n", remoteInfo.GetInt("NGoroutines"))
  444. fmt.Fprintf(cli.out, "EventsListeners: %d\n", remoteInfo.GetInt("NEventsListener"))
  445. if initSha1 := remoteInfo.Get("InitSha1"); initSha1 != "" {
  446. fmt.Fprintf(cli.out, "Init SHA1: %s\n", initSha1)
  447. }
  448. if initPath := remoteInfo.Get("InitPath"); initPath != "" {
  449. fmt.Fprintf(cli.out, "Init Path: %s\n", initPath)
  450. }
  451. }
  452. if len(remoteInfo.GetList("IndexServerAddress")) != 0 {
  453. cli.LoadConfigFile()
  454. u := cli.configFile.Configs[remoteInfo.Get("IndexServerAddress")].Username
  455. if len(u) > 0 {
  456. fmt.Fprintf(cli.out, "Username: %v\n", u)
  457. fmt.Fprintf(cli.out, "Registry: %v\n", remoteInfo.GetList("IndexServerAddress"))
  458. }
  459. }
  460. if !remoteInfo.GetBool("MemoryLimit") {
  461. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  462. }
  463. if !remoteInfo.GetBool("SwapLimit") {
  464. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  465. }
  466. if !remoteInfo.GetBool("IPv4Forwarding") {
  467. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  468. }
  469. return nil
  470. }
  471. func (cli *DockerCli) CmdStop(args ...string) error {
  472. cmd := cli.Subcmd("stop", "CONTAINER [CONTAINER...]", "Stop a running container by sending SIGTERM and then SIGKILL after a grace period")
  473. nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.")
  474. if err := cmd.Parse(args); err != nil {
  475. return nil
  476. }
  477. if cmd.NArg() < 1 {
  478. cmd.Usage()
  479. return nil
  480. }
  481. v := url.Values{}
  482. v.Set("t", strconv.Itoa(*nSeconds))
  483. var encounteredError error
  484. for _, name := range cmd.Args() {
  485. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, false))
  486. if err != nil {
  487. fmt.Fprintf(cli.err, "%s\n", err)
  488. encounteredError = fmt.Errorf("Error: failed to stop one or more containers")
  489. } else {
  490. fmt.Fprintf(cli.out, "%s\n", name)
  491. }
  492. }
  493. return encounteredError
  494. }
  495. func (cli *DockerCli) CmdRestart(args ...string) error {
  496. cmd := cli.Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container")
  497. nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.")
  498. if err := cmd.Parse(args); err != nil {
  499. return nil
  500. }
  501. if cmd.NArg() < 1 {
  502. cmd.Usage()
  503. return nil
  504. }
  505. v := url.Values{}
  506. v.Set("t", strconv.Itoa(*nSeconds))
  507. var encounteredError error
  508. for _, name := range cmd.Args() {
  509. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, false))
  510. if err != nil {
  511. fmt.Fprintf(cli.err, "%s\n", err)
  512. encounteredError = fmt.Errorf("Error: failed to restart one or more containers")
  513. } else {
  514. fmt.Fprintf(cli.out, "%s\n", name)
  515. }
  516. }
  517. return encounteredError
  518. }
  519. func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal {
  520. sigc := make(chan os.Signal, 128)
  521. signal.CatchAll(sigc)
  522. go func() {
  523. for s := range sigc {
  524. if s == syscall.SIGCHLD {
  525. continue
  526. }
  527. var sig string
  528. for sigStr, sigN := range signal.SignalMap {
  529. if sigN == s {
  530. sig = sigStr
  531. break
  532. }
  533. }
  534. if sig == "" {
  535. log.Errorf("Unsupported signal: %d. Discarding.", s)
  536. }
  537. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, false)); err != nil {
  538. log.Debugf("Error sending signal: %s", err)
  539. }
  540. }
  541. }()
  542. return sigc
  543. }
  544. func (cli *DockerCli) CmdStart(args ...string) error {
  545. var (
  546. cErr chan error
  547. tty bool
  548. cmd = cli.Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  549. attach = cmd.Bool([]string{"a", "-attach"}, false, "Attach container's STDOUT and STDERR and forward all signals to the process")
  550. openStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Attach container's STDIN")
  551. )
  552. if err := cmd.Parse(args); err != nil {
  553. return nil
  554. }
  555. if cmd.NArg() < 1 {
  556. cmd.Usage()
  557. return nil
  558. }
  559. if *attach || *openStdin {
  560. if cmd.NArg() > 1 {
  561. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  562. }
  563. steam, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  564. if err != nil {
  565. return err
  566. }
  567. env := engine.Env{}
  568. if err := env.Decode(steam); err != nil {
  569. return err
  570. }
  571. config := env.GetSubEnv("Config")
  572. tty = config.GetBool("Tty")
  573. if !tty {
  574. sigc := cli.forwardAllSignals(cmd.Arg(0))
  575. defer signal.StopCatch(sigc)
  576. }
  577. var in io.ReadCloser
  578. v := url.Values{}
  579. v.Set("stream", "1")
  580. if *openStdin && config.GetBool("OpenStdin") {
  581. v.Set("stdin", "1")
  582. in = cli.in
  583. }
  584. v.Set("stdout", "1")
  585. v.Set("stderr", "1")
  586. cErr = utils.Go(func() error {
  587. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil)
  588. })
  589. }
  590. var encounteredError error
  591. for _, name := range cmd.Args() {
  592. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, false))
  593. if err != nil {
  594. if !*attach || !*openStdin {
  595. fmt.Fprintf(cli.err, "%s\n", err)
  596. }
  597. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  598. } else {
  599. if !*attach || !*openStdin {
  600. fmt.Fprintf(cli.out, "%s\n", name)
  601. }
  602. }
  603. }
  604. if encounteredError != nil {
  605. if *openStdin || *attach {
  606. cli.in.Close()
  607. }
  608. return encounteredError
  609. }
  610. if *openStdin || *attach {
  611. if tty && cli.isTerminalOut {
  612. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  613. log.Errorf("Error monitoring TTY size: %s", err)
  614. }
  615. }
  616. return <-cErr
  617. }
  618. return nil
  619. }
  620. func (cli *DockerCli) CmdUnpause(args ...string) error {
  621. cmd := cli.Subcmd("unpause", "CONTAINER", "Unpause all processes within a container")
  622. if err := cmd.Parse(args); err != nil {
  623. return nil
  624. }
  625. if cmd.NArg() != 1 {
  626. cmd.Usage()
  627. return nil
  628. }
  629. var encounteredError error
  630. for _, name := range cmd.Args() {
  631. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, false)); err != nil {
  632. fmt.Fprintf(cli.err, "%s\n", err)
  633. encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name)
  634. } else {
  635. fmt.Fprintf(cli.out, "%s\n", name)
  636. }
  637. }
  638. return encounteredError
  639. }
  640. func (cli *DockerCli) CmdPause(args ...string) error {
  641. cmd := cli.Subcmd("pause", "CONTAINER", "Pause all processes within a container")
  642. if err := cmd.Parse(args); err != nil {
  643. return nil
  644. }
  645. if cmd.NArg() != 1 {
  646. cmd.Usage()
  647. return nil
  648. }
  649. var encounteredError error
  650. for _, name := range cmd.Args() {
  651. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, false)); err != nil {
  652. fmt.Fprintf(cli.err, "%s\n", err)
  653. encounteredError = fmt.Errorf("Error: failed to pause container named %s", name)
  654. } else {
  655. fmt.Fprintf(cli.out, "%s\n", name)
  656. }
  657. }
  658. return encounteredError
  659. }
  660. func (cli *DockerCli) CmdInspect(args ...string) error {
  661. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image")
  662. tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template.")
  663. if err := cmd.Parse(args); err != nil {
  664. return nil
  665. }
  666. if cmd.NArg() < 1 {
  667. cmd.Usage()
  668. return nil
  669. }
  670. var tmpl *template.Template
  671. if *tmplStr != "" {
  672. var err error
  673. if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil {
  674. fmt.Fprintf(cli.err, "Template parsing error: %v\n", err)
  675. return &utils.StatusError{StatusCode: 64,
  676. Status: "Template parsing error: " + err.Error()}
  677. }
  678. }
  679. indented := new(bytes.Buffer)
  680. indented.WriteByte('[')
  681. status := 0
  682. for _, name := range cmd.Args() {
  683. obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  684. if err != nil {
  685. obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, false))
  686. if err != nil {
  687. if strings.Contains(err.Error(), "No such") {
  688. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  689. } else {
  690. fmt.Fprintf(cli.err, "%s", err)
  691. }
  692. status = 1
  693. continue
  694. }
  695. }
  696. if tmpl == nil {
  697. if err = json.Indent(indented, obj, "", " "); err != nil {
  698. fmt.Fprintf(cli.err, "%s\n", err)
  699. status = 1
  700. continue
  701. }
  702. } else {
  703. // Has template, will render
  704. var value interface{}
  705. if err := json.Unmarshal(obj, &value); err != nil {
  706. fmt.Fprintf(cli.err, "%s\n", err)
  707. status = 1
  708. continue
  709. }
  710. if err := tmpl.Execute(cli.out, value); err != nil {
  711. return err
  712. }
  713. cli.out.Write([]byte{'\n'})
  714. }
  715. indented.WriteString(",")
  716. }
  717. if indented.Len() > 1 {
  718. // Remove trailing ','
  719. indented.Truncate(indented.Len() - 1)
  720. }
  721. indented.WriteByte(']')
  722. if tmpl == nil {
  723. if _, err := io.Copy(cli.out, indented); err != nil {
  724. return err
  725. }
  726. }
  727. if status != 0 {
  728. return &utils.StatusError{StatusCode: status}
  729. }
  730. return nil
  731. }
  732. func (cli *DockerCli) CmdTop(args ...string) error {
  733. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Display the running processes of a container")
  734. if err := cmd.Parse(args); err != nil {
  735. return nil
  736. }
  737. if cmd.NArg() == 0 {
  738. cmd.Usage()
  739. return nil
  740. }
  741. val := url.Values{}
  742. if cmd.NArg() > 1 {
  743. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  744. }
  745. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, false)
  746. if err != nil {
  747. return err
  748. }
  749. var procs engine.Env
  750. if err := procs.Decode(stream); err != nil {
  751. return err
  752. }
  753. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  754. fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t"))
  755. processes := [][]string{}
  756. if err := procs.GetJson("Processes", &processes); err != nil {
  757. return err
  758. }
  759. for _, proc := range processes {
  760. fmt.Fprintln(w, strings.Join(proc, "\t"))
  761. }
  762. w.Flush()
  763. return nil
  764. }
  765. func (cli *DockerCli) CmdPort(args ...string) error {
  766. cmd := cli.Subcmd("port", "CONTAINER [PRIVATE_PORT[/PROTO]]", "List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT")
  767. if err := cmd.Parse(args); err != nil {
  768. return nil
  769. }
  770. if cmd.NArg() < 1 {
  771. cmd.Usage()
  772. return nil
  773. }
  774. steam, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  775. if err != nil {
  776. return err
  777. }
  778. env := engine.Env{}
  779. if err := env.Decode(steam); err != nil {
  780. return err
  781. }
  782. ports := nat.PortMap{}
  783. if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil {
  784. return err
  785. }
  786. if cmd.NArg() == 2 {
  787. var (
  788. port = cmd.Arg(1)
  789. proto = "tcp"
  790. parts = strings.SplitN(port, "/", 2)
  791. )
  792. if len(parts) == 2 && len(parts[1]) != 0 {
  793. port = parts[0]
  794. proto = parts[1]
  795. }
  796. natPort := port + "/" + proto
  797. if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
  798. for _, frontend := range frontends {
  799. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  800. }
  801. return nil
  802. }
  803. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
  804. }
  805. for from, frontends := range ports {
  806. for _, frontend := range frontends {
  807. fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
  808. }
  809. }
  810. return nil
  811. }
  812. // 'docker rmi IMAGE' removes all images with the name IMAGE
  813. func (cli *DockerCli) CmdRmi(args ...string) error {
  814. var (
  815. cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  816. force = cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image")
  817. noprune = cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents")
  818. )
  819. if err := cmd.Parse(args); err != nil {
  820. return nil
  821. }
  822. if cmd.NArg() < 1 {
  823. cmd.Usage()
  824. return nil
  825. }
  826. v := url.Values{}
  827. if *force {
  828. v.Set("force", "1")
  829. }
  830. if *noprune {
  831. v.Set("noprune", "1")
  832. }
  833. var encounteredError error
  834. for _, name := range cmd.Args() {
  835. body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
  836. if err != nil {
  837. fmt.Fprintf(cli.err, "%s\n", err)
  838. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  839. } else {
  840. outs := engine.NewTable("Created", 0)
  841. if _, err := outs.ReadListFrom(body); err != nil {
  842. fmt.Fprintf(cli.err, "%s\n", err)
  843. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  844. continue
  845. }
  846. for _, out := range outs.Data {
  847. if out.Get("Deleted") != "" {
  848. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted"))
  849. } else {
  850. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged"))
  851. }
  852. }
  853. }
  854. }
  855. return encounteredError
  856. }
  857. func (cli *DockerCli) CmdHistory(args ...string) error {
  858. cmd := cli.Subcmd("history", "IMAGE", "Show the history of an image")
  859. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  860. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  861. if err := cmd.Parse(args); err != nil {
  862. return nil
  863. }
  864. if cmd.NArg() != 1 {
  865. cmd.Usage()
  866. return nil
  867. }
  868. body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
  869. if err != nil {
  870. return err
  871. }
  872. outs := engine.NewTable("Created", 0)
  873. if _, err := outs.ReadListFrom(body); err != nil {
  874. return err
  875. }
  876. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  877. if !*quiet {
  878. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  879. }
  880. for _, out := range outs.Data {
  881. outID := out.Get("Id")
  882. if !*quiet {
  883. if *noTrunc {
  884. fmt.Fprintf(w, "%s\t", outID)
  885. } else {
  886. fmt.Fprintf(w, "%s\t", utils.TruncateID(outID))
  887. }
  888. fmt.Fprintf(w, "%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))))
  889. if *noTrunc {
  890. fmt.Fprintf(w, "%s\t", out.Get("CreatedBy"))
  891. } else {
  892. fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45))
  893. }
  894. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("Size")))
  895. } else {
  896. if *noTrunc {
  897. fmt.Fprintln(w, outID)
  898. } else {
  899. fmt.Fprintln(w, utils.TruncateID(outID))
  900. }
  901. }
  902. }
  903. w.Flush()
  904. return nil
  905. }
  906. func (cli *DockerCli) CmdRm(args ...string) error {
  907. cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers")
  908. v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container")
  909. link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link and not the underlying container")
  910. force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)")
  911. if err := cmd.Parse(args); err != nil {
  912. return nil
  913. }
  914. if cmd.NArg() < 1 {
  915. cmd.Usage()
  916. return nil
  917. }
  918. val := url.Values{}
  919. if *v {
  920. val.Set("v", "1")
  921. }
  922. if *link {
  923. val.Set("link", "1")
  924. }
  925. if *force {
  926. val.Set("force", "1")
  927. }
  928. var encounteredError error
  929. for _, name := range cmd.Args() {
  930. _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false))
  931. if err != nil {
  932. fmt.Fprintf(cli.err, "%s\n", err)
  933. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  934. } else {
  935. fmt.Fprintf(cli.out, "%s\n", name)
  936. }
  937. }
  938. return encounteredError
  939. }
  940. // 'docker kill NAME' kills a running container
  941. func (cli *DockerCli) CmdKill(args ...string) error {
  942. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container using SIGKILL or a specified signal")
  943. signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container")
  944. if err := cmd.Parse(args); err != nil {
  945. return nil
  946. }
  947. if cmd.NArg() < 1 {
  948. cmd.Usage()
  949. return nil
  950. }
  951. var encounteredError error
  952. for _, name := range cmd.Args() {
  953. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil {
  954. fmt.Fprintf(cli.err, "%s\n", err)
  955. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  956. } else {
  957. fmt.Fprintf(cli.out, "%s\n", name)
  958. }
  959. }
  960. return encounteredError
  961. }
  962. func (cli *DockerCli) CmdImport(args ...string) error {
  963. cmd := cli.Subcmd("import", "URL|- [REPOSITORY[:TAG]]", "Create an empty filesystem image and import the contents of the tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then optionally tag it.")
  964. if err := cmd.Parse(args); err != nil {
  965. return nil
  966. }
  967. if cmd.NArg() < 1 {
  968. cmd.Usage()
  969. return nil
  970. }
  971. var (
  972. v = url.Values{}
  973. src = cmd.Arg(0)
  974. repository = cmd.Arg(1)
  975. )
  976. v.Set("fromSrc", src)
  977. v.Set("repo", repository)
  978. if cmd.NArg() == 3 {
  979. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  980. v.Set("tag", cmd.Arg(2))
  981. }
  982. if repository != "" {
  983. //Check if the given image name can be resolved
  984. repo, _ := parsers.ParseRepositoryTag(repository)
  985. if _, _, err := registry.ResolveRepositoryName(repo); err != nil {
  986. return err
  987. }
  988. }
  989. var in io.Reader
  990. if src == "-" {
  991. in = cli.in
  992. }
  993. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  994. }
  995. func (cli *DockerCli) CmdPush(args ...string) error {
  996. cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry")
  997. if err := cmd.Parse(args); err != nil {
  998. return nil
  999. }
  1000. name := cmd.Arg(0)
  1001. if name == "" {
  1002. cmd.Usage()
  1003. return nil
  1004. }
  1005. cli.LoadConfigFile()
  1006. remote, tag := parsers.ParseRepositoryTag(name)
  1007. // Resolve the Repository name from fqn to hostname + name
  1008. hostname, _, err := registry.ResolveRepositoryName(remote)
  1009. if err != nil {
  1010. return err
  1011. }
  1012. // Resolve the Auth config relevant for this server
  1013. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1014. // If we're not using a custom registry, we know the restrictions
  1015. // applied to repository names and can warn the user in advance.
  1016. // Custom repositories can have different rules, and we must also
  1017. // allow pushing by image ID.
  1018. if len(strings.SplitN(name, "/", 2)) == 1 {
  1019. username := cli.configFile.Configs[registry.IndexServerAddress()].Username
  1020. if username == "" {
  1021. username = "<user>"
  1022. }
  1023. return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  1024. }
  1025. v := url.Values{}
  1026. v.Set("tag", tag)
  1027. push := func(authConfig registry.AuthConfig) error {
  1028. buf, err := json.Marshal(authConfig)
  1029. if err != nil {
  1030. return err
  1031. }
  1032. registryAuthHeader := []string{
  1033. base64.URLEncoding.EncodeToString(buf),
  1034. }
  1035. return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  1036. "X-Registry-Auth": registryAuthHeader,
  1037. })
  1038. }
  1039. if err := push(authConfig); err != nil {
  1040. if strings.Contains(err.Error(), "Status 401") {
  1041. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  1042. if err := cli.CmdLogin(hostname); err != nil {
  1043. return err
  1044. }
  1045. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1046. return push(authConfig)
  1047. }
  1048. return err
  1049. }
  1050. return nil
  1051. }
  1052. func (cli *DockerCli) CmdPull(args ...string) error {
  1053. cmd := cli.Subcmd("pull", "NAME[:TAG]", "Pull an image or a repository from the registry")
  1054. allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository")
  1055. if err := cmd.Parse(args); err != nil {
  1056. return nil
  1057. }
  1058. if cmd.NArg() != 1 {
  1059. cmd.Usage()
  1060. return nil
  1061. }
  1062. var (
  1063. v = url.Values{}
  1064. remote = cmd.Arg(0)
  1065. newRemote = remote
  1066. )
  1067. taglessRemote, tag := parsers.ParseRepositoryTag(remote)
  1068. if tag == "" && !*allTags {
  1069. newRemote = taglessRemote + ":latest"
  1070. }
  1071. if tag != "" && *allTags {
  1072. return fmt.Errorf("tag can't be used with --all-tags/-a")
  1073. }
  1074. v.Set("fromImage", newRemote)
  1075. // Resolve the Repository name from fqn to hostname + name
  1076. hostname, _, err := registry.ResolveRepositoryName(taglessRemote)
  1077. if err != nil {
  1078. return err
  1079. }
  1080. cli.LoadConfigFile()
  1081. // Resolve the Auth config relevant for this server
  1082. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1083. pull := func(authConfig registry.AuthConfig) error {
  1084. buf, err := json.Marshal(authConfig)
  1085. if err != nil {
  1086. return err
  1087. }
  1088. registryAuthHeader := []string{
  1089. base64.URLEncoding.EncodeToString(buf),
  1090. }
  1091. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  1092. "X-Registry-Auth": registryAuthHeader,
  1093. })
  1094. }
  1095. if err := pull(authConfig); err != nil {
  1096. if strings.Contains(err.Error(), "Status 401") {
  1097. fmt.Fprintln(cli.out, "\nPlease login prior to pull:")
  1098. if err := cli.CmdLogin(hostname); err != nil {
  1099. return err
  1100. }
  1101. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1102. return pull(authConfig)
  1103. }
  1104. return err
  1105. }
  1106. return nil
  1107. }
  1108. func (cli *DockerCli) CmdImages(args ...string) error {
  1109. cmd := cli.Subcmd("images", "[NAME]", "List images")
  1110. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  1111. all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (by default filter out the intermediate image layers)")
  1112. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1113. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1114. flViz := cmd.Bool([]string{"#v", "#viz", "#-viz"}, false, "Output graph in graphviz format")
  1115. flTree := cmd.Bool([]string{"#t", "#tree", "#-tree"}, false, "Output graph in tree format")
  1116. flFilter := opts.NewListOpts(nil)
  1117. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values (i.e. 'dangling=true')")
  1118. if err := cmd.Parse(args); err != nil {
  1119. return nil
  1120. }
  1121. if cmd.NArg() > 1 {
  1122. cmd.Usage()
  1123. return nil
  1124. }
  1125. // Consolidate all filter flags, and sanity check them early.
  1126. // They'll get process in the daemon/server.
  1127. imageFilterArgs := filters.Args{}
  1128. for _, f := range flFilter.GetAll() {
  1129. var err error
  1130. imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs)
  1131. if err != nil {
  1132. return err
  1133. }
  1134. }
  1135. matchName := cmd.Arg(0)
  1136. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1137. if *flViz || *flTree {
  1138. v := url.Values{
  1139. "all": []string{"1"},
  1140. }
  1141. if len(imageFilterArgs) > 0 {
  1142. filterJson, err := filters.ToParam(imageFilterArgs)
  1143. if err != nil {
  1144. return err
  1145. }
  1146. v.Set("filters", filterJson)
  1147. }
  1148. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1149. if err != nil {
  1150. return err
  1151. }
  1152. outs := engine.NewTable("Created", 0)
  1153. if _, err := outs.ReadListFrom(body); err != nil {
  1154. return err
  1155. }
  1156. var (
  1157. printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)
  1158. startImage *engine.Env
  1159. roots = engine.NewTable("Created", outs.Len())
  1160. byParent = make(map[string]*engine.Table)
  1161. )
  1162. for _, image := range outs.Data {
  1163. if image.Get("ParentId") == "" {
  1164. roots.Add(image)
  1165. } else {
  1166. if children, exists := byParent[image.Get("ParentId")]; exists {
  1167. children.Add(image)
  1168. } else {
  1169. byParent[image.Get("ParentId")] = engine.NewTable("Created", 1)
  1170. byParent[image.Get("ParentId")].Add(image)
  1171. }
  1172. }
  1173. if matchName != "" {
  1174. if matchName == image.Get("Id") || matchName == utils.TruncateID(image.Get("Id")) {
  1175. startImage = image
  1176. }
  1177. for _, repotag := range image.GetList("RepoTags") {
  1178. if repotag == matchName {
  1179. startImage = image
  1180. }
  1181. }
  1182. }
  1183. }
  1184. if *flViz {
  1185. fmt.Fprintf(cli.out, "digraph docker {\n")
  1186. printNode = (*DockerCli).printVizNode
  1187. } else {
  1188. printNode = (*DockerCli).printTreeNode
  1189. }
  1190. if startImage != nil {
  1191. root := engine.NewTable("Created", 1)
  1192. root.Add(startImage)
  1193. cli.WalkTree(*noTrunc, root, byParent, "", printNode)
  1194. } else if matchName == "" {
  1195. cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
  1196. }
  1197. if *flViz {
  1198. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1199. }
  1200. } else {
  1201. v := url.Values{}
  1202. if len(imageFilterArgs) > 0 {
  1203. filterJson, err := filters.ToParam(imageFilterArgs)
  1204. if err != nil {
  1205. return err
  1206. }
  1207. v.Set("filters", filterJson)
  1208. }
  1209. if cmd.NArg() == 1 {
  1210. // FIXME rename this parameter, to not be confused with the filters flag
  1211. v.Set("filter", matchName)
  1212. }
  1213. if *all {
  1214. v.Set("all", "1")
  1215. }
  1216. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1217. if err != nil {
  1218. return err
  1219. }
  1220. outs := engine.NewTable("Created", 0)
  1221. if _, err := outs.ReadListFrom(body); err != nil {
  1222. return err
  1223. }
  1224. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1225. if !*quiet {
  1226. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1227. }
  1228. for _, out := range outs.Data {
  1229. for _, repotag := range out.GetList("RepoTags") {
  1230. repo, tag := parsers.ParseRepositoryTag(repotag)
  1231. outID := out.Get("Id")
  1232. if !*noTrunc {
  1233. outID = utils.TruncateID(outID)
  1234. }
  1235. if !*quiet {
  1236. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", repo, tag, outID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))), units.HumanSize(out.GetInt64("VirtualSize")))
  1237. } else {
  1238. fmt.Fprintln(w, outID)
  1239. }
  1240. }
  1241. }
  1242. if !*quiet {
  1243. w.Flush()
  1244. }
  1245. }
  1246. return nil
  1247. }
  1248. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1249. func (cli *DockerCli) WalkTree(noTrunc bool, images *engine.Table, byParent map[string]*engine.Table, prefix string, printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)) {
  1250. length := images.Len()
  1251. if length > 1 {
  1252. for index, image := range images.Data {
  1253. if index+1 == length {
  1254. printNode(cli, noTrunc, image, prefix+"└─")
  1255. if subimages, exists := byParent[image.Get("Id")]; exists {
  1256. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1257. }
  1258. } else {
  1259. printNode(cli, noTrunc, image, prefix+"\u251C─")
  1260. if subimages, exists := byParent[image.Get("Id")]; exists {
  1261. cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
  1262. }
  1263. }
  1264. }
  1265. } else {
  1266. for _, image := range images.Data {
  1267. printNode(cli, noTrunc, image, prefix+"└─")
  1268. if subimages, exists := byParent[image.Get("Id")]; exists {
  1269. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1270. }
  1271. }
  1272. }
  1273. }
  1274. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1275. func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) {
  1276. var (
  1277. imageID string
  1278. parentID string
  1279. )
  1280. if noTrunc {
  1281. imageID = image.Get("Id")
  1282. parentID = image.Get("ParentId")
  1283. } else {
  1284. imageID = utils.TruncateID(image.Get("Id"))
  1285. parentID = utils.TruncateID(image.Get("ParentId"))
  1286. }
  1287. if parentID == "" {
  1288. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1289. } else {
  1290. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1291. }
  1292. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1293. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1294. imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n"))
  1295. }
  1296. }
  1297. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1298. func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) {
  1299. var imageID string
  1300. if noTrunc {
  1301. imageID = image.Get("Id")
  1302. } else {
  1303. imageID = utils.TruncateID(image.Get("Id"))
  1304. }
  1305. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, units.HumanSize(image.GetInt64("VirtualSize")))
  1306. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1307. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", "))
  1308. } else {
  1309. fmt.Fprint(cli.out, "\n")
  1310. }
  1311. }
  1312. func (cli *DockerCli) CmdPs(args ...string) error {
  1313. cmd := cli.Subcmd("ps", "", "List containers")
  1314. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
  1315. size := cmd.Bool([]string{"s", "-size"}, false, "Display sizes")
  1316. all := cmd.Bool([]string{"a", "-all"}, false, "Show all containers. Only running containers are shown by default.")
  1317. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1318. nLatest := cmd.Bool([]string{"l", "-latest"}, false, "Show only the latest created container, include non-running ones.")
  1319. since := cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show only containers created since Id or Name, include non-running ones.")
  1320. before := cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name, include non-running ones.")
  1321. last := cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running ones.")
  1322. flFilter := opts.NewListOpts(nil)
  1323. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values. Valid filters:\nexited=<int> - containers with exit code of <int>\nstatus=(restarting|running|paused|exited)")
  1324. if err := cmd.Parse(args); err != nil {
  1325. return nil
  1326. }
  1327. v := url.Values{}
  1328. if *last == -1 && *nLatest {
  1329. *last = 1
  1330. }
  1331. if *all {
  1332. v.Set("all", "1")
  1333. }
  1334. if *last != -1 {
  1335. v.Set("limit", strconv.Itoa(*last))
  1336. }
  1337. if *since != "" {
  1338. v.Set("since", *since)
  1339. }
  1340. if *before != "" {
  1341. v.Set("before", *before)
  1342. }
  1343. if *size {
  1344. v.Set("size", "1")
  1345. }
  1346. // Consolidate all filter flags, and sanity check them.
  1347. // They'll get processed in the daemon/server.
  1348. psFilterArgs := filters.Args{}
  1349. for _, f := range flFilter.GetAll() {
  1350. var err error
  1351. psFilterArgs, err = filters.ParseFlag(f, psFilterArgs)
  1352. if err != nil {
  1353. return err
  1354. }
  1355. }
  1356. if len(psFilterArgs) > 0 {
  1357. filterJson, err := filters.ToParam(psFilterArgs)
  1358. if err != nil {
  1359. return err
  1360. }
  1361. v.Set("filters", filterJson)
  1362. }
  1363. body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
  1364. if err != nil {
  1365. return err
  1366. }
  1367. outs := engine.NewTable("Created", 0)
  1368. if _, err := outs.ReadListFrom(body); err != nil {
  1369. return err
  1370. }
  1371. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1372. if !*quiet {
  1373. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1374. if *size {
  1375. fmt.Fprintln(w, "\tSIZE")
  1376. } else {
  1377. fmt.Fprint(w, "\n")
  1378. }
  1379. }
  1380. for _, out := range outs.Data {
  1381. var (
  1382. outID = out.Get("Id")
  1383. outNames = out.GetList("Names")
  1384. )
  1385. if !*noTrunc {
  1386. outID = utils.TruncateID(outID)
  1387. }
  1388. // Remove the leading / from the names
  1389. for i := 0; i < len(outNames); i++ {
  1390. outNames[i] = outNames[i][1:]
  1391. }
  1392. if !*quiet {
  1393. var (
  1394. outCommand = out.Get("Command")
  1395. ports = engine.NewTable("", 0)
  1396. outNamesList = strings.Join(outNames, ",")
  1397. )
  1398. outCommand = strconv.Quote(outCommand)
  1399. if !*noTrunc {
  1400. outCommand = utils.Trunc(outCommand, 20)
  1401. outNamesList = outNames[0]
  1402. }
  1403. ports.ReadListFrom([]byte(out.Get("Ports")))
  1404. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", outID, out.Get("Image"), outCommand, units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))), out.Get("Status"), api.DisplayablePorts(ports), outNamesList)
  1405. if *size {
  1406. if out.GetInt("SizeRootFs") > 0 {
  1407. fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(out.GetInt64("SizeRw")), units.HumanSize(out.GetInt64("SizeRootFs")))
  1408. } else {
  1409. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("SizeRw")))
  1410. }
  1411. } else {
  1412. fmt.Fprint(w, "\n")
  1413. }
  1414. } else {
  1415. fmt.Fprintln(w, outID)
  1416. }
  1417. }
  1418. if !*quiet {
  1419. w.Flush()
  1420. }
  1421. return nil
  1422. }
  1423. func (cli *DockerCli) CmdCommit(args ...string) error {
  1424. cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1425. flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit")
  1426. flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
  1427. flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
  1428. // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands.
  1429. flConfig := cmd.String([]string{"#run", "#-run"}, "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands")
  1430. if err := cmd.Parse(args); err != nil {
  1431. return nil
  1432. }
  1433. var (
  1434. name = cmd.Arg(0)
  1435. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1436. )
  1437. if name == "" || len(cmd.Args()) > 2 {
  1438. cmd.Usage()
  1439. return nil
  1440. }
  1441. //Check if the given image name can be resolved
  1442. if repository != "" {
  1443. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1444. return err
  1445. }
  1446. }
  1447. v := url.Values{}
  1448. v.Set("container", name)
  1449. v.Set("repo", repository)
  1450. v.Set("tag", tag)
  1451. v.Set("comment", *flComment)
  1452. v.Set("author", *flAuthor)
  1453. if *flPause != true {
  1454. v.Set("pause", "0")
  1455. }
  1456. var (
  1457. config *runconfig.Config
  1458. env engine.Env
  1459. )
  1460. if *flConfig != "" {
  1461. config = &runconfig.Config{}
  1462. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1463. return err
  1464. }
  1465. }
  1466. stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false)
  1467. if err != nil {
  1468. return err
  1469. }
  1470. if err := env.Decode(stream); err != nil {
  1471. return err
  1472. }
  1473. fmt.Fprintf(cli.out, "%s\n", env.Get("Id"))
  1474. return nil
  1475. }
  1476. func (cli *DockerCli) CmdEvents(args ...string) error {
  1477. cmd := cli.Subcmd("events", "", "Get real time events from the server")
  1478. since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp")
  1479. until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp")
  1480. if err := cmd.Parse(args); err != nil {
  1481. return nil
  1482. }
  1483. if cmd.NArg() != 0 {
  1484. cmd.Usage()
  1485. return nil
  1486. }
  1487. var (
  1488. v = url.Values{}
  1489. loc = time.FixedZone(time.Now().Zone())
  1490. )
  1491. var setTime = func(key, value string) {
  1492. format := timeutils.RFC3339NanoFixed
  1493. if len(value) < len(format) {
  1494. format = format[:len(value)]
  1495. }
  1496. if t, err := time.ParseInLocation(format, value, loc); err == nil {
  1497. v.Set(key, strconv.FormatInt(t.Unix(), 10))
  1498. } else {
  1499. v.Set(key, value)
  1500. }
  1501. }
  1502. if *since != "" {
  1503. setTime("since", *since)
  1504. }
  1505. if *until != "" {
  1506. setTime("until", *until)
  1507. }
  1508. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1509. return err
  1510. }
  1511. return nil
  1512. }
  1513. func (cli *DockerCli) CmdExport(args ...string) error {
  1514. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1515. if err := cmd.Parse(args); err != nil {
  1516. return nil
  1517. }
  1518. if cmd.NArg() != 1 {
  1519. cmd.Usage()
  1520. return nil
  1521. }
  1522. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1523. return err
  1524. }
  1525. return nil
  1526. }
  1527. func (cli *DockerCli) CmdDiff(args ...string) error {
  1528. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1529. if err := cmd.Parse(args); err != nil {
  1530. return nil
  1531. }
  1532. if cmd.NArg() != 1 {
  1533. cmd.Usage()
  1534. return nil
  1535. }
  1536. body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
  1537. if err != nil {
  1538. return err
  1539. }
  1540. outs := engine.NewTable("", 0)
  1541. if _, err := outs.ReadListFrom(body); err != nil {
  1542. return err
  1543. }
  1544. for _, change := range outs.Data {
  1545. var kind string
  1546. switch change.GetInt("Kind") {
  1547. case archive.ChangeModify:
  1548. kind = "C"
  1549. case archive.ChangeAdd:
  1550. kind = "A"
  1551. case archive.ChangeDelete:
  1552. kind = "D"
  1553. }
  1554. fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
  1555. }
  1556. return nil
  1557. }
  1558. func (cli *DockerCli) CmdLogs(args ...string) error {
  1559. var (
  1560. cmd = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1561. follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
  1562. times = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
  1563. tail = cmd.String([]string{"-tail"}, "all", "Output the specified number of lines at the end of logs (defaults to all logs)")
  1564. )
  1565. if err := cmd.Parse(args); err != nil {
  1566. return nil
  1567. }
  1568. if cmd.NArg() != 1 {
  1569. cmd.Usage()
  1570. return nil
  1571. }
  1572. name := cmd.Arg(0)
  1573. steam, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1574. if err != nil {
  1575. return err
  1576. }
  1577. env := engine.Env{}
  1578. if err := env.Decode(steam); err != nil {
  1579. return err
  1580. }
  1581. v := url.Values{}
  1582. v.Set("stdout", "1")
  1583. v.Set("stderr", "1")
  1584. if *times {
  1585. v.Set("timestamps", "1")
  1586. }
  1587. if *follow {
  1588. v.Set("follow", "1")
  1589. }
  1590. v.Set("tail", *tail)
  1591. return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil)
  1592. }
  1593. func (cli *DockerCli) CmdAttach(args ...string) error {
  1594. var (
  1595. cmd = cli.Subcmd("attach", "CONTAINER", "Attach to a running container")
  1596. noStdin = cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN")
  1597. proxy = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy all received signals to the process (even in non-TTY mode). SIGCHLD, SIGKILL, and SIGSTOP are not proxied.")
  1598. )
  1599. if err := cmd.Parse(args); err != nil {
  1600. return nil
  1601. }
  1602. if cmd.NArg() != 1 {
  1603. cmd.Usage()
  1604. return nil
  1605. }
  1606. name := cmd.Arg(0)
  1607. stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1608. if err != nil {
  1609. return err
  1610. }
  1611. env := engine.Env{}
  1612. if err := env.Decode(stream); err != nil {
  1613. return err
  1614. }
  1615. if !env.GetSubEnv("State").GetBool("Running") {
  1616. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  1617. }
  1618. var (
  1619. config = env.GetSubEnv("Config")
  1620. tty = config.GetBool("Tty")
  1621. )
  1622. if tty && cli.isTerminalOut {
  1623. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  1624. log.Debugf("Error monitoring TTY size: %s", err)
  1625. }
  1626. }
  1627. var in io.ReadCloser
  1628. v := url.Values{}
  1629. v.Set("stream", "1")
  1630. if !*noStdin && config.GetBool("OpenStdin") {
  1631. v.Set("stdin", "1")
  1632. in = cli.in
  1633. }
  1634. v.Set("stdout", "1")
  1635. v.Set("stderr", "1")
  1636. if *proxy && !tty {
  1637. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1638. defer signal.StopCatch(sigc)
  1639. }
  1640. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil); err != nil {
  1641. return err
  1642. }
  1643. _, status, err := getExitCode(cli, cmd.Arg(0))
  1644. if err != nil {
  1645. return err
  1646. }
  1647. if status != 0 {
  1648. return &utils.StatusError{StatusCode: status}
  1649. }
  1650. return nil
  1651. }
  1652. func (cli *DockerCli) CmdSearch(args ...string) error {
  1653. cmd := cli.Subcmd("search", "TERM", "Search the Docker Hub for images")
  1654. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1655. trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds")
  1656. automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds")
  1657. stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars")
  1658. if err := cmd.Parse(args); err != nil {
  1659. return nil
  1660. }
  1661. if cmd.NArg() != 1 {
  1662. cmd.Usage()
  1663. return nil
  1664. }
  1665. v := url.Values{}
  1666. v.Set("term", cmd.Arg(0))
  1667. body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true))
  1668. if err != nil {
  1669. return err
  1670. }
  1671. outs := engine.NewTable("star_count", 0)
  1672. if _, err := outs.ReadListFrom(body); err != nil {
  1673. return err
  1674. }
  1675. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1676. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n")
  1677. for _, out := range outs.Data {
  1678. if ((*automated || *trusted) && (!out.GetBool("is_trusted") && !out.GetBool("is_automated"))) || (*stars > out.GetInt("star_count")) {
  1679. continue
  1680. }
  1681. desc := strings.Replace(out.Get("description"), "\n", " ", -1)
  1682. desc = strings.Replace(desc, "\r", " ", -1)
  1683. if !*noTrunc && len(desc) > 45 {
  1684. desc = utils.Trunc(desc, 42) + "..."
  1685. }
  1686. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count"))
  1687. if out.GetBool("is_official") {
  1688. fmt.Fprint(w, "[OK]")
  1689. }
  1690. fmt.Fprint(w, "\t")
  1691. if out.GetBool("is_automated") || out.GetBool("is_trusted") {
  1692. fmt.Fprint(w, "[OK]")
  1693. }
  1694. fmt.Fprint(w, "\n")
  1695. }
  1696. w.Flush()
  1697. return nil
  1698. }
  1699. // Ports type - Used to parse multiple -p flags
  1700. type ports []int
  1701. func (cli *DockerCli) CmdTag(args ...string) error {
  1702. cmd := cli.Subcmd("tag", "IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository")
  1703. force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force")
  1704. if err := cmd.Parse(args); err != nil {
  1705. return nil
  1706. }
  1707. if cmd.NArg() != 2 {
  1708. cmd.Usage()
  1709. return nil
  1710. }
  1711. var (
  1712. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1713. v = url.Values{}
  1714. )
  1715. //Check if the given image name can be resolved
  1716. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1717. return err
  1718. }
  1719. v.Set("repo", repository)
  1720. v.Set("tag", tag)
  1721. if *force {
  1722. v.Set("force", "1")
  1723. }
  1724. if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil {
  1725. return err
  1726. }
  1727. return nil
  1728. }
  1729. func (cli *DockerCli) pullImage(image string) error {
  1730. v := url.Values{}
  1731. repos, tag := parsers.ParseRepositoryTag(image)
  1732. // pull only the image tagged 'latest' if no tag was specified
  1733. if tag == "" {
  1734. tag = "latest"
  1735. }
  1736. v.Set("fromImage", repos)
  1737. v.Set("tag", tag)
  1738. // Resolve the Repository name from fqn to hostname + name
  1739. hostname, _, err := registry.ResolveRepositoryName(repos)
  1740. if err != nil {
  1741. return err
  1742. }
  1743. // Load the auth config file, to be able to pull the image
  1744. cli.LoadConfigFile()
  1745. // Resolve the Auth config relevant for this server
  1746. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1747. buf, err := json.Marshal(authConfig)
  1748. if err != nil {
  1749. return err
  1750. }
  1751. registryAuthHeader := []string{
  1752. base64.URLEncoding.EncodeToString(buf),
  1753. }
  1754. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1755. return err
  1756. }
  1757. return nil
  1758. }
  1759. type cidFile struct {
  1760. path string
  1761. file *os.File
  1762. written bool
  1763. }
  1764. func newCIDFile(path string) (*cidFile, error) {
  1765. if _, err := os.Stat(path); err == nil {
  1766. return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
  1767. }
  1768. f, err := os.Create(path)
  1769. if err != nil {
  1770. return nil, fmt.Errorf("Failed to create the container ID file: %s", err)
  1771. }
  1772. return &cidFile{path: path, file: f}, nil
  1773. }
  1774. func (cid *cidFile) Close() error {
  1775. cid.file.Close()
  1776. if !cid.written {
  1777. if err := os.Remove(cid.path); err != nil {
  1778. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  1779. }
  1780. }
  1781. return nil
  1782. }
  1783. func (cid *cidFile) Write(id string) error {
  1784. if _, err := cid.file.Write([]byte(id)); err != nil {
  1785. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  1786. }
  1787. cid.written = true
  1788. return nil
  1789. }
  1790. func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (engine.Env, error) {
  1791. containerValues := url.Values{}
  1792. if name != "" {
  1793. containerValues.Set("name", name)
  1794. }
  1795. mergedConfig := runconfig.MergeConfigs(config, hostConfig)
  1796. var containerIDFile *cidFile
  1797. if cidfile != "" {
  1798. var err error
  1799. if containerIDFile, err = newCIDFile(cidfile); err != nil {
  1800. return nil, err
  1801. }
  1802. defer containerIDFile.Close()
  1803. }
  1804. //create the container
  1805. stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false)
  1806. //if image not found try to pull it
  1807. if statusCode == 404 {
  1808. fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", config.Image)
  1809. if err = cli.pullImage(config.Image); err != nil {
  1810. return nil, err
  1811. }
  1812. // Retry
  1813. if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil {
  1814. return nil, err
  1815. }
  1816. } else if err != nil {
  1817. return nil, err
  1818. }
  1819. var result engine.Env
  1820. if err := result.Decode(stream); err != nil {
  1821. return nil, err
  1822. }
  1823. for _, warning := range result.GetList("Warnings") {
  1824. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1825. }
  1826. if containerIDFile != nil {
  1827. if err = containerIDFile.Write(result.Get("Id")); err != nil {
  1828. return nil, err
  1829. }
  1830. }
  1831. return result, nil
  1832. }
  1833. func (cli *DockerCli) CmdCreate(args ...string) error {
  1834. cmd := cli.Subcmd("create", "IMAGE [COMMAND] [ARG...]", "Create a new container")
  1835. // These are flags not stored in Config/HostConfig
  1836. var (
  1837. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  1838. )
  1839. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1840. if err != nil {
  1841. return err
  1842. }
  1843. if config.Image == "" {
  1844. cmd.Usage()
  1845. return nil
  1846. }
  1847. createResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1848. if err != nil {
  1849. return err
  1850. }
  1851. fmt.Fprintf(cli.out, "%s\n", createResult.Get("Id"))
  1852. return nil
  1853. }
  1854. func (cli *DockerCli) CmdRun(args ...string) error {
  1855. // FIXME: just use runconfig.Parse already
  1856. cmd := cli.Subcmd("run", "IMAGE [COMMAND] [ARG...]", "Run a command in a new container")
  1857. // These are flags not stored in Config/HostConfig
  1858. var (
  1859. flAutoRemove = cmd.Bool([]string{"#rm", "-rm"}, false, "Automatically remove the container when it exits (incompatible with -d)")
  1860. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run the container in the background and print the new container ID")
  1861. flSigProxy = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy received signals to the process (even in non-TTY mode). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.")
  1862. flName = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container")
  1863. flAttach *opts.ListOpts
  1864. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  1865. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  1866. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  1867. )
  1868. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1869. if err != nil {
  1870. return err
  1871. }
  1872. if config.Image == "" {
  1873. cmd.Usage()
  1874. return nil
  1875. }
  1876. if *flDetach {
  1877. if fl := cmd.Lookup("attach"); fl != nil {
  1878. flAttach = fl.Value.(*opts.ListOpts)
  1879. if flAttach.Len() != 0 {
  1880. return ErrConflictAttachDetach
  1881. }
  1882. }
  1883. if *flAutoRemove {
  1884. return ErrConflictDetachAutoRemove
  1885. }
  1886. config.AttachStdin = false
  1887. config.AttachStdout = false
  1888. config.AttachStderr = false
  1889. config.StdinOnce = false
  1890. }
  1891. // Disable flSigProxy in case on TTY
  1892. sigProxy := *flSigProxy
  1893. if config.Tty {
  1894. sigProxy = false
  1895. }
  1896. runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1897. if err != nil {
  1898. return err
  1899. }
  1900. if sigProxy {
  1901. sigc := cli.forwardAllSignals(runResult.Get("Id"))
  1902. defer signal.StopCatch(sigc)
  1903. }
  1904. var (
  1905. waitDisplayId chan struct{}
  1906. errCh chan error
  1907. )
  1908. if !config.AttachStdout && !config.AttachStderr {
  1909. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1910. waitDisplayId = make(chan struct{})
  1911. go func() {
  1912. defer close(waitDisplayId)
  1913. fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
  1914. }()
  1915. }
  1916. if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") {
  1917. return ErrConflictRestartPolicyAndAutoRemove
  1918. }
  1919. // We need to instanciate the chan because the select needs it. It can
  1920. // be closed but can't be uninitialized.
  1921. hijacked := make(chan io.Closer)
  1922. // Block the return until the chan gets closed
  1923. defer func() {
  1924. log.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1925. if _, ok := <-hijacked; ok {
  1926. log.Errorf("Hijack did not finish (chan still open)")
  1927. }
  1928. }()
  1929. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1930. var (
  1931. out, stderr io.Writer
  1932. in io.ReadCloser
  1933. v = url.Values{}
  1934. )
  1935. v.Set("stream", "1")
  1936. if config.AttachStdin {
  1937. v.Set("stdin", "1")
  1938. in = cli.in
  1939. }
  1940. if config.AttachStdout {
  1941. v.Set("stdout", "1")
  1942. out = cli.out
  1943. }
  1944. if config.AttachStderr {
  1945. v.Set("stderr", "1")
  1946. if config.Tty {
  1947. stderr = cli.out
  1948. } else {
  1949. stderr = cli.err
  1950. }
  1951. }
  1952. errCh = utils.Go(func() error {
  1953. return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
  1954. })
  1955. } else {
  1956. close(hijacked)
  1957. }
  1958. // Acknowledge the hijack before starting
  1959. select {
  1960. case closer := <-hijacked:
  1961. // Make sure that hijack gets closed when returning. (result
  1962. // in closing hijack chan and freeing server's goroutines.
  1963. if closer != nil {
  1964. defer closer.Close()
  1965. }
  1966. case err := <-errCh:
  1967. if err != nil {
  1968. log.Debugf("Error hijack: %s", err)
  1969. return err
  1970. }
  1971. }
  1972. //start the container
  1973. if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", hostConfig, false)); err != nil {
  1974. return err
  1975. }
  1976. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  1977. if err := cli.monitorTtySize(runResult.Get("Id"), false); err != nil {
  1978. log.Errorf("Error monitoring TTY size: %s", err)
  1979. }
  1980. }
  1981. if errCh != nil {
  1982. if err := <-errCh; err != nil {
  1983. log.Debugf("Error hijack: %s", err)
  1984. return err
  1985. }
  1986. }
  1987. // Detached mode: wait for the id to be displayed and return.
  1988. if !config.AttachStdout && !config.AttachStderr {
  1989. // Detached mode
  1990. <-waitDisplayId
  1991. return nil
  1992. }
  1993. var status int
  1994. // Attached mode
  1995. if *flAutoRemove {
  1996. // Autoremove: wait for the container to finish, retrieve
  1997. // the exit code and remove the container
  1998. if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
  1999. return err
  2000. }
  2001. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2002. return err
  2003. }
  2004. if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
  2005. return err
  2006. }
  2007. } else {
  2008. if !config.Tty {
  2009. // In non-tty mode, we can't dettach, so we know we need to wait.
  2010. if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
  2011. return err
  2012. }
  2013. } else {
  2014. // In TTY mode, there is a race. If the process dies too slowly, the state can be update after the getExitCode call
  2015. // and result in a wrong exit code.
  2016. // No Autoremove: Simply retrieve the exit code
  2017. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2018. return err
  2019. }
  2020. }
  2021. }
  2022. if status != 0 {
  2023. return &utils.StatusError{StatusCode: status}
  2024. }
  2025. return nil
  2026. }
  2027. func (cli *DockerCli) CmdCp(args ...string) error {
  2028. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  2029. if err := cmd.Parse(args); err != nil {
  2030. return nil
  2031. }
  2032. if cmd.NArg() != 2 {
  2033. cmd.Usage()
  2034. return nil
  2035. }
  2036. var copyData engine.Env
  2037. info := strings.Split(cmd.Arg(0), ":")
  2038. if len(info) != 2 {
  2039. return fmt.Errorf("Error: Path not specified")
  2040. }
  2041. copyData.Set("Resource", info[1])
  2042. copyData.Set("HostPath", cmd.Arg(1))
  2043. stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false)
  2044. if stream != nil {
  2045. defer stream.Close()
  2046. }
  2047. if statusCode == 404 {
  2048. return fmt.Errorf("No such container: %v", info[0])
  2049. }
  2050. if err != nil {
  2051. return err
  2052. }
  2053. if statusCode == 200 {
  2054. if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
  2055. return err
  2056. }
  2057. }
  2058. return nil
  2059. }
  2060. func (cli *DockerCli) CmdSave(args ...string) error {
  2061. cmd := cli.Subcmd("save", "IMAGE [IMAGE...]", "Save an image(s) to a tar archive (streamed to STDOUT by default)")
  2062. outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT")
  2063. if err := cmd.Parse(args); err != nil {
  2064. return err
  2065. }
  2066. if cmd.NArg() < 1 {
  2067. cmd.Usage()
  2068. return nil
  2069. }
  2070. var (
  2071. output io.Writer = cli.out
  2072. err error
  2073. )
  2074. if *outfile != "" {
  2075. output, err = os.Create(*outfile)
  2076. if err != nil {
  2077. return err
  2078. }
  2079. }
  2080. if len(cmd.Args()) == 1 {
  2081. image := cmd.Arg(0)
  2082. if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil {
  2083. return err
  2084. }
  2085. } else {
  2086. v := url.Values{}
  2087. for _, arg := range cmd.Args() {
  2088. v.Add("names", arg)
  2089. }
  2090. if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil {
  2091. return err
  2092. }
  2093. }
  2094. return nil
  2095. }
  2096. func (cli *DockerCli) CmdLoad(args ...string) error {
  2097. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  2098. infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
  2099. if err := cmd.Parse(args); err != nil {
  2100. return err
  2101. }
  2102. if cmd.NArg() != 0 {
  2103. cmd.Usage()
  2104. return nil
  2105. }
  2106. var (
  2107. input io.Reader = cli.in
  2108. err error
  2109. )
  2110. if *infile != "" {
  2111. input, err = os.Open(*infile)
  2112. if err != nil {
  2113. return err
  2114. }
  2115. }
  2116. if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil {
  2117. return err
  2118. }
  2119. return nil
  2120. }
  2121. func (cli *DockerCli) CmdExec(args ...string) error {
  2122. cmd := cli.Subcmd("exec", "CONTAINER COMMAND [ARG...]", "Run a command in an existing container")
  2123. execConfig, err := runconfig.ParseExec(cmd, args)
  2124. if err != nil {
  2125. return err
  2126. }
  2127. if execConfig.Container == "" {
  2128. cmd.Usage()
  2129. return nil
  2130. }
  2131. stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, false)
  2132. if err != nil {
  2133. return err
  2134. }
  2135. var execResult engine.Env
  2136. if err := execResult.Decode(stream); err != nil {
  2137. return err
  2138. }
  2139. execID := execResult.Get("Id")
  2140. if execID == "" {
  2141. fmt.Fprintf(cli.out, "exec ID empty")
  2142. return nil
  2143. }
  2144. if execConfig.Detach {
  2145. if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, false)); err != nil {
  2146. return err
  2147. }
  2148. return nil
  2149. }
  2150. // Interactive exec requested.
  2151. var (
  2152. out, stderr io.Writer
  2153. in io.ReadCloser
  2154. hijacked = make(chan io.Closer)
  2155. errCh chan error
  2156. )
  2157. // Block the return until the chan gets closed
  2158. defer func() {
  2159. log.Debugf("End of CmdExec(), Waiting for hijack to finish.")
  2160. if _, ok := <-hijacked; ok {
  2161. log.Errorf("Hijack did not finish (chan still open)")
  2162. }
  2163. }()
  2164. if execConfig.AttachStdin {
  2165. in = cli.in
  2166. }
  2167. if execConfig.AttachStdout {
  2168. out = cli.out
  2169. }
  2170. if execConfig.AttachStderr {
  2171. if execConfig.Tty {
  2172. stderr = cli.out
  2173. } else {
  2174. stderr = cli.err
  2175. }
  2176. }
  2177. errCh = utils.Go(func() error {
  2178. return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig)
  2179. })
  2180. // Acknowledge the hijack before starting
  2181. select {
  2182. case closer := <-hijacked:
  2183. // Make sure that hijack gets closed when returning. (result
  2184. // in closing hijack chan and freeing server's goroutines.
  2185. if closer != nil {
  2186. defer closer.Close()
  2187. }
  2188. case err := <-errCh:
  2189. if err != nil {
  2190. log.Debugf("Error hijack: %s", err)
  2191. return err
  2192. }
  2193. }
  2194. if execConfig.Tty && cli.isTerminalIn {
  2195. if err := cli.monitorTtySize(execID, true); err != nil {
  2196. log.Errorf("Error monitoring TTY size: %s", err)
  2197. }
  2198. }
  2199. if err := <-errCh; err != nil {
  2200. log.Debugf("Error hijack: %s", err)
  2201. return err
  2202. }
  2203. return nil
  2204. }