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