commands.go 66 KB

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