commands.go 58 KB

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