commands.go 67 KB

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