commands.go 78 KB

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