commands.go 69 KB

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