client.go 67 KB

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