commands.go 52 KB

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