commands.go 59 KB

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