commands.go 54 KB

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