commands.go 69 KB

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