commands.go 78 KB

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