commands.go 59 KB

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