commands.go 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623
  1. package client
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "text/tabwriter"
  21. "text/template"
  22. "time"
  23. log "github.com/Sirupsen/logrus"
  24. "github.com/docker/docker/api"
  25. "github.com/docker/docker/dockerversion"
  26. "github.com/docker/docker/engine"
  27. "github.com/docker/docker/graph"
  28. "github.com/docker/docker/nat"
  29. "github.com/docker/docker/opts"
  30. "github.com/docker/docker/pkg/archive"
  31. flag "github.com/docker/docker/pkg/mflag"
  32. "github.com/docker/docker/pkg/parsers"
  33. "github.com/docker/docker/pkg/parsers/filters"
  34. "github.com/docker/docker/pkg/promise"
  35. "github.com/docker/docker/pkg/signal"
  36. "github.com/docker/docker/pkg/term"
  37. "github.com/docker/docker/pkg/timeutils"
  38. "github.com/docker/docker/pkg/units"
  39. "github.com/docker/docker/registry"
  40. "github.com/docker/docker/runconfig"
  41. "github.com/docker/docker/utils"
  42. )
  43. const (
  44. tarHeaderSize = 512
  45. )
  46. func (cli *DockerCli) CmdHelp(args ...string) error {
  47. if len(args) > 1 {
  48. method, exists := cli.getMethod(args[:2]...)
  49. if exists {
  50. method("--help")
  51. return nil
  52. }
  53. }
  54. if len(args) > 0 {
  55. method, exists := cli.getMethod(args[0])
  56. if !exists {
  57. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  58. } else {
  59. method("--help")
  60. return nil
  61. }
  62. }
  63. flag.Usage()
  64. return nil
  65. }
  66. func (cli *DockerCli) CmdBuild(args ...string) error {
  67. cmd := cli.Subcmd("build", "PATH | URL | -", "Build a new image from the source code at PATH")
  68. tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) to be applied to the resulting image in case of success")
  69. suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers")
  70. noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image")
  71. rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build")
  72. forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers, even after unsuccessful builds")
  73. 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. return nil
  513. }
  514. func (cli *DockerCli) CmdStop(args ...string) error {
  515. cmd := cli.Subcmd("stop", "CONTAINER [CONTAINER...]", "Stop a running container by sending SIGTERM and then SIGKILL after a grace period")
  516. nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.")
  517. if err := cmd.Parse(args); err != nil {
  518. return nil
  519. }
  520. if cmd.NArg() < 1 {
  521. cmd.Usage()
  522. return nil
  523. }
  524. v := url.Values{}
  525. v.Set("t", strconv.Itoa(*nSeconds))
  526. var encounteredError error
  527. for _, name := range cmd.Args() {
  528. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, false))
  529. if err != nil {
  530. fmt.Fprintf(cli.err, "%s\n", err)
  531. encounteredError = fmt.Errorf("Error: failed to stop one or more containers")
  532. } else {
  533. fmt.Fprintf(cli.out, "%s\n", name)
  534. }
  535. }
  536. return encounteredError
  537. }
  538. func (cli *DockerCli) CmdRestart(args ...string) error {
  539. cmd := cli.Subcmd("restart", "CONTAINER [CONTAINER...]", "Restart a running container")
  540. 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.")
  541. if err := cmd.Parse(args); err != nil {
  542. return nil
  543. }
  544. if cmd.NArg() < 1 {
  545. cmd.Usage()
  546. return nil
  547. }
  548. v := url.Values{}
  549. v.Set("t", strconv.Itoa(*nSeconds))
  550. var encounteredError error
  551. for _, name := range cmd.Args() {
  552. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, false))
  553. if err != nil {
  554. fmt.Fprintf(cli.err, "%s\n", err)
  555. encounteredError = fmt.Errorf("Error: failed to restart one or more containers")
  556. } else {
  557. fmt.Fprintf(cli.out, "%s\n", name)
  558. }
  559. }
  560. return encounteredError
  561. }
  562. func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal {
  563. sigc := make(chan os.Signal, 128)
  564. signal.CatchAll(sigc)
  565. go func() {
  566. for s := range sigc {
  567. if s == signal.SIGCHLD {
  568. continue
  569. }
  570. var sig string
  571. for sigStr, sigN := range signal.SignalMap {
  572. if sigN == s {
  573. sig = sigStr
  574. break
  575. }
  576. }
  577. if sig == "" {
  578. log.Errorf("Unsupported signal: %v. Discarding.", s)
  579. }
  580. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, false)); err != nil {
  581. log.Debugf("Error sending signal: %s", err)
  582. }
  583. }
  584. }()
  585. return sigc
  586. }
  587. func (cli *DockerCli) CmdStart(args ...string) error {
  588. var (
  589. cErr chan error
  590. tty bool
  591. cmd = cli.Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  592. attach = cmd.Bool([]string{"a", "-attach"}, false, "Attach container's STDOUT and STDERR and forward all signals to the process")
  593. openStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Attach container's STDIN")
  594. )
  595. if err := cmd.Parse(args); err != nil {
  596. return nil
  597. }
  598. if cmd.NArg() < 1 {
  599. cmd.Usage()
  600. return nil
  601. }
  602. hijacked := make(chan io.Closer)
  603. if *attach || *openStdin {
  604. if cmd.NArg() > 1 {
  605. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  606. }
  607. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  608. if err != nil {
  609. return err
  610. }
  611. env := engine.Env{}
  612. if err := env.Decode(stream); err != nil {
  613. return err
  614. }
  615. config := env.GetSubEnv("Config")
  616. tty = config.GetBool("Tty")
  617. if !tty {
  618. sigc := cli.forwardAllSignals(cmd.Arg(0))
  619. defer signal.StopCatch(sigc)
  620. }
  621. var in io.ReadCloser
  622. v := url.Values{}
  623. v.Set("stream", "1")
  624. if *openStdin && config.GetBool("OpenStdin") {
  625. v.Set("stdin", "1")
  626. in = cli.in
  627. }
  628. v.Set("stdout", "1")
  629. v.Set("stderr", "1")
  630. cErr = promise.Go(func() error {
  631. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, hijacked, nil)
  632. })
  633. } else {
  634. close(hijacked)
  635. }
  636. // Acknowledge the hijack before starting
  637. select {
  638. case closer := <-hijacked:
  639. // Make sure that the hijack gets closed when returning (results
  640. // in closing the hijack chan and freeing server's goroutines)
  641. if closer != nil {
  642. defer closer.Close()
  643. }
  644. case err := <-cErr:
  645. if err != nil {
  646. return err
  647. }
  648. }
  649. var encounteredError error
  650. for _, name := range cmd.Args() {
  651. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, false))
  652. if err != nil {
  653. if !*attach || !*openStdin {
  654. fmt.Fprintf(cli.err, "%s\n", err)
  655. }
  656. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  657. } else {
  658. if !*attach || !*openStdin {
  659. fmt.Fprintf(cli.out, "%s\n", name)
  660. }
  661. }
  662. }
  663. if encounteredError != nil {
  664. if *openStdin || *attach {
  665. cli.in.Close()
  666. }
  667. return encounteredError
  668. }
  669. if *openStdin || *attach {
  670. if tty && cli.isTerminalOut {
  671. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  672. log.Errorf("Error monitoring TTY size: %s", err)
  673. }
  674. }
  675. if attchErr := <-cErr; attchErr != nil {
  676. return attchErr
  677. }
  678. _, status, err := getExitCode(cli, cmd.Arg(0))
  679. if err != nil {
  680. return err
  681. }
  682. if status != 0 {
  683. return &utils.StatusError{StatusCode: status}
  684. }
  685. }
  686. return nil
  687. }
  688. func (cli *DockerCli) CmdUnpause(args ...string) error {
  689. cmd := cli.Subcmd("unpause", "CONTAINER", "Unpause all processes within a container")
  690. if err := cmd.Parse(args); err != nil {
  691. return nil
  692. }
  693. if cmd.NArg() != 1 {
  694. cmd.Usage()
  695. return nil
  696. }
  697. var encounteredError error
  698. for _, name := range cmd.Args() {
  699. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, false)); err != nil {
  700. fmt.Fprintf(cli.err, "%s\n", err)
  701. encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name)
  702. } else {
  703. fmt.Fprintf(cli.out, "%s\n", name)
  704. }
  705. }
  706. return encounteredError
  707. }
  708. func (cli *DockerCli) CmdPause(args ...string) error {
  709. cmd := cli.Subcmd("pause", "CONTAINER", "Pause all processes within a container")
  710. if err := cmd.Parse(args); err != nil {
  711. return nil
  712. }
  713. if cmd.NArg() != 1 {
  714. cmd.Usage()
  715. return nil
  716. }
  717. var encounteredError error
  718. for _, name := range cmd.Args() {
  719. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, false)); err != nil {
  720. fmt.Fprintf(cli.err, "%s\n", err)
  721. encounteredError = fmt.Errorf("Error: failed to pause container named %s", name)
  722. } else {
  723. fmt.Fprintf(cli.out, "%s\n", name)
  724. }
  725. }
  726. return encounteredError
  727. }
  728. func (cli *DockerCli) CmdInspect(args ...string) error {
  729. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image")
  730. tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template.")
  731. if err := cmd.Parse(args); err != nil {
  732. return nil
  733. }
  734. if cmd.NArg() < 1 {
  735. cmd.Usage()
  736. return nil
  737. }
  738. var tmpl *template.Template
  739. if *tmplStr != "" {
  740. var err error
  741. if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil {
  742. fmt.Fprintf(cli.err, "Template parsing error: %v\n", err)
  743. return &utils.StatusError{StatusCode: 64,
  744. Status: "Template parsing error: " + err.Error()}
  745. }
  746. }
  747. indented := new(bytes.Buffer)
  748. indented.WriteByte('[')
  749. status := 0
  750. for _, name := range cmd.Args() {
  751. obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  752. if err != nil {
  753. obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, false))
  754. if err != nil {
  755. if strings.Contains(err.Error(), "No such") {
  756. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  757. } else {
  758. fmt.Fprintf(cli.err, "%s", err)
  759. }
  760. status = 1
  761. continue
  762. }
  763. }
  764. if tmpl == nil {
  765. if err = json.Indent(indented, obj, "", " "); err != nil {
  766. fmt.Fprintf(cli.err, "%s\n", err)
  767. status = 1
  768. continue
  769. }
  770. } else {
  771. // Has template, will render
  772. var value interface{}
  773. if err := json.Unmarshal(obj, &value); err != nil {
  774. fmt.Fprintf(cli.err, "%s\n", err)
  775. status = 1
  776. continue
  777. }
  778. if err := tmpl.Execute(cli.out, value); err != nil {
  779. return err
  780. }
  781. cli.out.Write([]byte{'\n'})
  782. }
  783. indented.WriteString(",")
  784. }
  785. if indented.Len() > 1 {
  786. // Remove trailing ','
  787. indented.Truncate(indented.Len() - 1)
  788. }
  789. indented.WriteByte(']')
  790. if tmpl == nil {
  791. if _, err := io.Copy(cli.out, indented); err != nil {
  792. return err
  793. }
  794. }
  795. if status != 0 {
  796. return &utils.StatusError{StatusCode: status}
  797. }
  798. return nil
  799. }
  800. func (cli *DockerCli) CmdTop(args ...string) error {
  801. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Display the running processes of a container")
  802. if err := cmd.Parse(args); err != nil {
  803. return nil
  804. }
  805. if cmd.NArg() == 0 {
  806. cmd.Usage()
  807. return nil
  808. }
  809. val := url.Values{}
  810. if cmd.NArg() > 1 {
  811. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  812. }
  813. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, false)
  814. if err != nil {
  815. return err
  816. }
  817. var procs engine.Env
  818. if err := procs.Decode(stream); err != nil {
  819. return err
  820. }
  821. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  822. fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t"))
  823. processes := [][]string{}
  824. if err := procs.GetJson("Processes", &processes); err != nil {
  825. return err
  826. }
  827. for _, proc := range processes {
  828. fmt.Fprintln(w, strings.Join(proc, "\t"))
  829. }
  830. w.Flush()
  831. return nil
  832. }
  833. func (cli *DockerCli) CmdPort(args ...string) error {
  834. 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")
  835. if err := cmd.Parse(args); err != nil {
  836. return nil
  837. }
  838. if cmd.NArg() < 1 {
  839. cmd.Usage()
  840. return nil
  841. }
  842. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  843. if err != nil {
  844. return err
  845. }
  846. env := engine.Env{}
  847. if err := env.Decode(stream); err != nil {
  848. return err
  849. }
  850. ports := nat.PortMap{}
  851. if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil {
  852. return err
  853. }
  854. if cmd.NArg() == 2 {
  855. var (
  856. port = cmd.Arg(1)
  857. proto = "tcp"
  858. parts = strings.SplitN(port, "/", 2)
  859. )
  860. if len(parts) == 2 && len(parts[1]) != 0 {
  861. port = parts[0]
  862. proto = parts[1]
  863. }
  864. natPort := port + "/" + proto
  865. if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
  866. for _, frontend := range frontends {
  867. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  868. }
  869. return nil
  870. }
  871. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
  872. }
  873. for from, frontends := range ports {
  874. for _, frontend := range frontends {
  875. fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
  876. }
  877. }
  878. return nil
  879. }
  880. // 'docker rmi IMAGE' removes all images with the name IMAGE
  881. func (cli *DockerCli) CmdRmi(args ...string) error {
  882. var (
  883. cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  884. force = cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image")
  885. noprune = cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents")
  886. )
  887. if err := cmd.Parse(args); err != nil {
  888. return nil
  889. }
  890. if cmd.NArg() < 1 {
  891. cmd.Usage()
  892. return nil
  893. }
  894. v := url.Values{}
  895. if *force {
  896. v.Set("force", "1")
  897. }
  898. if *noprune {
  899. v.Set("noprune", "1")
  900. }
  901. var encounteredError error
  902. for _, name := range cmd.Args() {
  903. body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
  904. if err != nil {
  905. fmt.Fprintf(cli.err, "%s\n", err)
  906. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  907. } else {
  908. outs := engine.NewTable("Created", 0)
  909. if _, err := outs.ReadListFrom(body); err != nil {
  910. fmt.Fprintf(cli.err, "%s\n", err)
  911. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  912. continue
  913. }
  914. for _, out := range outs.Data {
  915. if out.Get("Deleted") != "" {
  916. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted"))
  917. } else {
  918. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged"))
  919. }
  920. }
  921. }
  922. }
  923. return encounteredError
  924. }
  925. func (cli *DockerCli) CmdHistory(args ...string) error {
  926. cmd := cli.Subcmd("history", "IMAGE", "Show the history of an image")
  927. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  928. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  929. if err := cmd.Parse(args); err != nil {
  930. return nil
  931. }
  932. if cmd.NArg() != 1 {
  933. cmd.Usage()
  934. return nil
  935. }
  936. body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
  937. if err != nil {
  938. return err
  939. }
  940. outs := engine.NewTable("Created", 0)
  941. if _, err := outs.ReadListFrom(body); err != nil {
  942. return err
  943. }
  944. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  945. if !*quiet {
  946. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  947. }
  948. for _, out := range outs.Data {
  949. outID := out.Get("Id")
  950. if !*quiet {
  951. if *noTrunc {
  952. fmt.Fprintf(w, "%s\t", outID)
  953. } else {
  954. fmt.Fprintf(w, "%s\t", utils.TruncateID(outID))
  955. }
  956. fmt.Fprintf(w, "%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))))
  957. if *noTrunc {
  958. fmt.Fprintf(w, "%s\t", out.Get("CreatedBy"))
  959. } else {
  960. fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45))
  961. }
  962. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("Size")))
  963. } else {
  964. if *noTrunc {
  965. fmt.Fprintln(w, outID)
  966. } else {
  967. fmt.Fprintln(w, utils.TruncateID(outID))
  968. }
  969. }
  970. }
  971. w.Flush()
  972. return nil
  973. }
  974. func (cli *DockerCli) CmdRm(args ...string) error {
  975. cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers")
  976. v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container")
  977. link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link and not the underlying container")
  978. force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)")
  979. if err := cmd.Parse(args); err != nil {
  980. return nil
  981. }
  982. if cmd.NArg() < 1 {
  983. cmd.Usage()
  984. return nil
  985. }
  986. val := url.Values{}
  987. if *v {
  988. val.Set("v", "1")
  989. }
  990. if *link {
  991. val.Set("link", "1")
  992. }
  993. if *force {
  994. val.Set("force", "1")
  995. }
  996. var encounteredError error
  997. for _, name := range cmd.Args() {
  998. _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false))
  999. if err != nil {
  1000. fmt.Fprintf(cli.err, "%s\n", err)
  1001. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  1002. } else {
  1003. fmt.Fprintf(cli.out, "%s\n", name)
  1004. }
  1005. }
  1006. return encounteredError
  1007. }
  1008. // 'docker kill NAME' kills a running container
  1009. func (cli *DockerCli) CmdKill(args ...string) error {
  1010. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container using SIGKILL or a specified signal")
  1011. signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container")
  1012. if err := cmd.Parse(args); err != nil {
  1013. return nil
  1014. }
  1015. if cmd.NArg() < 1 {
  1016. cmd.Usage()
  1017. return nil
  1018. }
  1019. var encounteredError error
  1020. for _, name := range cmd.Args() {
  1021. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil {
  1022. fmt.Fprintf(cli.err, "%s\n", err)
  1023. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  1024. } else {
  1025. fmt.Fprintf(cli.out, "%s\n", name)
  1026. }
  1027. }
  1028. return encounteredError
  1029. }
  1030. func (cli *DockerCli) CmdImport(args ...string) error {
  1031. 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.")
  1032. if err := cmd.Parse(args); err != nil {
  1033. return nil
  1034. }
  1035. if cmd.NArg() < 1 {
  1036. cmd.Usage()
  1037. return nil
  1038. }
  1039. var (
  1040. v = url.Values{}
  1041. src = cmd.Arg(0)
  1042. repository = cmd.Arg(1)
  1043. )
  1044. v.Set("fromSrc", src)
  1045. v.Set("repo", repository)
  1046. if cmd.NArg() == 3 {
  1047. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  1048. v.Set("tag", cmd.Arg(2))
  1049. }
  1050. if repository != "" {
  1051. //Check if the given image name can be resolved
  1052. repo, _ := parsers.ParseRepositoryTag(repository)
  1053. if _, _, err := registry.ResolveRepositoryName(repo); err != nil {
  1054. return err
  1055. }
  1056. }
  1057. var in io.Reader
  1058. if src == "-" {
  1059. in = cli.in
  1060. }
  1061. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  1062. }
  1063. func (cli *DockerCli) CmdPush(args ...string) error {
  1064. cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry")
  1065. if err := cmd.Parse(args); err != nil {
  1066. return nil
  1067. }
  1068. name := cmd.Arg(0)
  1069. if name == "" {
  1070. cmd.Usage()
  1071. return nil
  1072. }
  1073. cli.LoadConfigFile()
  1074. remote, tag := parsers.ParseRepositoryTag(name)
  1075. // Resolve the Repository name from fqn to hostname + name
  1076. hostname, _, err := registry.ResolveRepositoryName(remote)
  1077. if err != nil {
  1078. return err
  1079. }
  1080. // Resolve the Auth config relevant for this server
  1081. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1082. // If we're not using a custom registry, we know the restrictions
  1083. // applied to repository names and can warn the user in advance.
  1084. // Custom repositories can have different rules, and we must also
  1085. // allow pushing by image ID.
  1086. if len(strings.SplitN(name, "/", 2)) == 1 {
  1087. username := cli.configFile.Configs[registry.IndexServerAddress()].Username
  1088. if username == "" {
  1089. username = "<user>"
  1090. }
  1091. return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  1092. }
  1093. v := url.Values{}
  1094. v.Set("tag", tag)
  1095. push := func(authConfig registry.AuthConfig) error {
  1096. buf, err := json.Marshal(authConfig)
  1097. if err != nil {
  1098. return err
  1099. }
  1100. registryAuthHeader := []string{
  1101. base64.URLEncoding.EncodeToString(buf),
  1102. }
  1103. return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  1104. "X-Registry-Auth": registryAuthHeader,
  1105. })
  1106. }
  1107. if err := push(authConfig); err != nil {
  1108. if strings.Contains(err.Error(), "Status 401") {
  1109. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  1110. if err := cli.CmdLogin(hostname); err != nil {
  1111. return err
  1112. }
  1113. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1114. return push(authConfig)
  1115. }
  1116. return err
  1117. }
  1118. return nil
  1119. }
  1120. func (cli *DockerCli) CmdPull(args ...string) error {
  1121. cmd := cli.Subcmd("pull", "NAME[:TAG]", "Pull an image or a repository from the registry")
  1122. allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository")
  1123. if err := cmd.Parse(args); err != nil {
  1124. return nil
  1125. }
  1126. if cmd.NArg() != 1 {
  1127. cmd.Usage()
  1128. return nil
  1129. }
  1130. var (
  1131. v = url.Values{}
  1132. remote = cmd.Arg(0)
  1133. newRemote = remote
  1134. )
  1135. taglessRemote, tag := parsers.ParseRepositoryTag(remote)
  1136. if tag == "" && !*allTags {
  1137. newRemote = taglessRemote + ":" + graph.DEFAULTTAG
  1138. }
  1139. if tag != "" && *allTags {
  1140. return fmt.Errorf("tag can't be used with --all-tags/-a")
  1141. }
  1142. v.Set("fromImage", newRemote)
  1143. // Resolve the Repository name from fqn to hostname + name
  1144. hostname, _, err := registry.ResolveRepositoryName(taglessRemote)
  1145. if err != nil {
  1146. return err
  1147. }
  1148. cli.LoadConfigFile()
  1149. // Resolve the Auth config relevant for this server
  1150. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1151. pull := func(authConfig registry.AuthConfig) error {
  1152. buf, err := json.Marshal(authConfig)
  1153. if err != nil {
  1154. return err
  1155. }
  1156. registryAuthHeader := []string{
  1157. base64.URLEncoding.EncodeToString(buf),
  1158. }
  1159. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  1160. "X-Registry-Auth": registryAuthHeader,
  1161. })
  1162. }
  1163. if err := pull(authConfig); err != nil {
  1164. if strings.Contains(err.Error(), "Status 401") {
  1165. fmt.Fprintln(cli.out, "\nPlease login prior to pull:")
  1166. if err := cli.CmdLogin(hostname); err != nil {
  1167. return err
  1168. }
  1169. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1170. return pull(authConfig)
  1171. }
  1172. return err
  1173. }
  1174. return nil
  1175. }
  1176. func (cli *DockerCli) CmdImages(args ...string) error {
  1177. cmd := cli.Subcmd("images", "[NAME]", "List images")
  1178. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  1179. all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (by default filter out the intermediate image layers)")
  1180. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1181. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1182. flViz := cmd.Bool([]string{"#v", "#viz", "#-viz"}, false, "Output graph in graphviz format")
  1183. flTree := cmd.Bool([]string{"#t", "#tree", "#-tree"}, false, "Output graph in tree format")
  1184. flFilter := opts.NewListOpts(nil)
  1185. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values (i.e. 'dangling=true')")
  1186. if err := cmd.Parse(args); err != nil {
  1187. return nil
  1188. }
  1189. if cmd.NArg() > 1 {
  1190. cmd.Usage()
  1191. return nil
  1192. }
  1193. // Consolidate all filter flags, and sanity check them early.
  1194. // They'll get process in the daemon/server.
  1195. imageFilterArgs := filters.Args{}
  1196. for _, f := range flFilter.GetAll() {
  1197. var err error
  1198. imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs)
  1199. if err != nil {
  1200. return err
  1201. }
  1202. }
  1203. matchName := cmd.Arg(0)
  1204. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1205. if *flViz || *flTree {
  1206. v := url.Values{
  1207. "all": []string{"1"},
  1208. }
  1209. if len(imageFilterArgs) > 0 {
  1210. filterJson, err := filters.ToParam(imageFilterArgs)
  1211. if err != nil {
  1212. return err
  1213. }
  1214. v.Set("filters", filterJson)
  1215. }
  1216. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1217. if err != nil {
  1218. return err
  1219. }
  1220. outs := engine.NewTable("Created", 0)
  1221. if _, err := outs.ReadListFrom(body); err != nil {
  1222. return err
  1223. }
  1224. var (
  1225. printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)
  1226. startImage *engine.Env
  1227. roots = engine.NewTable("Created", outs.Len())
  1228. byParent = make(map[string]*engine.Table)
  1229. )
  1230. for _, image := range outs.Data {
  1231. if image.Get("ParentId") == "" {
  1232. roots.Add(image)
  1233. } else {
  1234. if children, exists := byParent[image.Get("ParentId")]; exists {
  1235. children.Add(image)
  1236. } else {
  1237. byParent[image.Get("ParentId")] = engine.NewTable("Created", 1)
  1238. byParent[image.Get("ParentId")].Add(image)
  1239. }
  1240. }
  1241. if matchName != "" {
  1242. if matchName == image.Get("Id") || matchName == utils.TruncateID(image.Get("Id")) {
  1243. startImage = image
  1244. }
  1245. for _, repotag := range image.GetList("RepoTags") {
  1246. if repotag == matchName {
  1247. startImage = image
  1248. }
  1249. }
  1250. }
  1251. }
  1252. if *flViz {
  1253. fmt.Fprintf(cli.out, "digraph docker {\n")
  1254. printNode = (*DockerCli).printVizNode
  1255. } else {
  1256. printNode = (*DockerCli).printTreeNode
  1257. }
  1258. if startImage != nil {
  1259. root := engine.NewTable("Created", 1)
  1260. root.Add(startImage)
  1261. cli.WalkTree(*noTrunc, root, byParent, "", printNode)
  1262. } else if matchName == "" {
  1263. cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
  1264. }
  1265. if *flViz {
  1266. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1267. }
  1268. } else {
  1269. v := url.Values{}
  1270. if len(imageFilterArgs) > 0 {
  1271. filterJson, err := filters.ToParam(imageFilterArgs)
  1272. if err != nil {
  1273. return err
  1274. }
  1275. v.Set("filters", filterJson)
  1276. }
  1277. if cmd.NArg() == 1 {
  1278. // FIXME rename this parameter, to not be confused with the filters flag
  1279. v.Set("filter", matchName)
  1280. }
  1281. if *all {
  1282. v.Set("all", "1")
  1283. }
  1284. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1285. if err != nil {
  1286. return err
  1287. }
  1288. outs := engine.NewTable("Created", 0)
  1289. if _, err := outs.ReadListFrom(body); err != nil {
  1290. return err
  1291. }
  1292. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1293. if !*quiet {
  1294. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1295. }
  1296. for _, out := range outs.Data {
  1297. for _, repotag := range out.GetList("RepoTags") {
  1298. repo, tag := parsers.ParseRepositoryTag(repotag)
  1299. outID := out.Get("Id")
  1300. if !*noTrunc {
  1301. outID = utils.TruncateID(outID)
  1302. }
  1303. if !*quiet {
  1304. 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")))
  1305. } else {
  1306. fmt.Fprintln(w, outID)
  1307. }
  1308. }
  1309. }
  1310. if !*quiet {
  1311. w.Flush()
  1312. }
  1313. }
  1314. return nil
  1315. }
  1316. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1317. 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)) {
  1318. length := images.Len()
  1319. if length > 1 {
  1320. for index, image := range images.Data {
  1321. if index+1 == length {
  1322. printNode(cli, noTrunc, image, prefix+"└─")
  1323. if subimages, exists := byParent[image.Get("Id")]; exists {
  1324. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1325. }
  1326. } else {
  1327. printNode(cli, noTrunc, image, prefix+"\u251C─")
  1328. if subimages, exists := byParent[image.Get("Id")]; exists {
  1329. cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
  1330. }
  1331. }
  1332. }
  1333. } else {
  1334. for _, image := range images.Data {
  1335. printNode(cli, noTrunc, image, prefix+"└─")
  1336. if subimages, exists := byParent[image.Get("Id")]; exists {
  1337. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1338. }
  1339. }
  1340. }
  1341. }
  1342. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1343. func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) {
  1344. var (
  1345. imageID string
  1346. parentID string
  1347. )
  1348. if noTrunc {
  1349. imageID = image.Get("Id")
  1350. parentID = image.Get("ParentId")
  1351. } else {
  1352. imageID = utils.TruncateID(image.Get("Id"))
  1353. parentID = utils.TruncateID(image.Get("ParentId"))
  1354. }
  1355. if parentID == "" {
  1356. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1357. } else {
  1358. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1359. }
  1360. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1361. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1362. imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n"))
  1363. }
  1364. }
  1365. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1366. func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) {
  1367. var imageID string
  1368. if noTrunc {
  1369. imageID = image.Get("Id")
  1370. } else {
  1371. imageID = utils.TruncateID(image.Get("Id"))
  1372. }
  1373. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, units.HumanSize(image.GetInt64("VirtualSize")))
  1374. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1375. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", "))
  1376. } else {
  1377. fmt.Fprint(cli.out, "\n")
  1378. }
  1379. }
  1380. func (cli *DockerCli) CmdPs(args ...string) error {
  1381. var (
  1382. err error
  1383. psFilterArgs = filters.Args{}
  1384. v = url.Values{}
  1385. cmd = cli.Subcmd("ps", "", "List containers")
  1386. quiet = cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
  1387. size = cmd.Bool([]string{"s", "-size"}, false, "Display total file sizes")
  1388. all = cmd.Bool([]string{"a", "-all"}, false, "Show all containers. Only running containers are shown by default.")
  1389. noTrunc = cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1390. nLatest = cmd.Bool([]string{"l", "-latest"}, false, "Show only the latest created container, include non-running ones.")
  1391. since = cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show only containers created since Id or Name, include non-running ones.")
  1392. before = cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name, include non-running ones.")
  1393. last = cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running ones.")
  1394. flFilter = opts.NewListOpts(nil)
  1395. )
  1396. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values. Valid filters:\nexited=<int> - containers with exit code of <int>\nstatus=(restarting|running|paused|exited)")
  1397. if err := cmd.Parse(args); err != nil {
  1398. return nil
  1399. }
  1400. if *last == -1 && *nLatest {
  1401. *last = 1
  1402. }
  1403. if *all {
  1404. v.Set("all", "1")
  1405. }
  1406. if *last != -1 {
  1407. v.Set("limit", strconv.Itoa(*last))
  1408. }
  1409. if *since != "" {
  1410. v.Set("since", *since)
  1411. }
  1412. if *before != "" {
  1413. v.Set("before", *before)
  1414. }
  1415. if *size {
  1416. v.Set("size", "1")
  1417. }
  1418. // Consolidate all filter flags, and sanity check them.
  1419. // They'll get processed in the daemon/server.
  1420. for _, f := range flFilter.GetAll() {
  1421. if psFilterArgs, err = filters.ParseFlag(f, psFilterArgs); err != nil {
  1422. return err
  1423. }
  1424. }
  1425. if len(psFilterArgs) > 0 {
  1426. filterJson, err := filters.ToParam(psFilterArgs)
  1427. if err != nil {
  1428. return err
  1429. }
  1430. v.Set("filters", filterJson)
  1431. }
  1432. body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
  1433. if err != nil {
  1434. return err
  1435. }
  1436. outs := engine.NewTable("Created", 0)
  1437. if _, err := outs.ReadListFrom(body); err != nil {
  1438. return err
  1439. }
  1440. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1441. if !*quiet {
  1442. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1443. if *size {
  1444. fmt.Fprintln(w, "\tSIZE")
  1445. } else {
  1446. fmt.Fprint(w, "\n")
  1447. }
  1448. }
  1449. stripNamePrefix := func(ss []string) []string {
  1450. for i, s := range ss {
  1451. ss[i] = s[1:]
  1452. }
  1453. return ss
  1454. }
  1455. for _, out := range outs.Data {
  1456. outID := out.Get("Id")
  1457. if !*noTrunc {
  1458. outID = utils.TruncateID(outID)
  1459. }
  1460. if *quiet {
  1461. fmt.Fprintln(w, outID)
  1462. continue
  1463. }
  1464. var (
  1465. outNames = stripNamePrefix(out.GetList("Names"))
  1466. outCommand = strconv.Quote(out.Get("Command"))
  1467. ports = engine.NewTable("", 0)
  1468. )
  1469. if !*noTrunc {
  1470. outCommand = utils.Trunc(outCommand, 20)
  1471. // only display the default name for the container with notrunc is passed
  1472. for _, name := range outNames {
  1473. if len(strings.Split(name, "/")) == 1 {
  1474. outNames = []string{name}
  1475. break
  1476. }
  1477. }
  1478. }
  1479. ports.ReadListFrom([]byte(out.Get("Ports")))
  1480. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", outID, out.Get("Image"), outCommand,
  1481. units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))),
  1482. out.Get("Status"), api.DisplayablePorts(ports), strings.Join(outNames, ","))
  1483. if *size {
  1484. if out.GetInt("SizeRootFs") > 0 {
  1485. fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(out.GetInt64("SizeRw")), units.HumanSize(out.GetInt64("SizeRootFs")))
  1486. } else {
  1487. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("SizeRw")))
  1488. }
  1489. continue
  1490. }
  1491. fmt.Fprint(w, "\n")
  1492. }
  1493. if !*quiet {
  1494. w.Flush()
  1495. }
  1496. return nil
  1497. }
  1498. func (cli *DockerCli) CmdCommit(args ...string) error {
  1499. cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1500. flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit")
  1501. flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
  1502. flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
  1503. // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands.
  1504. 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")
  1505. if err := cmd.Parse(args); err != nil {
  1506. return nil
  1507. }
  1508. var (
  1509. name = cmd.Arg(0)
  1510. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1511. )
  1512. if name == "" || len(cmd.Args()) > 2 {
  1513. cmd.Usage()
  1514. return nil
  1515. }
  1516. //Check if the given image name can be resolved
  1517. if repository != "" {
  1518. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1519. return err
  1520. }
  1521. }
  1522. v := url.Values{}
  1523. v.Set("container", name)
  1524. v.Set("repo", repository)
  1525. v.Set("tag", tag)
  1526. v.Set("comment", *flComment)
  1527. v.Set("author", *flAuthor)
  1528. if *flPause != true {
  1529. v.Set("pause", "0")
  1530. }
  1531. var (
  1532. config *runconfig.Config
  1533. env engine.Env
  1534. )
  1535. if *flConfig != "" {
  1536. config = &runconfig.Config{}
  1537. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1538. return err
  1539. }
  1540. }
  1541. stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false)
  1542. if err != nil {
  1543. return err
  1544. }
  1545. if err := env.Decode(stream); err != nil {
  1546. return err
  1547. }
  1548. fmt.Fprintf(cli.out, "%s\n", env.Get("Id"))
  1549. return nil
  1550. }
  1551. func (cli *DockerCli) CmdEvents(args ...string) error {
  1552. cmd := cli.Subcmd("events", "", "Get real time events from the server")
  1553. since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp")
  1554. until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp")
  1555. if err := cmd.Parse(args); err != nil {
  1556. return nil
  1557. }
  1558. if cmd.NArg() != 0 {
  1559. cmd.Usage()
  1560. return nil
  1561. }
  1562. var (
  1563. v = url.Values{}
  1564. loc = time.FixedZone(time.Now().Zone())
  1565. )
  1566. var setTime = func(key, value string) {
  1567. format := timeutils.RFC3339NanoFixed
  1568. if len(value) < len(format) {
  1569. format = format[:len(value)]
  1570. }
  1571. if t, err := time.ParseInLocation(format, value, loc); err == nil {
  1572. v.Set(key, strconv.FormatInt(t.Unix(), 10))
  1573. } else {
  1574. v.Set(key, value)
  1575. }
  1576. }
  1577. if *since != "" {
  1578. setTime("since", *since)
  1579. }
  1580. if *until != "" {
  1581. setTime("until", *until)
  1582. }
  1583. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1584. return err
  1585. }
  1586. return nil
  1587. }
  1588. func (cli *DockerCli) CmdExport(args ...string) error {
  1589. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1590. if err := cmd.Parse(args); err != nil {
  1591. return nil
  1592. }
  1593. if cmd.NArg() != 1 {
  1594. cmd.Usage()
  1595. return nil
  1596. }
  1597. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1598. return err
  1599. }
  1600. return nil
  1601. }
  1602. func (cli *DockerCli) CmdDiff(args ...string) error {
  1603. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1604. if err := cmd.Parse(args); err != nil {
  1605. return nil
  1606. }
  1607. if cmd.NArg() != 1 {
  1608. cmd.Usage()
  1609. return nil
  1610. }
  1611. body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
  1612. if err != nil {
  1613. return err
  1614. }
  1615. outs := engine.NewTable("", 0)
  1616. if _, err := outs.ReadListFrom(body); err != nil {
  1617. return err
  1618. }
  1619. for _, change := range outs.Data {
  1620. var kind string
  1621. switch change.GetInt("Kind") {
  1622. case archive.ChangeModify:
  1623. kind = "C"
  1624. case archive.ChangeAdd:
  1625. kind = "A"
  1626. case archive.ChangeDelete:
  1627. kind = "D"
  1628. }
  1629. fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
  1630. }
  1631. return nil
  1632. }
  1633. func (cli *DockerCli) CmdLogs(args ...string) error {
  1634. var (
  1635. cmd = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1636. follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
  1637. times = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
  1638. tail = cmd.String([]string{"-tail"}, "all", "Output the specified number of lines at the end of logs (defaults to all logs)")
  1639. )
  1640. if err := cmd.Parse(args); err != nil {
  1641. return nil
  1642. }
  1643. if cmd.NArg() != 1 {
  1644. cmd.Usage()
  1645. return nil
  1646. }
  1647. name := cmd.Arg(0)
  1648. stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1649. if err != nil {
  1650. return err
  1651. }
  1652. env := engine.Env{}
  1653. if err := env.Decode(stream); err != nil {
  1654. return err
  1655. }
  1656. v := url.Values{}
  1657. v.Set("stdout", "1")
  1658. v.Set("stderr", "1")
  1659. if *times {
  1660. v.Set("timestamps", "1")
  1661. }
  1662. if *follow {
  1663. v.Set("follow", "1")
  1664. }
  1665. v.Set("tail", *tail)
  1666. return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil)
  1667. }
  1668. func (cli *DockerCli) CmdAttach(args ...string) error {
  1669. var (
  1670. cmd = cli.Subcmd("attach", "CONTAINER", "Attach to a running container")
  1671. noStdin = cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN")
  1672. 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.")
  1673. )
  1674. if err := cmd.Parse(args); err != nil {
  1675. return nil
  1676. }
  1677. if cmd.NArg() != 1 {
  1678. cmd.Usage()
  1679. return nil
  1680. }
  1681. name := cmd.Arg(0)
  1682. stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1683. if err != nil {
  1684. return err
  1685. }
  1686. env := engine.Env{}
  1687. if err := env.Decode(stream); err != nil {
  1688. return err
  1689. }
  1690. if !env.GetSubEnv("State").GetBool("Running") {
  1691. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  1692. }
  1693. var (
  1694. config = env.GetSubEnv("Config")
  1695. tty = config.GetBool("Tty")
  1696. )
  1697. if tty && cli.isTerminalOut {
  1698. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  1699. log.Debugf("Error monitoring TTY size: %s", err)
  1700. }
  1701. }
  1702. var in io.ReadCloser
  1703. v := url.Values{}
  1704. v.Set("stream", "1")
  1705. if !*noStdin && config.GetBool("OpenStdin") {
  1706. v.Set("stdin", "1")
  1707. in = cli.in
  1708. }
  1709. v.Set("stdout", "1")
  1710. v.Set("stderr", "1")
  1711. if *proxy && !tty {
  1712. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1713. defer signal.StopCatch(sigc)
  1714. }
  1715. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil); err != nil {
  1716. return err
  1717. }
  1718. _, status, err := getExitCode(cli, cmd.Arg(0))
  1719. if err != nil {
  1720. return err
  1721. }
  1722. if status != 0 {
  1723. return &utils.StatusError{StatusCode: status}
  1724. }
  1725. return nil
  1726. }
  1727. func (cli *DockerCli) CmdSearch(args ...string) error {
  1728. cmd := cli.Subcmd("search", "TERM", "Search the Docker Hub for images")
  1729. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1730. trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds")
  1731. automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds")
  1732. stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars")
  1733. if err := cmd.Parse(args); err != nil {
  1734. return nil
  1735. }
  1736. if cmd.NArg() != 1 {
  1737. cmd.Usage()
  1738. return nil
  1739. }
  1740. v := url.Values{}
  1741. v.Set("term", cmd.Arg(0))
  1742. body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true))
  1743. if err != nil {
  1744. return err
  1745. }
  1746. outs := engine.NewTable("star_count", 0)
  1747. if _, err := outs.ReadListFrom(body); err != nil {
  1748. return err
  1749. }
  1750. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1751. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n")
  1752. for _, out := range outs.Data {
  1753. if ((*automated || *trusted) && (!out.GetBool("is_trusted") && !out.GetBool("is_automated"))) || (*stars > out.GetInt("star_count")) {
  1754. continue
  1755. }
  1756. desc := strings.Replace(out.Get("description"), "\n", " ", -1)
  1757. desc = strings.Replace(desc, "\r", " ", -1)
  1758. if !*noTrunc && len(desc) > 45 {
  1759. desc = utils.Trunc(desc, 42) + "..."
  1760. }
  1761. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count"))
  1762. if out.GetBool("is_official") {
  1763. fmt.Fprint(w, "[OK]")
  1764. }
  1765. fmt.Fprint(w, "\t")
  1766. if out.GetBool("is_automated") || out.GetBool("is_trusted") {
  1767. fmt.Fprint(w, "[OK]")
  1768. }
  1769. fmt.Fprint(w, "\n")
  1770. }
  1771. w.Flush()
  1772. return nil
  1773. }
  1774. // Ports type - Used to parse multiple -p flags
  1775. type ports []int
  1776. func (cli *DockerCli) CmdTag(args ...string) error {
  1777. cmd := cli.Subcmd("tag", "IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository")
  1778. force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force")
  1779. if err := cmd.Parse(args); err != nil {
  1780. return nil
  1781. }
  1782. if cmd.NArg() != 2 {
  1783. cmd.Usage()
  1784. return nil
  1785. }
  1786. var (
  1787. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1788. v = url.Values{}
  1789. )
  1790. //Check if the given image name can be resolved
  1791. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1792. return err
  1793. }
  1794. v.Set("repo", repository)
  1795. v.Set("tag", tag)
  1796. if *force {
  1797. v.Set("force", "1")
  1798. }
  1799. if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil {
  1800. return err
  1801. }
  1802. return nil
  1803. }
  1804. func (cli *DockerCli) pullImage(image string) error {
  1805. return cli.pullImageCustomOut(image, cli.out)
  1806. }
  1807. func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error {
  1808. v := url.Values{}
  1809. repos, tag := parsers.ParseRepositoryTag(image)
  1810. // pull only the image tagged 'latest' if no tag was specified
  1811. if tag == "" {
  1812. tag = graph.DEFAULTTAG
  1813. }
  1814. v.Set("fromImage", repos)
  1815. v.Set("tag", tag)
  1816. // Resolve the Repository name from fqn to hostname + name
  1817. hostname, _, err := registry.ResolveRepositoryName(repos)
  1818. if err != nil {
  1819. return err
  1820. }
  1821. // Load the auth config file, to be able to pull the image
  1822. cli.LoadConfigFile()
  1823. // Resolve the Auth config relevant for this server
  1824. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1825. buf, err := json.Marshal(authConfig)
  1826. if err != nil {
  1827. return err
  1828. }
  1829. registryAuthHeader := []string{
  1830. base64.URLEncoding.EncodeToString(buf),
  1831. }
  1832. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1833. return err
  1834. }
  1835. return nil
  1836. }
  1837. type cidFile struct {
  1838. path string
  1839. file *os.File
  1840. written bool
  1841. }
  1842. func newCIDFile(path string) (*cidFile, error) {
  1843. if _, err := os.Stat(path); err == nil {
  1844. return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
  1845. }
  1846. f, err := os.Create(path)
  1847. if err != nil {
  1848. return nil, fmt.Errorf("Failed to create the container ID file: %s", err)
  1849. }
  1850. return &cidFile{path: path, file: f}, nil
  1851. }
  1852. func (cid *cidFile) Close() error {
  1853. cid.file.Close()
  1854. if !cid.written {
  1855. if err := os.Remove(cid.path); err != nil {
  1856. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  1857. }
  1858. }
  1859. return nil
  1860. }
  1861. func (cid *cidFile) Write(id string) error {
  1862. if _, err := cid.file.Write([]byte(id)); err != nil {
  1863. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  1864. }
  1865. cid.written = true
  1866. return nil
  1867. }
  1868. func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (engine.Env, error) {
  1869. containerValues := url.Values{}
  1870. if name != "" {
  1871. containerValues.Set("name", name)
  1872. }
  1873. mergedConfig := runconfig.MergeConfigs(config, hostConfig)
  1874. var containerIDFile *cidFile
  1875. if cidfile != "" {
  1876. var err error
  1877. if containerIDFile, err = newCIDFile(cidfile); err != nil {
  1878. return nil, err
  1879. }
  1880. defer containerIDFile.Close()
  1881. }
  1882. //create the container
  1883. stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false)
  1884. //if image not found try to pull it
  1885. if statusCode == 404 {
  1886. repo, tag := parsers.ParseRepositoryTag(config.Image)
  1887. if tag == "" {
  1888. tag = graph.DEFAULTTAG
  1889. }
  1890. fmt.Fprintf(cli.err, "Unable to find image '%s:%s' locally\n", repo, tag)
  1891. // we don't want to write to stdout anything apart from container.ID
  1892. if err = cli.pullImageCustomOut(config.Image, cli.err); err != nil {
  1893. return nil, err
  1894. }
  1895. // Retry
  1896. if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil {
  1897. return nil, err
  1898. }
  1899. } else if err != nil {
  1900. return nil, err
  1901. }
  1902. var result engine.Env
  1903. if err := result.Decode(stream); err != nil {
  1904. return nil, err
  1905. }
  1906. for _, warning := range result.GetList("Warnings") {
  1907. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1908. }
  1909. if containerIDFile != nil {
  1910. if err = containerIDFile.Write(result.Get("Id")); err != nil {
  1911. return nil, err
  1912. }
  1913. }
  1914. return result, nil
  1915. }
  1916. func (cli *DockerCli) CmdCreate(args ...string) error {
  1917. cmd := cli.Subcmd("create", "IMAGE [COMMAND] [ARG...]", "Create a new container")
  1918. // These are flags not stored in Config/HostConfig
  1919. var (
  1920. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  1921. )
  1922. config, hostConfig, cmd, err := runconfig.Parse(cmd, args)
  1923. if err != nil {
  1924. return err
  1925. }
  1926. if config.Image == "" {
  1927. cmd.Usage()
  1928. return nil
  1929. }
  1930. createResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1931. if err != nil {
  1932. return err
  1933. }
  1934. fmt.Fprintf(cli.out, "%s\n", createResult.Get("Id"))
  1935. return nil
  1936. }
  1937. func (cli *DockerCli) CmdRun(args ...string) error {
  1938. // FIXME: just use runconfig.Parse already
  1939. cmd := cli.Subcmd("run", "IMAGE [COMMAND] [ARG...]", "Run a command in a new container")
  1940. // These are flags not stored in Config/HostConfig
  1941. var (
  1942. flAutoRemove = cmd.Bool([]string{"#rm", "-rm"}, false, "Automatically remove the container when it exits (incompatible with -d)")
  1943. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run the container in the background and print the new container ID")
  1944. flSigProxy = cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy received signals to the process (non-TTY mode only). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.")
  1945. flName = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container")
  1946. flAttach *opts.ListOpts
  1947. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  1948. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  1949. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  1950. )
  1951. config, hostConfig, cmd, err := runconfig.Parse(cmd, args)
  1952. if err != nil {
  1953. return err
  1954. }
  1955. if config.Image == "" {
  1956. cmd.Usage()
  1957. return nil
  1958. }
  1959. if *flDetach {
  1960. if fl := cmd.Lookup("attach"); fl != nil {
  1961. flAttach = fl.Value.(*opts.ListOpts)
  1962. if flAttach.Len() != 0 {
  1963. return ErrConflictAttachDetach
  1964. }
  1965. }
  1966. if *flAutoRemove {
  1967. return ErrConflictDetachAutoRemove
  1968. }
  1969. config.AttachStdin = false
  1970. config.AttachStdout = false
  1971. config.AttachStderr = false
  1972. config.StdinOnce = false
  1973. }
  1974. // Disable flSigProxy when in TTY mode
  1975. sigProxy := *flSigProxy
  1976. if config.Tty {
  1977. sigProxy = false
  1978. }
  1979. runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1980. if err != nil {
  1981. return err
  1982. }
  1983. if sigProxy {
  1984. sigc := cli.forwardAllSignals(runResult.Get("Id"))
  1985. defer signal.StopCatch(sigc)
  1986. }
  1987. var (
  1988. waitDisplayId chan struct{}
  1989. errCh chan error
  1990. )
  1991. if !config.AttachStdout && !config.AttachStderr {
  1992. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  1993. waitDisplayId = make(chan struct{})
  1994. go func() {
  1995. defer close(waitDisplayId)
  1996. fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
  1997. }()
  1998. }
  1999. if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") {
  2000. return ErrConflictRestartPolicyAndAutoRemove
  2001. }
  2002. // We need to instantiate the chan because the select needs it. It can
  2003. // be closed but can't be uninitialized.
  2004. hijacked := make(chan io.Closer)
  2005. // Block the return until the chan gets closed
  2006. defer func() {
  2007. log.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  2008. if _, ok := <-hijacked; ok {
  2009. log.Errorf("Hijack did not finish (chan still open)")
  2010. }
  2011. }()
  2012. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  2013. var (
  2014. out, stderr io.Writer
  2015. in io.ReadCloser
  2016. v = url.Values{}
  2017. )
  2018. v.Set("stream", "1")
  2019. if config.AttachStdin {
  2020. v.Set("stdin", "1")
  2021. in = cli.in
  2022. }
  2023. if config.AttachStdout {
  2024. v.Set("stdout", "1")
  2025. out = cli.out
  2026. }
  2027. if config.AttachStderr {
  2028. v.Set("stderr", "1")
  2029. if config.Tty {
  2030. stderr = cli.out
  2031. } else {
  2032. stderr = cli.err
  2033. }
  2034. }
  2035. errCh = promise.Go(func() error {
  2036. return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
  2037. })
  2038. } else {
  2039. close(hijacked)
  2040. }
  2041. // Acknowledge the hijack before starting
  2042. select {
  2043. case closer := <-hijacked:
  2044. // Make sure that the hijack gets closed when returning (results
  2045. // in closing the hijack chan and freeing server's goroutines)
  2046. if closer != nil {
  2047. defer closer.Close()
  2048. }
  2049. case err := <-errCh:
  2050. if err != nil {
  2051. log.Debugf("Error hijack: %s", err)
  2052. return err
  2053. }
  2054. }
  2055. //start the container
  2056. if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", nil, false)); err != nil {
  2057. return err
  2058. }
  2059. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  2060. if err := cli.monitorTtySize(runResult.Get("Id"), false); err != nil {
  2061. log.Errorf("Error monitoring TTY size: %s", err)
  2062. }
  2063. }
  2064. if errCh != nil {
  2065. if err := <-errCh; err != nil {
  2066. log.Debugf("Error hijack: %s", err)
  2067. return err
  2068. }
  2069. }
  2070. // Detached mode: wait for the id to be displayed and return.
  2071. if !config.AttachStdout && !config.AttachStderr {
  2072. // Detached mode
  2073. <-waitDisplayId
  2074. return nil
  2075. }
  2076. var status int
  2077. // Attached mode
  2078. if *flAutoRemove {
  2079. // Autoremove: wait for the container to finish, retrieve
  2080. // the exit code and remove the container
  2081. if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
  2082. return err
  2083. }
  2084. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2085. return err
  2086. }
  2087. if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
  2088. return err
  2089. }
  2090. } else {
  2091. // No Autoremove: Simply retrieve the exit code
  2092. if !config.Tty {
  2093. // In non-TTY mode, we can't detach, so we must wait for container exit
  2094. if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
  2095. return err
  2096. }
  2097. } else {
  2098. // In TTY mode, there is a race: if the process dies too slowly, the state could
  2099. // be updated after the getExitCode call and result in the wrong exit code being reported
  2100. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2101. return err
  2102. }
  2103. }
  2104. }
  2105. if status != 0 {
  2106. return &utils.StatusError{StatusCode: status}
  2107. }
  2108. return nil
  2109. }
  2110. func (cli *DockerCli) CmdCp(args ...string) error {
  2111. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  2112. if err := cmd.Parse(args); err != nil {
  2113. return nil
  2114. }
  2115. if cmd.NArg() != 2 {
  2116. cmd.Usage()
  2117. return nil
  2118. }
  2119. var copyData engine.Env
  2120. info := strings.Split(cmd.Arg(0), ":")
  2121. if len(info) != 2 {
  2122. return fmt.Errorf("Error: Path not specified")
  2123. }
  2124. copyData.Set("Resource", info[1])
  2125. copyData.Set("HostPath", cmd.Arg(1))
  2126. stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false)
  2127. if stream != nil {
  2128. defer stream.Close()
  2129. }
  2130. if statusCode == 404 {
  2131. return fmt.Errorf("No such container: %v", info[0])
  2132. }
  2133. if err != nil {
  2134. return err
  2135. }
  2136. if statusCode == 200 {
  2137. if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
  2138. return err
  2139. }
  2140. }
  2141. return nil
  2142. }
  2143. func (cli *DockerCli) CmdSave(args ...string) error {
  2144. cmd := cli.Subcmd("save", "IMAGE [IMAGE...]", "Save an image(s) to a tar archive (streamed to STDOUT by default)")
  2145. outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT")
  2146. if err := cmd.Parse(args); err != nil {
  2147. return err
  2148. }
  2149. if cmd.NArg() < 1 {
  2150. cmd.Usage()
  2151. return nil
  2152. }
  2153. var (
  2154. output io.Writer = cli.out
  2155. err error
  2156. )
  2157. if *outfile != "" {
  2158. output, err = os.Create(*outfile)
  2159. if err != nil {
  2160. return err
  2161. }
  2162. } else if cli.isTerminalOut {
  2163. return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
  2164. }
  2165. if len(cmd.Args()) == 1 {
  2166. image := cmd.Arg(0)
  2167. if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil {
  2168. return err
  2169. }
  2170. } else {
  2171. v := url.Values{}
  2172. for _, arg := range cmd.Args() {
  2173. v.Add("names", arg)
  2174. }
  2175. if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil {
  2176. return err
  2177. }
  2178. }
  2179. return nil
  2180. }
  2181. func (cli *DockerCli) CmdLoad(args ...string) error {
  2182. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  2183. infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
  2184. if err := cmd.Parse(args); err != nil {
  2185. return err
  2186. }
  2187. if cmd.NArg() != 0 {
  2188. cmd.Usage()
  2189. return nil
  2190. }
  2191. var (
  2192. input io.Reader = cli.in
  2193. err error
  2194. )
  2195. if *infile != "" {
  2196. input, err = os.Open(*infile)
  2197. if err != nil {
  2198. return err
  2199. }
  2200. }
  2201. if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil {
  2202. return err
  2203. }
  2204. return nil
  2205. }
  2206. func (cli *DockerCli) CmdExec(args ...string) error {
  2207. cmd := cli.Subcmd("exec", "CONTAINER COMMAND [ARG...]", "Run a command in a running container")
  2208. execConfig, err := runconfig.ParseExec(cmd, args)
  2209. if err != nil {
  2210. return err
  2211. }
  2212. if execConfig.Container == "" {
  2213. cmd.Usage()
  2214. return nil
  2215. }
  2216. stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, false)
  2217. if err != nil {
  2218. return err
  2219. }
  2220. var execResult engine.Env
  2221. if err := execResult.Decode(stream); err != nil {
  2222. return err
  2223. }
  2224. execID := execResult.Get("Id")
  2225. if execID == "" {
  2226. fmt.Fprintf(cli.out, "exec ID empty")
  2227. return nil
  2228. }
  2229. if execConfig.Detach {
  2230. if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, false)); err != nil {
  2231. return err
  2232. }
  2233. return nil
  2234. }
  2235. // Interactive exec requested.
  2236. var (
  2237. out, stderr io.Writer
  2238. in io.ReadCloser
  2239. hijacked = make(chan io.Closer)
  2240. errCh chan error
  2241. )
  2242. // Block the return until the chan gets closed
  2243. defer func() {
  2244. log.Debugf("End of CmdExec(), Waiting for hijack to finish.")
  2245. if _, ok := <-hijacked; ok {
  2246. log.Errorf("Hijack did not finish (chan still open)")
  2247. }
  2248. }()
  2249. if execConfig.AttachStdin {
  2250. in = cli.in
  2251. }
  2252. if execConfig.AttachStdout {
  2253. out = cli.out
  2254. }
  2255. if execConfig.AttachStderr {
  2256. if execConfig.Tty {
  2257. stderr = cli.out
  2258. } else {
  2259. stderr = cli.err
  2260. }
  2261. }
  2262. errCh = promise.Go(func() error {
  2263. return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig)
  2264. })
  2265. // Acknowledge the hijack before starting
  2266. select {
  2267. case closer := <-hijacked:
  2268. // Make sure that hijack gets closed when returning. (result
  2269. // in closing hijack chan and freeing server's goroutines.
  2270. if closer != nil {
  2271. defer closer.Close()
  2272. }
  2273. case err := <-errCh:
  2274. if err != nil {
  2275. log.Debugf("Error hijack: %s", err)
  2276. return err
  2277. }
  2278. }
  2279. if execConfig.Tty && cli.isTerminalIn {
  2280. if err := cli.monitorTtySize(execID, true); err != nil {
  2281. log.Errorf("Error monitoring TTY size: %s", err)
  2282. }
  2283. }
  2284. if err := <-errCh; err != nil {
  2285. log.Debugf("Error hijack: %s", err)
  2286. return err
  2287. }
  2288. return nil
  2289. }