commands.go 73 KB

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