commands.go 61 KB

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