commands.go 67 KB

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