commands.go 69 KB

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