commands.go 76 KB

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