commands.go 63 KB

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