commands.go 66 KB

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