commands.go 68 KB

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