commands.go 68 KB

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