commands.go 58 KB

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