commands.go 68 KB

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