commands.go 58 KB

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