commands.go 58 KB

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