commands.go 62 KB

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