commands.go 71 KB

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