commands.go 59 KB

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