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