client.go 68 KB

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