commands.go 58 KB

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