commands.go 57 KB

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