commands.go 69 KB

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