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