commands.go 59 KB

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