commands.go 71 KB

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