commands.go 68 KB

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