commands.go 69 KB

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