commands.go 59 KB

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