commands.go 59 KB

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