commands.go 79 KB

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