commands.go 77 KB

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