commands.go 78 KB

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