commands.go 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  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. if *attach || *openStdin {
  568. if cmd.NArg() > 1 {
  569. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  570. }
  571. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  572. if err != nil {
  573. return err
  574. }
  575. env := engine.Env{}
  576. if err := env.Decode(stream); err != nil {
  577. return err
  578. }
  579. config := env.GetSubEnv("Config")
  580. tty = config.GetBool("Tty")
  581. if !tty {
  582. sigc := cli.forwardAllSignals(cmd.Arg(0))
  583. defer signal.StopCatch(sigc)
  584. }
  585. var in io.ReadCloser
  586. v := url.Values{}
  587. v.Set("stream", "1")
  588. if *openStdin && config.GetBool("OpenStdin") {
  589. v.Set("stdin", "1")
  590. in = cli.in
  591. }
  592. v.Set("stdout", "1")
  593. v.Set("stderr", "1")
  594. cErr = promise.Go(func() error {
  595. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil)
  596. })
  597. }
  598. var encounteredError error
  599. for _, name := range cmd.Args() {
  600. _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, false))
  601. if err != nil {
  602. if !*attach || !*openStdin {
  603. fmt.Fprintf(cli.err, "%s\n", err)
  604. }
  605. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  606. } else {
  607. if !*attach || !*openStdin {
  608. fmt.Fprintf(cli.out, "%s\n", name)
  609. }
  610. }
  611. }
  612. if encounteredError != nil {
  613. if *openStdin || *attach {
  614. cli.in.Close()
  615. }
  616. return encounteredError
  617. }
  618. if *openStdin || *attach {
  619. if tty && cli.isTerminalOut {
  620. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  621. log.Errorf("Error monitoring TTY size: %s", err)
  622. }
  623. }
  624. if attchErr := <-cErr; attchErr != nil {
  625. return attchErr
  626. }
  627. _, status, err := getExitCode(cli, cmd.Arg(0))
  628. if err != nil {
  629. return err
  630. }
  631. if status != 0 {
  632. return &utils.StatusError{StatusCode: status}
  633. }
  634. }
  635. return nil
  636. }
  637. func (cli *DockerCli) CmdUnpause(args ...string) error {
  638. cmd := cli.Subcmd("unpause", "CONTAINER", "Unpause all processes within a container")
  639. if err := cmd.Parse(args); err != nil {
  640. return nil
  641. }
  642. if cmd.NArg() != 1 {
  643. cmd.Usage()
  644. return nil
  645. }
  646. var encounteredError error
  647. for _, name := range cmd.Args() {
  648. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, false)); err != nil {
  649. fmt.Fprintf(cli.err, "%s\n", err)
  650. encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name)
  651. } else {
  652. fmt.Fprintf(cli.out, "%s\n", name)
  653. }
  654. }
  655. return encounteredError
  656. }
  657. func (cli *DockerCli) CmdPause(args ...string) error {
  658. cmd := cli.Subcmd("pause", "CONTAINER", "Pause all processes within a container")
  659. if err := cmd.Parse(args); err != nil {
  660. return nil
  661. }
  662. if cmd.NArg() != 1 {
  663. cmd.Usage()
  664. return nil
  665. }
  666. var encounteredError error
  667. for _, name := range cmd.Args() {
  668. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, false)); err != nil {
  669. fmt.Fprintf(cli.err, "%s\n", err)
  670. encounteredError = fmt.Errorf("Error: failed to pause container named %s", name)
  671. } else {
  672. fmt.Fprintf(cli.out, "%s\n", name)
  673. }
  674. }
  675. return encounteredError
  676. }
  677. func (cli *DockerCli) CmdInspect(args ...string) error {
  678. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container or image")
  679. tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template.")
  680. if err := cmd.Parse(args); err != nil {
  681. return nil
  682. }
  683. if cmd.NArg() < 1 {
  684. cmd.Usage()
  685. return nil
  686. }
  687. var tmpl *template.Template
  688. if *tmplStr != "" {
  689. var err error
  690. if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil {
  691. fmt.Fprintf(cli.err, "Template parsing error: %v\n", err)
  692. return &utils.StatusError{StatusCode: 64,
  693. Status: "Template parsing error: " + err.Error()}
  694. }
  695. }
  696. indented := new(bytes.Buffer)
  697. indented.WriteByte('[')
  698. status := 0
  699. for _, name := range cmd.Args() {
  700. obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false))
  701. if err != nil {
  702. obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, false))
  703. if err != nil {
  704. if strings.Contains(err.Error(), "No such") {
  705. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  706. } else {
  707. fmt.Fprintf(cli.err, "%s", err)
  708. }
  709. status = 1
  710. continue
  711. }
  712. }
  713. if tmpl == nil {
  714. if err = json.Indent(indented, obj, "", " "); err != nil {
  715. fmt.Fprintf(cli.err, "%s\n", err)
  716. status = 1
  717. continue
  718. }
  719. } else {
  720. // Has template, will render
  721. var value interface{}
  722. if err := json.Unmarshal(obj, &value); err != nil {
  723. fmt.Fprintf(cli.err, "%s\n", err)
  724. status = 1
  725. continue
  726. }
  727. if err := tmpl.Execute(cli.out, value); err != nil {
  728. return err
  729. }
  730. cli.out.Write([]byte{'\n'})
  731. }
  732. indented.WriteString(",")
  733. }
  734. if indented.Len() > 1 {
  735. // Remove trailing ','
  736. indented.Truncate(indented.Len() - 1)
  737. }
  738. indented.WriteByte(']')
  739. if tmpl == nil {
  740. if _, err := io.Copy(cli.out, indented); err != nil {
  741. return err
  742. }
  743. }
  744. if status != 0 {
  745. return &utils.StatusError{StatusCode: status}
  746. }
  747. return nil
  748. }
  749. func (cli *DockerCli) CmdTop(args ...string) error {
  750. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Display the running processes of a container")
  751. if err := cmd.Parse(args); err != nil {
  752. return nil
  753. }
  754. if cmd.NArg() == 0 {
  755. cmd.Usage()
  756. return nil
  757. }
  758. val := url.Values{}
  759. if cmd.NArg() > 1 {
  760. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  761. }
  762. stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, false)
  763. if err != nil {
  764. return err
  765. }
  766. var procs engine.Env
  767. if err := procs.Decode(stream); err != nil {
  768. return err
  769. }
  770. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  771. fmt.Fprintln(w, strings.Join(procs.GetList("Titles"), "\t"))
  772. processes := [][]string{}
  773. if err := procs.GetJson("Processes", &processes); err != nil {
  774. return err
  775. }
  776. for _, proc := range processes {
  777. fmt.Fprintln(w, strings.Join(proc, "\t"))
  778. }
  779. w.Flush()
  780. return nil
  781. }
  782. func (cli *DockerCli) CmdPort(args ...string) error {
  783. cmd := cli.Subcmd("port", "CONTAINER [PRIVATE_PORT[/PROTO]]", "List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT")
  784. if err := cmd.Parse(args); err != nil {
  785. return nil
  786. }
  787. if cmd.NArg() < 1 {
  788. cmd.Usage()
  789. return nil
  790. }
  791. steam, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false)
  792. if err != nil {
  793. return err
  794. }
  795. env := engine.Env{}
  796. if err := env.Decode(steam); err != nil {
  797. return err
  798. }
  799. ports := nat.PortMap{}
  800. if err := env.GetSubEnv("NetworkSettings").GetJson("Ports", &ports); err != nil {
  801. return err
  802. }
  803. if cmd.NArg() == 2 {
  804. var (
  805. port = cmd.Arg(1)
  806. proto = "tcp"
  807. parts = strings.SplitN(port, "/", 2)
  808. )
  809. if len(parts) == 2 && len(parts[1]) != 0 {
  810. port = parts[0]
  811. proto = parts[1]
  812. }
  813. natPort := port + "/" + proto
  814. if frontends, exists := ports[nat.Port(port+"/"+proto)]; exists && frontends != nil {
  815. for _, frontend := range frontends {
  816. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  817. }
  818. return nil
  819. }
  820. return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0))
  821. }
  822. for from, frontends := range ports {
  823. for _, frontend := range frontends {
  824. fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIp, frontend.HostPort)
  825. }
  826. }
  827. return nil
  828. }
  829. // 'docker rmi IMAGE' removes all images with the name IMAGE
  830. func (cli *DockerCli) CmdRmi(args ...string) error {
  831. var (
  832. cmd = cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  833. force = cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image")
  834. noprune = cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents")
  835. )
  836. if err := cmd.Parse(args); err != nil {
  837. return nil
  838. }
  839. if cmd.NArg() < 1 {
  840. cmd.Usage()
  841. return nil
  842. }
  843. v := url.Values{}
  844. if *force {
  845. v.Set("force", "1")
  846. }
  847. if *noprune {
  848. v.Set("noprune", "1")
  849. }
  850. var encounteredError error
  851. for _, name := range cmd.Args() {
  852. body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false))
  853. if err != nil {
  854. fmt.Fprintf(cli.err, "%s\n", err)
  855. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  856. } else {
  857. outs := engine.NewTable("Created", 0)
  858. if _, err := outs.ReadListFrom(body); err != nil {
  859. fmt.Fprintf(cli.err, "%s\n", err)
  860. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  861. continue
  862. }
  863. for _, out := range outs.Data {
  864. if out.Get("Deleted") != "" {
  865. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Get("Deleted"))
  866. } else {
  867. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Get("Untagged"))
  868. }
  869. }
  870. }
  871. }
  872. return encounteredError
  873. }
  874. func (cli *DockerCli) CmdHistory(args ...string) error {
  875. cmd := cli.Subcmd("history", "IMAGE", "Show the history of an image")
  876. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  877. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  878. if err := cmd.Parse(args); err != nil {
  879. return nil
  880. }
  881. if cmd.NArg() != 1 {
  882. cmd.Usage()
  883. return nil
  884. }
  885. body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false))
  886. if err != nil {
  887. return err
  888. }
  889. outs := engine.NewTable("Created", 0)
  890. if _, err := outs.ReadListFrom(body); err != nil {
  891. return err
  892. }
  893. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  894. if !*quiet {
  895. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  896. }
  897. for _, out := range outs.Data {
  898. outID := out.Get("Id")
  899. if !*quiet {
  900. if *noTrunc {
  901. fmt.Fprintf(w, "%s\t", outID)
  902. } else {
  903. fmt.Fprintf(w, "%s\t", utils.TruncateID(outID))
  904. }
  905. fmt.Fprintf(w, "%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))))
  906. if *noTrunc {
  907. fmt.Fprintf(w, "%s\t", out.Get("CreatedBy"))
  908. } else {
  909. fmt.Fprintf(w, "%s\t", utils.Trunc(out.Get("CreatedBy"), 45))
  910. }
  911. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("Size")))
  912. } else {
  913. if *noTrunc {
  914. fmt.Fprintln(w, outID)
  915. } else {
  916. fmt.Fprintln(w, utils.TruncateID(outID))
  917. }
  918. }
  919. }
  920. w.Flush()
  921. return nil
  922. }
  923. func (cli *DockerCli) CmdRm(args ...string) error {
  924. cmd := cli.Subcmd("rm", "CONTAINER [CONTAINER...]", "Remove one or more containers")
  925. v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container")
  926. link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link and not the underlying container")
  927. force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)")
  928. if err := cmd.Parse(args); err != nil {
  929. return nil
  930. }
  931. if cmd.NArg() < 1 {
  932. cmd.Usage()
  933. return nil
  934. }
  935. val := url.Values{}
  936. if *v {
  937. val.Set("v", "1")
  938. }
  939. if *link {
  940. val.Set("link", "1")
  941. }
  942. if *force {
  943. val.Set("force", "1")
  944. }
  945. var encounteredError error
  946. for _, name := range cmd.Args() {
  947. _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false))
  948. if err != nil {
  949. fmt.Fprintf(cli.err, "%s\n", err)
  950. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  951. } else {
  952. fmt.Fprintf(cli.out, "%s\n", name)
  953. }
  954. }
  955. return encounteredError
  956. }
  957. // 'docker kill NAME' kills a running container
  958. func (cli *DockerCli) CmdKill(args ...string) error {
  959. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container using SIGKILL or a specified signal")
  960. signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container")
  961. if err := cmd.Parse(args); err != nil {
  962. return nil
  963. }
  964. if cmd.NArg() < 1 {
  965. cmd.Usage()
  966. return nil
  967. }
  968. var encounteredError error
  969. for _, name := range cmd.Args() {
  970. if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil {
  971. fmt.Fprintf(cli.err, "%s\n", err)
  972. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  973. } else {
  974. fmt.Fprintf(cli.out, "%s\n", name)
  975. }
  976. }
  977. return encounteredError
  978. }
  979. func (cli *DockerCli) CmdImport(args ...string) error {
  980. 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.")
  981. if err := cmd.Parse(args); err != nil {
  982. return nil
  983. }
  984. if cmd.NArg() < 1 {
  985. cmd.Usage()
  986. return nil
  987. }
  988. var (
  989. v = url.Values{}
  990. src = cmd.Arg(0)
  991. repository = cmd.Arg(1)
  992. )
  993. v.Set("fromSrc", src)
  994. v.Set("repo", repository)
  995. if cmd.NArg() == 3 {
  996. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  997. v.Set("tag", cmd.Arg(2))
  998. }
  999. if repository != "" {
  1000. //Check if the given image name can be resolved
  1001. repo, _ := parsers.ParseRepositoryTag(repository)
  1002. if _, _, err := registry.ResolveRepositoryName(repo); err != nil {
  1003. return err
  1004. }
  1005. }
  1006. var in io.Reader
  1007. if src == "-" {
  1008. in = cli.in
  1009. }
  1010. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  1011. }
  1012. func (cli *DockerCli) CmdPush(args ...string) error {
  1013. cmd := cli.Subcmd("push", "NAME[:TAG]", "Push an image or a repository to the registry")
  1014. if err := cmd.Parse(args); err != nil {
  1015. return nil
  1016. }
  1017. name := cmd.Arg(0)
  1018. if name == "" {
  1019. cmd.Usage()
  1020. return nil
  1021. }
  1022. cli.LoadConfigFile()
  1023. remote, tag := parsers.ParseRepositoryTag(name)
  1024. // Resolve the Repository name from fqn to hostname + name
  1025. hostname, _, err := registry.ResolveRepositoryName(remote)
  1026. if err != nil {
  1027. return err
  1028. }
  1029. // Resolve the Auth config relevant for this server
  1030. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1031. // If we're not using a custom registry, we know the restrictions
  1032. // applied to repository names and can warn the user in advance.
  1033. // Custom repositories can have different rules, and we must also
  1034. // allow pushing by image ID.
  1035. if len(strings.SplitN(name, "/", 2)) == 1 {
  1036. username := cli.configFile.Configs[registry.IndexServerAddress()].Username
  1037. if username == "" {
  1038. username = "<user>"
  1039. }
  1040. return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  1041. }
  1042. v := url.Values{}
  1043. v.Set("tag", tag)
  1044. push := func(authConfig registry.AuthConfig) error {
  1045. buf, err := json.Marshal(authConfig)
  1046. if err != nil {
  1047. return err
  1048. }
  1049. registryAuthHeader := []string{
  1050. base64.URLEncoding.EncodeToString(buf),
  1051. }
  1052. return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  1053. "X-Registry-Auth": registryAuthHeader,
  1054. })
  1055. }
  1056. if err := push(authConfig); err != nil {
  1057. if strings.Contains(err.Error(), "Status 401") {
  1058. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  1059. if err := cli.CmdLogin(hostname); err != nil {
  1060. return err
  1061. }
  1062. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1063. return push(authConfig)
  1064. }
  1065. return err
  1066. }
  1067. return nil
  1068. }
  1069. func (cli *DockerCli) CmdPull(args ...string) error {
  1070. cmd := cli.Subcmd("pull", "NAME[:TAG]", "Pull an image or a repository from the registry")
  1071. allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository")
  1072. if err := cmd.Parse(args); err != nil {
  1073. return nil
  1074. }
  1075. if cmd.NArg() != 1 {
  1076. cmd.Usage()
  1077. return nil
  1078. }
  1079. var (
  1080. v = url.Values{}
  1081. remote = cmd.Arg(0)
  1082. newRemote = remote
  1083. )
  1084. taglessRemote, tag := parsers.ParseRepositoryTag(remote)
  1085. if tag == "" && !*allTags {
  1086. newRemote = taglessRemote + ":latest"
  1087. }
  1088. if tag != "" && *allTags {
  1089. return fmt.Errorf("tag can't be used with --all-tags/-a")
  1090. }
  1091. v.Set("fromImage", newRemote)
  1092. // Resolve the Repository name from fqn to hostname + name
  1093. hostname, _, err := registry.ResolveRepositoryName(taglessRemote)
  1094. if err != nil {
  1095. return err
  1096. }
  1097. cli.LoadConfigFile()
  1098. // Resolve the Auth config relevant for this server
  1099. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1100. pull := func(authConfig registry.AuthConfig) error {
  1101. buf, err := json.Marshal(authConfig)
  1102. if err != nil {
  1103. return err
  1104. }
  1105. registryAuthHeader := []string{
  1106. base64.URLEncoding.EncodeToString(buf),
  1107. }
  1108. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  1109. "X-Registry-Auth": registryAuthHeader,
  1110. })
  1111. }
  1112. if err := pull(authConfig); err != nil {
  1113. if strings.Contains(err.Error(), "Status 401") {
  1114. fmt.Fprintln(cli.out, "\nPlease login prior to pull:")
  1115. if err := cli.CmdLogin(hostname); err != nil {
  1116. return err
  1117. }
  1118. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1119. return pull(authConfig)
  1120. }
  1121. return err
  1122. }
  1123. return nil
  1124. }
  1125. func (cli *DockerCli) CmdImages(args ...string) error {
  1126. cmd := cli.Subcmd("images", "[NAME]", "List images")
  1127. quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs")
  1128. all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (by default filter out the intermediate image layers)")
  1129. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1130. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1131. flViz := cmd.Bool([]string{"#v", "#viz", "#-viz"}, false, "Output graph in graphviz format")
  1132. flTree := cmd.Bool([]string{"#t", "#tree", "#-tree"}, false, "Output graph in tree format")
  1133. flFilter := opts.NewListOpts(nil)
  1134. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values (i.e. 'dangling=true')")
  1135. if err := cmd.Parse(args); err != nil {
  1136. return nil
  1137. }
  1138. if cmd.NArg() > 1 {
  1139. cmd.Usage()
  1140. return nil
  1141. }
  1142. // Consolidate all filter flags, and sanity check them early.
  1143. // They'll get process in the daemon/server.
  1144. imageFilterArgs := filters.Args{}
  1145. for _, f := range flFilter.GetAll() {
  1146. var err error
  1147. imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs)
  1148. if err != nil {
  1149. return err
  1150. }
  1151. }
  1152. matchName := cmd.Arg(0)
  1153. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1154. if *flViz || *flTree {
  1155. v := url.Values{
  1156. "all": []string{"1"},
  1157. }
  1158. if len(imageFilterArgs) > 0 {
  1159. filterJson, err := filters.ToParam(imageFilterArgs)
  1160. if err != nil {
  1161. return err
  1162. }
  1163. v.Set("filters", filterJson)
  1164. }
  1165. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1166. if err != nil {
  1167. return err
  1168. }
  1169. outs := engine.NewTable("Created", 0)
  1170. if _, err := outs.ReadListFrom(body); err != nil {
  1171. return err
  1172. }
  1173. var (
  1174. printNode func(cli *DockerCli, noTrunc bool, image *engine.Env, prefix string)
  1175. startImage *engine.Env
  1176. roots = engine.NewTable("Created", outs.Len())
  1177. byParent = make(map[string]*engine.Table)
  1178. )
  1179. for _, image := range outs.Data {
  1180. if image.Get("ParentId") == "" {
  1181. roots.Add(image)
  1182. } else {
  1183. if children, exists := byParent[image.Get("ParentId")]; exists {
  1184. children.Add(image)
  1185. } else {
  1186. byParent[image.Get("ParentId")] = engine.NewTable("Created", 1)
  1187. byParent[image.Get("ParentId")].Add(image)
  1188. }
  1189. }
  1190. if matchName != "" {
  1191. if matchName == image.Get("Id") || matchName == utils.TruncateID(image.Get("Id")) {
  1192. startImage = image
  1193. }
  1194. for _, repotag := range image.GetList("RepoTags") {
  1195. if repotag == matchName {
  1196. startImage = image
  1197. }
  1198. }
  1199. }
  1200. }
  1201. if *flViz {
  1202. fmt.Fprintf(cli.out, "digraph docker {\n")
  1203. printNode = (*DockerCli).printVizNode
  1204. } else {
  1205. printNode = (*DockerCli).printTreeNode
  1206. }
  1207. if startImage != nil {
  1208. root := engine.NewTable("Created", 1)
  1209. root.Add(startImage)
  1210. cli.WalkTree(*noTrunc, root, byParent, "", printNode)
  1211. } else if matchName == "" {
  1212. cli.WalkTree(*noTrunc, roots, byParent, "", printNode)
  1213. }
  1214. if *flViz {
  1215. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1216. }
  1217. } else {
  1218. v := url.Values{}
  1219. if len(imageFilterArgs) > 0 {
  1220. filterJson, err := filters.ToParam(imageFilterArgs)
  1221. if err != nil {
  1222. return err
  1223. }
  1224. v.Set("filters", filterJson)
  1225. }
  1226. if cmd.NArg() == 1 {
  1227. // FIXME rename this parameter, to not be confused with the filters flag
  1228. v.Set("filter", matchName)
  1229. }
  1230. if *all {
  1231. v.Set("all", "1")
  1232. }
  1233. body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false))
  1234. if err != nil {
  1235. return err
  1236. }
  1237. outs := engine.NewTable("Created", 0)
  1238. if _, err := outs.ReadListFrom(body); err != nil {
  1239. return err
  1240. }
  1241. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1242. if !*quiet {
  1243. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE")
  1244. }
  1245. for _, out := range outs.Data {
  1246. for _, repotag := range out.GetList("RepoTags") {
  1247. repo, tag := parsers.ParseRepositoryTag(repotag)
  1248. outID := out.Get("Id")
  1249. if !*noTrunc {
  1250. outID = utils.TruncateID(outID)
  1251. }
  1252. if !*quiet {
  1253. 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")))
  1254. } else {
  1255. fmt.Fprintln(w, outID)
  1256. }
  1257. }
  1258. }
  1259. if !*quiet {
  1260. w.Flush()
  1261. }
  1262. }
  1263. return nil
  1264. }
  1265. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1266. 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)) {
  1267. length := images.Len()
  1268. if length > 1 {
  1269. for index, image := range images.Data {
  1270. if index+1 == length {
  1271. printNode(cli, noTrunc, image, prefix+"└─")
  1272. if subimages, exists := byParent[image.Get("Id")]; exists {
  1273. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1274. }
  1275. } else {
  1276. printNode(cli, noTrunc, image, prefix+"\u251C─")
  1277. if subimages, exists := byParent[image.Get("Id")]; exists {
  1278. cli.WalkTree(noTrunc, subimages, byParent, prefix+"\u2502 ", printNode)
  1279. }
  1280. }
  1281. }
  1282. } else {
  1283. for _, image := range images.Data {
  1284. printNode(cli, noTrunc, image, prefix+"└─")
  1285. if subimages, exists := byParent[image.Get("Id")]; exists {
  1286. cli.WalkTree(noTrunc, subimages, byParent, prefix+" ", printNode)
  1287. }
  1288. }
  1289. }
  1290. }
  1291. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1292. func (cli *DockerCli) printVizNode(noTrunc bool, image *engine.Env, prefix string) {
  1293. var (
  1294. imageID string
  1295. parentID string
  1296. )
  1297. if noTrunc {
  1298. imageID = image.Get("Id")
  1299. parentID = image.Get("ParentId")
  1300. } else {
  1301. imageID = utils.TruncateID(image.Get("Id"))
  1302. parentID = utils.TruncateID(image.Get("ParentId"))
  1303. }
  1304. if parentID == "" {
  1305. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", imageID)
  1306. } else {
  1307. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", parentID, imageID)
  1308. }
  1309. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1310. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n",
  1311. imageID, imageID, strings.Join(image.GetList("RepoTags"), "\\n"))
  1312. }
  1313. }
  1314. // FIXME: --viz and --tree are deprecated. Remove them in a future version.
  1315. func (cli *DockerCli) printTreeNode(noTrunc bool, image *engine.Env, prefix string) {
  1316. var imageID string
  1317. if noTrunc {
  1318. imageID = image.Get("Id")
  1319. } else {
  1320. imageID = utils.TruncateID(image.Get("Id"))
  1321. }
  1322. fmt.Fprintf(cli.out, "%s%s Virtual Size: %s", prefix, imageID, units.HumanSize(image.GetInt64("VirtualSize")))
  1323. if image.GetList("RepoTags")[0] != "<none>:<none>" {
  1324. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.GetList("RepoTags"), ", "))
  1325. } else {
  1326. fmt.Fprint(cli.out, "\n")
  1327. }
  1328. }
  1329. func (cli *DockerCli) CmdPs(args ...string) error {
  1330. var (
  1331. err error
  1332. psFilterArgs = filters.Args{}
  1333. v = url.Values{}
  1334. cmd = cli.Subcmd("ps", "", "List containers")
  1335. quiet = cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs")
  1336. size = cmd.Bool([]string{"s", "-size"}, false, "Display sizes")
  1337. all = cmd.Bool([]string{"a", "-all"}, false, "Show all containers. Only running containers are shown by default.")
  1338. noTrunc = cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1339. nLatest = cmd.Bool([]string{"l", "-latest"}, false, "Show only the latest created container, include non-running ones.")
  1340. since = cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show only containers created since Id or Name, include non-running ones.")
  1341. before = cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name, include non-running ones.")
  1342. last = cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running ones.")
  1343. flFilter = opts.NewListOpts(nil)
  1344. )
  1345. cmd.Var(&flFilter, []string{"f", "-filter"}, "Provide filter values. Valid filters:\nexited=<int> - containers with exit code of <int>\nstatus=(restarting|running|paused|exited)")
  1346. if err := cmd.Parse(args); err != nil {
  1347. return nil
  1348. }
  1349. if *last == -1 && *nLatest {
  1350. *last = 1
  1351. }
  1352. if *all {
  1353. v.Set("all", "1")
  1354. }
  1355. if *last != -1 {
  1356. v.Set("limit", strconv.Itoa(*last))
  1357. }
  1358. if *since != "" {
  1359. v.Set("since", *since)
  1360. }
  1361. if *before != "" {
  1362. v.Set("before", *before)
  1363. }
  1364. if *size {
  1365. v.Set("size", "1")
  1366. }
  1367. // Consolidate all filter flags, and sanity check them.
  1368. // They'll get processed in the daemon/server.
  1369. for _, f := range flFilter.GetAll() {
  1370. if psFilterArgs, err = filters.ParseFlag(f, psFilterArgs); err != nil {
  1371. return err
  1372. }
  1373. }
  1374. if len(psFilterArgs) > 0 {
  1375. filterJson, err := filters.ToParam(psFilterArgs)
  1376. if err != nil {
  1377. return err
  1378. }
  1379. v.Set("filters", filterJson)
  1380. }
  1381. body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false))
  1382. if err != nil {
  1383. return err
  1384. }
  1385. outs := engine.NewTable("Created", 0)
  1386. if _, err := outs.ReadListFrom(body); err != nil {
  1387. return err
  1388. }
  1389. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1390. if !*quiet {
  1391. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1392. if *size {
  1393. fmt.Fprintln(w, "\tSIZE")
  1394. } else {
  1395. fmt.Fprint(w, "\n")
  1396. }
  1397. }
  1398. stripNamePrefix := func(ss []string) []string {
  1399. for i, s := range ss {
  1400. ss[i] = s[1:]
  1401. }
  1402. return ss
  1403. }
  1404. for _, out := range outs.Data {
  1405. outID := out.Get("Id")
  1406. if !*noTrunc {
  1407. outID = utils.TruncateID(outID)
  1408. }
  1409. if *quiet {
  1410. fmt.Fprintln(w, outID)
  1411. continue
  1412. }
  1413. var (
  1414. outNames = stripNamePrefix(out.GetList("Names"))
  1415. outCommand = strconv.Quote(out.Get("Command"))
  1416. ports = engine.NewTable("", 0)
  1417. )
  1418. if !*noTrunc {
  1419. outCommand = utils.Trunc(outCommand, 20)
  1420. // only display the default name for the container with notrunc is passed
  1421. for _, name := range outNames {
  1422. if len(strings.Split(name, "/")) == 1 {
  1423. outNames = []string{name}
  1424. break
  1425. }
  1426. }
  1427. }
  1428. ports.ReadListFrom([]byte(out.Get("Ports")))
  1429. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", outID, out.Get("Image"), outCommand,
  1430. units.HumanDuration(time.Now().UTC().Sub(time.Unix(out.GetInt64("Created"), 0))),
  1431. out.Get("Status"), api.DisplayablePorts(ports), strings.Join(outNames, ","))
  1432. if *size {
  1433. if out.GetInt("SizeRootFs") > 0 {
  1434. fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(out.GetInt64("SizeRw")), units.HumanSize(out.GetInt64("SizeRootFs")))
  1435. } else {
  1436. fmt.Fprintf(w, "%s\n", units.HumanSize(out.GetInt64("SizeRw")))
  1437. }
  1438. continue
  1439. }
  1440. fmt.Fprint(w, "\n")
  1441. }
  1442. if !*quiet {
  1443. w.Flush()
  1444. }
  1445. return nil
  1446. }
  1447. func (cli *DockerCli) CmdCommit(args ...string) error {
  1448. cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1449. flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit")
  1450. flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
  1451. flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
  1452. // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands.
  1453. 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")
  1454. if err := cmd.Parse(args); err != nil {
  1455. return nil
  1456. }
  1457. var (
  1458. name = cmd.Arg(0)
  1459. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1460. )
  1461. if name == "" || len(cmd.Args()) > 2 {
  1462. cmd.Usage()
  1463. return nil
  1464. }
  1465. //Check if the given image name can be resolved
  1466. if repository != "" {
  1467. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1468. return err
  1469. }
  1470. }
  1471. v := url.Values{}
  1472. v.Set("container", name)
  1473. v.Set("repo", repository)
  1474. v.Set("tag", tag)
  1475. v.Set("comment", *flComment)
  1476. v.Set("author", *flAuthor)
  1477. if *flPause != true {
  1478. v.Set("pause", "0")
  1479. }
  1480. var (
  1481. config *runconfig.Config
  1482. env engine.Env
  1483. )
  1484. if *flConfig != "" {
  1485. config = &runconfig.Config{}
  1486. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1487. return err
  1488. }
  1489. }
  1490. stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false)
  1491. if err != nil {
  1492. return err
  1493. }
  1494. if err := env.Decode(stream); err != nil {
  1495. return err
  1496. }
  1497. fmt.Fprintf(cli.out, "%s\n", env.Get("Id"))
  1498. return nil
  1499. }
  1500. func (cli *DockerCli) CmdEvents(args ...string) error {
  1501. cmd := cli.Subcmd("events", "", "Get real time events from the server")
  1502. since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp")
  1503. until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp")
  1504. if err := cmd.Parse(args); err != nil {
  1505. return nil
  1506. }
  1507. if cmd.NArg() != 0 {
  1508. cmd.Usage()
  1509. return nil
  1510. }
  1511. var (
  1512. v = url.Values{}
  1513. loc = time.FixedZone(time.Now().Zone())
  1514. )
  1515. var setTime = func(key, value string) {
  1516. format := timeutils.RFC3339NanoFixed
  1517. if len(value) < len(format) {
  1518. format = format[:len(value)]
  1519. }
  1520. if t, err := time.ParseInLocation(format, value, loc); err == nil {
  1521. v.Set(key, strconv.FormatInt(t.Unix(), 10))
  1522. } else {
  1523. v.Set(key, value)
  1524. }
  1525. }
  1526. if *since != "" {
  1527. setTime("since", *since)
  1528. }
  1529. if *until != "" {
  1530. setTime("until", *until)
  1531. }
  1532. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1533. return err
  1534. }
  1535. return nil
  1536. }
  1537. func (cli *DockerCli) CmdExport(args ...string) error {
  1538. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1539. if err := cmd.Parse(args); err != nil {
  1540. return nil
  1541. }
  1542. if cmd.NArg() != 1 {
  1543. cmd.Usage()
  1544. return nil
  1545. }
  1546. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1547. return err
  1548. }
  1549. return nil
  1550. }
  1551. func (cli *DockerCli) CmdDiff(args ...string) error {
  1552. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1553. if err := cmd.Parse(args); err != nil {
  1554. return nil
  1555. }
  1556. if cmd.NArg() != 1 {
  1557. cmd.Usage()
  1558. return nil
  1559. }
  1560. body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false))
  1561. if err != nil {
  1562. return err
  1563. }
  1564. outs := engine.NewTable("", 0)
  1565. if _, err := outs.ReadListFrom(body); err != nil {
  1566. return err
  1567. }
  1568. for _, change := range outs.Data {
  1569. var kind string
  1570. switch change.GetInt("Kind") {
  1571. case archive.ChangeModify:
  1572. kind = "C"
  1573. case archive.ChangeAdd:
  1574. kind = "A"
  1575. case archive.ChangeDelete:
  1576. kind = "D"
  1577. }
  1578. fmt.Fprintf(cli.out, "%s %s\n", kind, change.Get("Path"))
  1579. }
  1580. return nil
  1581. }
  1582. func (cli *DockerCli) CmdLogs(args ...string) error {
  1583. var (
  1584. cmd = cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1585. follow = cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
  1586. times = cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
  1587. tail = cmd.String([]string{"-tail"}, "all", "Output the specified number of lines at the end of logs (defaults to all logs)")
  1588. )
  1589. if err := cmd.Parse(args); err != nil {
  1590. return nil
  1591. }
  1592. if cmd.NArg() != 1 {
  1593. cmd.Usage()
  1594. return nil
  1595. }
  1596. name := cmd.Arg(0)
  1597. steam, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1598. if err != nil {
  1599. return err
  1600. }
  1601. env := engine.Env{}
  1602. if err := env.Decode(steam); err != nil {
  1603. return err
  1604. }
  1605. v := url.Values{}
  1606. v.Set("stdout", "1")
  1607. v.Set("stderr", "1")
  1608. if *times {
  1609. v.Set("timestamps", "1")
  1610. }
  1611. if *follow {
  1612. v.Set("follow", "1")
  1613. }
  1614. v.Set("tail", *tail)
  1615. return cli.streamHelper("GET", "/containers/"+name+"/logs?"+v.Encode(), env.GetSubEnv("Config").GetBool("Tty"), nil, cli.out, cli.err, nil)
  1616. }
  1617. func (cli *DockerCli) CmdAttach(args ...string) error {
  1618. var (
  1619. cmd = cli.Subcmd("attach", "CONTAINER", "Attach to a running container")
  1620. noStdin = cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN")
  1621. 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.")
  1622. )
  1623. if err := cmd.Parse(args); err != nil {
  1624. return nil
  1625. }
  1626. if cmd.NArg() != 1 {
  1627. cmd.Usage()
  1628. return nil
  1629. }
  1630. name := cmd.Arg(0)
  1631. stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false)
  1632. if err != nil {
  1633. return err
  1634. }
  1635. env := engine.Env{}
  1636. if err := env.Decode(stream); err != nil {
  1637. return err
  1638. }
  1639. if !env.GetSubEnv("State").GetBool("Running") {
  1640. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  1641. }
  1642. var (
  1643. config = env.GetSubEnv("Config")
  1644. tty = config.GetBool("Tty")
  1645. )
  1646. if tty && cli.isTerminalOut {
  1647. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  1648. log.Debugf("Error monitoring TTY size: %s", err)
  1649. }
  1650. }
  1651. var in io.ReadCloser
  1652. v := url.Values{}
  1653. v.Set("stream", "1")
  1654. if !*noStdin && config.GetBool("OpenStdin") {
  1655. v.Set("stdin", "1")
  1656. in = cli.in
  1657. }
  1658. v.Set("stdout", "1")
  1659. v.Set("stderr", "1")
  1660. if *proxy && !tty {
  1661. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1662. defer signal.StopCatch(sigc)
  1663. }
  1664. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, nil, nil); err != nil {
  1665. return err
  1666. }
  1667. _, status, err := getExitCode(cli, cmd.Arg(0))
  1668. if err != nil {
  1669. return err
  1670. }
  1671. if status != 0 {
  1672. return &utils.StatusError{StatusCode: status}
  1673. }
  1674. return nil
  1675. }
  1676. func (cli *DockerCli) CmdSearch(args ...string) error {
  1677. cmd := cli.Subcmd("search", "TERM", "Search the Docker Hub for images")
  1678. noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output")
  1679. trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds")
  1680. automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds")
  1681. stars := cmd.Int([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars")
  1682. if err := cmd.Parse(args); err != nil {
  1683. return nil
  1684. }
  1685. if cmd.NArg() != 1 {
  1686. cmd.Usage()
  1687. return nil
  1688. }
  1689. v := url.Values{}
  1690. v.Set("term", cmd.Arg(0))
  1691. body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true))
  1692. if err != nil {
  1693. return err
  1694. }
  1695. outs := engine.NewTable("star_count", 0)
  1696. if _, err := outs.ReadListFrom(body); err != nil {
  1697. return err
  1698. }
  1699. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1700. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n")
  1701. for _, out := range outs.Data {
  1702. if ((*automated || *trusted) && (!out.GetBool("is_trusted") && !out.GetBool("is_automated"))) || (*stars > out.GetInt("star_count")) {
  1703. continue
  1704. }
  1705. desc := strings.Replace(out.Get("description"), "\n", " ", -1)
  1706. desc = strings.Replace(desc, "\r", " ", -1)
  1707. if !*noTrunc && len(desc) > 45 {
  1708. desc = utils.Trunc(desc, 42) + "..."
  1709. }
  1710. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Get("name"), desc, out.GetInt("star_count"))
  1711. if out.GetBool("is_official") {
  1712. fmt.Fprint(w, "[OK]")
  1713. }
  1714. fmt.Fprint(w, "\t")
  1715. if out.GetBool("is_automated") || out.GetBool("is_trusted") {
  1716. fmt.Fprint(w, "[OK]")
  1717. }
  1718. fmt.Fprint(w, "\n")
  1719. }
  1720. w.Flush()
  1721. return nil
  1722. }
  1723. // Ports type - Used to parse multiple -p flags
  1724. type ports []int
  1725. func (cli *DockerCli) CmdTag(args ...string) error {
  1726. cmd := cli.Subcmd("tag", "IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]", "Tag an image into a repository")
  1727. force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force")
  1728. if err := cmd.Parse(args); err != nil {
  1729. return nil
  1730. }
  1731. if cmd.NArg() != 2 {
  1732. cmd.Usage()
  1733. return nil
  1734. }
  1735. var (
  1736. repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
  1737. v = url.Values{}
  1738. )
  1739. //Check if the given image name can be resolved
  1740. if _, _, err := registry.ResolveRepositoryName(repository); err != nil {
  1741. return err
  1742. }
  1743. v.Set("repo", repository)
  1744. v.Set("tag", tag)
  1745. if *force {
  1746. v.Set("force", "1")
  1747. }
  1748. if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil {
  1749. return err
  1750. }
  1751. return nil
  1752. }
  1753. func (cli *DockerCli) pullImage(image string) error {
  1754. return cli.pullImageCustomOut(image, cli.out)
  1755. }
  1756. func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error {
  1757. v := url.Values{}
  1758. repos, tag := parsers.ParseRepositoryTag(image)
  1759. // pull only the image tagged 'latest' if no tag was specified
  1760. if tag == "" {
  1761. tag = "latest"
  1762. }
  1763. v.Set("fromImage", repos)
  1764. v.Set("tag", tag)
  1765. // Resolve the Repository name from fqn to hostname + name
  1766. hostname, _, err := registry.ResolveRepositoryName(repos)
  1767. if err != nil {
  1768. return err
  1769. }
  1770. // Load the auth config file, to be able to pull the image
  1771. cli.LoadConfigFile()
  1772. // Resolve the Auth config relevant for this server
  1773. authConfig := cli.configFile.ResolveAuthConfig(hostname)
  1774. buf, err := json.Marshal(authConfig)
  1775. if err != nil {
  1776. return err
  1777. }
  1778. registryAuthHeader := []string{
  1779. base64.URLEncoding.EncodeToString(buf),
  1780. }
  1781. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, out, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1782. return err
  1783. }
  1784. return nil
  1785. }
  1786. type cidFile struct {
  1787. path string
  1788. file *os.File
  1789. written bool
  1790. }
  1791. func newCIDFile(path string) (*cidFile, error) {
  1792. if _, err := os.Stat(path); err == nil {
  1793. return nil, fmt.Errorf("Container ID file found, make sure the other container isn't running or delete %s", path)
  1794. }
  1795. f, err := os.Create(path)
  1796. if err != nil {
  1797. return nil, fmt.Errorf("Failed to create the container ID file: %s", err)
  1798. }
  1799. return &cidFile{path: path, file: f}, nil
  1800. }
  1801. func (cid *cidFile) Close() error {
  1802. cid.file.Close()
  1803. if !cid.written {
  1804. if err := os.Remove(cid.path); err != nil {
  1805. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  1806. }
  1807. }
  1808. return nil
  1809. }
  1810. func (cid *cidFile) Write(id string) error {
  1811. if _, err := cid.file.Write([]byte(id)); err != nil {
  1812. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  1813. }
  1814. cid.written = true
  1815. return nil
  1816. }
  1817. func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (engine.Env, error) {
  1818. containerValues := url.Values{}
  1819. if name != "" {
  1820. containerValues.Set("name", name)
  1821. }
  1822. mergedConfig := runconfig.MergeConfigs(config, hostConfig)
  1823. var containerIDFile *cidFile
  1824. if cidfile != "" {
  1825. var err error
  1826. if containerIDFile, err = newCIDFile(cidfile); err != nil {
  1827. return nil, err
  1828. }
  1829. defer containerIDFile.Close()
  1830. }
  1831. //create the container
  1832. stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false)
  1833. //if image not found try to pull it
  1834. if statusCode == 404 {
  1835. fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", config.Image)
  1836. // we don't want to write to stdout anything apart from container.ID
  1837. if err = cli.pullImageCustomOut(config.Image, cli.err); err != nil {
  1838. return nil, err
  1839. }
  1840. // Retry
  1841. if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil {
  1842. return nil, err
  1843. }
  1844. } else if err != nil {
  1845. return nil, err
  1846. }
  1847. var result engine.Env
  1848. if err := result.Decode(stream); err != nil {
  1849. return nil, err
  1850. }
  1851. for _, warning := range result.GetList("Warnings") {
  1852. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1853. }
  1854. if containerIDFile != nil {
  1855. if err = containerIDFile.Write(result.Get("Id")); err != nil {
  1856. return nil, err
  1857. }
  1858. }
  1859. return result, nil
  1860. }
  1861. func (cli *DockerCli) CmdCreate(args ...string) error {
  1862. cmd := cli.Subcmd("create", "IMAGE [COMMAND] [ARG...]", "Create a new container")
  1863. // These are flags not stored in Config/HostConfig
  1864. var (
  1865. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  1866. )
  1867. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1868. if err != nil {
  1869. return err
  1870. }
  1871. if config.Image == "" {
  1872. cmd.Usage()
  1873. return nil
  1874. }
  1875. createResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1876. if err != nil {
  1877. return err
  1878. }
  1879. fmt.Fprintf(cli.out, "%s\n", createResult.Get("Id"))
  1880. return nil
  1881. }
  1882. func (cli *DockerCli) CmdRun(args ...string) error {
  1883. // FIXME: just use runconfig.Parse already
  1884. cmd := cli.Subcmd("run", "IMAGE [COMMAND] [ARG...]", "Run a command in a new container")
  1885. // These are flags not stored in Config/HostConfig
  1886. var (
  1887. flAutoRemove = cmd.Bool([]string{"#rm", "-rm"}, false, "Automatically remove the container when it exits (incompatible with -d)")
  1888. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run the container in the background and print the new container ID")
  1889. 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.")
  1890. flName = cmd.String([]string{"#name", "-name"}, "", "Assign a name to the container")
  1891. flAttach *opts.ListOpts
  1892. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  1893. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  1894. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  1895. )
  1896. config, hostConfig, cmd, err := runconfig.Parse(cmd, args, nil)
  1897. if err != nil {
  1898. return err
  1899. }
  1900. if config.Image == "" {
  1901. cmd.Usage()
  1902. return nil
  1903. }
  1904. if *flDetach {
  1905. if fl := cmd.Lookup("attach"); fl != nil {
  1906. flAttach = fl.Value.(*opts.ListOpts)
  1907. if flAttach.Len() != 0 {
  1908. return ErrConflictAttachDetach
  1909. }
  1910. }
  1911. if *flAutoRemove {
  1912. return ErrConflictDetachAutoRemove
  1913. }
  1914. config.AttachStdin = false
  1915. config.AttachStdout = false
  1916. config.AttachStderr = false
  1917. config.StdinOnce = false
  1918. }
  1919. // Disable flSigProxy when in TTY mode
  1920. sigProxy := *flSigProxy
  1921. if config.Tty {
  1922. sigProxy = false
  1923. }
  1924. runResult, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  1925. if err != nil {
  1926. return err
  1927. }
  1928. if sigProxy {
  1929. sigc := cli.forwardAllSignals(runResult.Get("Id"))
  1930. defer signal.StopCatch(sigc)
  1931. }
  1932. var (
  1933. waitDisplayId chan struct{}
  1934. errCh chan error
  1935. )
  1936. if !config.AttachStdout && !config.AttachStderr {
  1937. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  1938. waitDisplayId = make(chan struct{})
  1939. go func() {
  1940. defer close(waitDisplayId)
  1941. fmt.Fprintf(cli.out, "%s\n", runResult.Get("Id"))
  1942. }()
  1943. }
  1944. if *flAutoRemove && (hostConfig.RestartPolicy.Name == "always" || hostConfig.RestartPolicy.Name == "on-failure") {
  1945. return ErrConflictRestartPolicyAndAutoRemove
  1946. }
  1947. // We need to instantiate the chan because the select needs it. It can
  1948. // be closed but can't be uninitialized.
  1949. hijacked := make(chan io.Closer)
  1950. // Block the return until the chan gets closed
  1951. defer func() {
  1952. log.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1953. if _, ok := <-hijacked; ok {
  1954. log.Errorf("Hijack did not finish (chan still open)")
  1955. }
  1956. }()
  1957. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1958. var (
  1959. out, stderr io.Writer
  1960. in io.ReadCloser
  1961. v = url.Values{}
  1962. )
  1963. v.Set("stream", "1")
  1964. if config.AttachStdin {
  1965. v.Set("stdin", "1")
  1966. in = cli.in
  1967. }
  1968. if config.AttachStdout {
  1969. v.Set("stdout", "1")
  1970. out = cli.out
  1971. }
  1972. if config.AttachStderr {
  1973. v.Set("stderr", "1")
  1974. if config.Tty {
  1975. stderr = cli.out
  1976. } else {
  1977. stderr = cli.err
  1978. }
  1979. }
  1980. errCh = promise.Go(func() error {
  1981. return cli.hijack("POST", "/containers/"+runResult.Get("Id")+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil)
  1982. })
  1983. } else {
  1984. close(hijacked)
  1985. }
  1986. // Acknowledge the hijack before starting
  1987. select {
  1988. case closer := <-hijacked:
  1989. // Make sure that the hijack gets closed when returning (results
  1990. // in closing the hijack chan and freeing server's goroutines)
  1991. if closer != nil {
  1992. defer closer.Close()
  1993. }
  1994. case err := <-errCh:
  1995. if err != nil {
  1996. log.Debugf("Error hijack: %s", err)
  1997. return err
  1998. }
  1999. }
  2000. //start the container
  2001. if _, _, err = readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/start", nil, false)); err != nil {
  2002. return err
  2003. }
  2004. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  2005. if err := cli.monitorTtySize(runResult.Get("Id"), false); err != nil {
  2006. log.Errorf("Error monitoring TTY size: %s", err)
  2007. }
  2008. }
  2009. if errCh != nil {
  2010. if err := <-errCh; err != nil {
  2011. log.Debugf("Error hijack: %s", err)
  2012. return err
  2013. }
  2014. }
  2015. // Detached mode: wait for the id to be displayed and return.
  2016. if !config.AttachStdout && !config.AttachStderr {
  2017. // Detached mode
  2018. <-waitDisplayId
  2019. return nil
  2020. }
  2021. var status int
  2022. // Attached mode
  2023. if *flAutoRemove {
  2024. // Autoremove: wait for the container to finish, retrieve
  2025. // the exit code and remove the container
  2026. if _, _, err := readBody(cli.call("POST", "/containers/"+runResult.Get("Id")+"/wait", nil, false)); err != nil {
  2027. return err
  2028. }
  2029. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2030. return err
  2031. }
  2032. if _, _, err := readBody(cli.call("DELETE", "/containers/"+runResult.Get("Id")+"?v=1", nil, false)); err != nil {
  2033. return err
  2034. }
  2035. } else {
  2036. // No Autoremove: Simply retrieve the exit code
  2037. if !config.Tty {
  2038. // In non-TTY mode, we can't detach, so we must wait for container exit
  2039. if status, err = waitForExit(cli, runResult.Get("Id")); err != nil {
  2040. return err
  2041. }
  2042. } else {
  2043. // In TTY mode, there is a race: if the process dies too slowly, the state could
  2044. // be updated after the getExitCode call and result in the wrong exit code being reported
  2045. if _, status, err = getExitCode(cli, runResult.Get("Id")); err != nil {
  2046. return err
  2047. }
  2048. }
  2049. }
  2050. if status != 0 {
  2051. return &utils.StatusError{StatusCode: status}
  2052. }
  2053. return nil
  2054. }
  2055. func (cli *DockerCli) CmdCp(args ...string) error {
  2056. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  2057. if err := cmd.Parse(args); err != nil {
  2058. return nil
  2059. }
  2060. if cmd.NArg() != 2 {
  2061. cmd.Usage()
  2062. return nil
  2063. }
  2064. var copyData engine.Env
  2065. info := strings.Split(cmd.Arg(0), ":")
  2066. if len(info) != 2 {
  2067. return fmt.Errorf("Error: Path not specified")
  2068. }
  2069. copyData.Set("Resource", info[1])
  2070. copyData.Set("HostPath", cmd.Arg(1))
  2071. stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false)
  2072. if stream != nil {
  2073. defer stream.Close()
  2074. }
  2075. if statusCode == 404 {
  2076. return fmt.Errorf("No such container: %v", info[0])
  2077. }
  2078. if err != nil {
  2079. return err
  2080. }
  2081. if statusCode == 200 {
  2082. if err := archive.Untar(stream, copyData.Get("HostPath"), &archive.TarOptions{NoLchown: true}); err != nil {
  2083. return err
  2084. }
  2085. }
  2086. return nil
  2087. }
  2088. func (cli *DockerCli) CmdSave(args ...string) error {
  2089. cmd := cli.Subcmd("save", "IMAGE [IMAGE...]", "Save an image(s) to a tar archive (streamed to STDOUT by default)")
  2090. outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT")
  2091. if err := cmd.Parse(args); err != nil {
  2092. return err
  2093. }
  2094. if cmd.NArg() < 1 {
  2095. cmd.Usage()
  2096. return nil
  2097. }
  2098. var (
  2099. output io.Writer = cli.out
  2100. err error
  2101. )
  2102. if *outfile != "" {
  2103. output, err = os.Create(*outfile)
  2104. if err != nil {
  2105. return err
  2106. }
  2107. } else if cli.isTerminalOut {
  2108. return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
  2109. }
  2110. if len(cmd.Args()) == 1 {
  2111. image := cmd.Arg(0)
  2112. if err := cli.stream("GET", "/images/"+image+"/get", nil, output, nil); err != nil {
  2113. return err
  2114. }
  2115. } else {
  2116. v := url.Values{}
  2117. for _, arg := range cmd.Args() {
  2118. v.Add("names", arg)
  2119. }
  2120. if err := cli.stream("GET", "/images/get?"+v.Encode(), nil, output, nil); err != nil {
  2121. return err
  2122. }
  2123. }
  2124. return nil
  2125. }
  2126. func (cli *DockerCli) CmdLoad(args ...string) error {
  2127. cmd := cli.Subcmd("load", "", "Load an image from a tar archive on STDIN")
  2128. infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
  2129. if err := cmd.Parse(args); err != nil {
  2130. return err
  2131. }
  2132. if cmd.NArg() != 0 {
  2133. cmd.Usage()
  2134. return nil
  2135. }
  2136. var (
  2137. input io.Reader = cli.in
  2138. err error
  2139. )
  2140. if *infile != "" {
  2141. input, err = os.Open(*infile)
  2142. if err != nil {
  2143. return err
  2144. }
  2145. }
  2146. if err := cli.stream("POST", "/images/load", input, cli.out, nil); err != nil {
  2147. return err
  2148. }
  2149. return nil
  2150. }
  2151. func (cli *DockerCli) CmdExec(args ...string) error {
  2152. cmd := cli.Subcmd("exec", "CONTAINER COMMAND [ARG...]", "Run a command in an existing container")
  2153. execConfig, err := runconfig.ParseExec(cmd, args)
  2154. if err != nil {
  2155. return err
  2156. }
  2157. if execConfig.Container == "" {
  2158. cmd.Usage()
  2159. return nil
  2160. }
  2161. stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, false)
  2162. if err != nil {
  2163. return err
  2164. }
  2165. var execResult engine.Env
  2166. if err := execResult.Decode(stream); err != nil {
  2167. return err
  2168. }
  2169. execID := execResult.Get("Id")
  2170. if execID == "" {
  2171. fmt.Fprintf(cli.out, "exec ID empty")
  2172. return nil
  2173. }
  2174. if execConfig.Detach {
  2175. if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, false)); err != nil {
  2176. return err
  2177. }
  2178. return nil
  2179. }
  2180. // Interactive exec requested.
  2181. var (
  2182. out, stderr io.Writer
  2183. in io.ReadCloser
  2184. hijacked = make(chan io.Closer)
  2185. errCh chan error
  2186. )
  2187. // Block the return until the chan gets closed
  2188. defer func() {
  2189. log.Debugf("End of CmdExec(), Waiting for hijack to finish.")
  2190. if _, ok := <-hijacked; ok {
  2191. log.Errorf("Hijack did not finish (chan still open)")
  2192. }
  2193. }()
  2194. if execConfig.AttachStdin {
  2195. in = cli.in
  2196. }
  2197. if execConfig.AttachStdout {
  2198. out = cli.out
  2199. }
  2200. if execConfig.AttachStderr {
  2201. if execConfig.Tty {
  2202. stderr = cli.out
  2203. } else {
  2204. stderr = cli.err
  2205. }
  2206. }
  2207. errCh = promise.Go(func() error {
  2208. return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig)
  2209. })
  2210. // Acknowledge the hijack before starting
  2211. select {
  2212. case closer := <-hijacked:
  2213. // Make sure that hijack gets closed when returning. (result
  2214. // in closing hijack chan and freeing server's goroutines.
  2215. if closer != nil {
  2216. defer closer.Close()
  2217. }
  2218. case err := <-errCh:
  2219. if err != nil {
  2220. log.Debugf("Error hijack: %s", err)
  2221. return err
  2222. }
  2223. }
  2224. if execConfig.Tty && cli.isTerminalIn {
  2225. if err := cli.monitorTtySize(execID, true); err != nil {
  2226. log.Errorf("Error monitoring TTY size: %s", err)
  2227. }
  2228. }
  2229. if err := <-errCh; err != nil {
  2230. log.Debugf("Error hijack: %s", err)
  2231. return err
  2232. }
  2233. return nil
  2234. }