commands.go 78 KB

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