commands.go 69 KB

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