commands.go 70 KB

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