commands.go 80 KB

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