commands.go 67 KB

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