commands.go 63 KB

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