commands.go 63 KB

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