commands.go 63 KB

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