commands.go 71 KB

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