commands.go 78 KB

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