commands.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263
  1. package docker
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "github.com/dotcloud/docker/archive"
  12. "github.com/dotcloud/docker/auth"
  13. "github.com/dotcloud/docker/registry"
  14. "github.com/dotcloud/docker/term"
  15. "github.com/dotcloud/docker/utils"
  16. "io"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/http/httputil"
  21. "net/url"
  22. "os"
  23. "os/signal"
  24. "path/filepath"
  25. "reflect"
  26. "regexp"
  27. "runtime"
  28. "sort"
  29. "strconv"
  30. "strings"
  31. "syscall"
  32. "text/tabwriter"
  33. "time"
  34. )
  35. var (
  36. GITCOMMIT string
  37. VERSION string
  38. )
  39. var (
  40. ErrConnectionRefused = errors.New("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  41. )
  42. func (cli *DockerCli) getMethod(name string) (func(...string) error, bool) {
  43. methodName := "Cmd" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
  44. method := reflect.ValueOf(cli).MethodByName(methodName)
  45. if !method.IsValid() {
  46. return nil, false
  47. }
  48. return method.Interface().(func(...string) error), true
  49. }
  50. func ParseCommands(proto, addr string, args ...string) error {
  51. cli := NewDockerCli(os.Stdin, os.Stdout, os.Stderr, proto, addr)
  52. if len(args) > 0 {
  53. method, exists := cli.getMethod(args[0])
  54. if !exists {
  55. fmt.Println("Error: Command not found:", args[0])
  56. return cli.CmdHelp(args[1:]...)
  57. }
  58. return method(args[1:]...)
  59. }
  60. return cli.CmdHelp(args...)
  61. }
  62. func (cli *DockerCli) CmdHelp(args ...string) error {
  63. if len(args) > 0 {
  64. method, exists := cli.getMethod(args[0])
  65. if !exists {
  66. fmt.Fprintf(cli.err, "Error: Command not found: %s\n", args[0])
  67. } else {
  68. method("--help")
  69. return nil
  70. }
  71. }
  72. 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", DEFAULTUNIXSOCKET)
  73. for _, command := range [][]string{
  74. {"attach", "Attach to a running container"},
  75. {"build", "Build a container from a Dockerfile"},
  76. {"commit", "Create a new image from a container's changes"},
  77. {"cp", "Copy files/folders from the containers filesystem to the host path"},
  78. {"diff", "Inspect changes on a container's filesystem"},
  79. {"events", "Get real time events from the server"},
  80. {"export", "Stream the contents of a container as a tar archive"},
  81. {"history", "Show the history of an image"},
  82. {"images", "List images"},
  83. {"import", "Create a new filesystem image from the contents of a tarball"},
  84. {"info", "Display system-wide information"},
  85. {"insert", "Insert a file in an image"},
  86. {"inspect", "Return low-level information on a container"},
  87. {"kill", "Kill a running container"},
  88. {"login", "Register or Login to the docker registry server"},
  89. {"logs", "Fetch the logs of a container"},
  90. {"port", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT"},
  91. {"ps", "List containers"},
  92. {"pull", "Pull an image or a repository from the docker registry server"},
  93. {"push", "Push an image or a repository to the docker registry server"},
  94. {"restart", "Restart a running container"},
  95. {"rm", "Remove one or more containers"},
  96. {"rmi", "Remove one or more images"},
  97. {"run", "Run a command in a new container"},
  98. {"search", "Search for an image in the docker index"},
  99. {"start", "Start a stopped container"},
  100. {"stop", "Stop a running container"},
  101. {"tag", "Tag an image into a repository"},
  102. {"top", "Lookup the running processes of a container"},
  103. {"version", "Show the docker version information"},
  104. {"wait", "Block until a container stops, then print its exit code"},
  105. } {
  106. help += fmt.Sprintf(" %-10.10s%s\n", command[0], command[1])
  107. }
  108. fmt.Fprintf(cli.err, "%s\n", help)
  109. return nil
  110. }
  111. func (cli *DockerCli) CmdInsert(args ...string) error {
  112. cmd := Subcmd("insert", "IMAGE URL PATH", "Insert a file from URL in the IMAGE at PATH")
  113. if err := cmd.Parse(args); err != nil {
  114. return nil
  115. }
  116. if cmd.NArg() != 3 {
  117. cmd.Usage()
  118. return nil
  119. }
  120. v := url.Values{}
  121. v.Set("url", cmd.Arg(1))
  122. v.Set("path", cmd.Arg(2))
  123. if err := cli.stream("POST", "/images/"+cmd.Arg(0)+"/insert?"+v.Encode(), nil, cli.out, nil); err != nil {
  124. return err
  125. }
  126. return nil
  127. }
  128. // mkBuildContext returns an archive of an empty context with the contents
  129. // of `dockerfile` at the path ./Dockerfile
  130. func mkBuildContext(dockerfile string, files [][2]string) (archive.Archive, error) {
  131. buf := new(bytes.Buffer)
  132. tw := tar.NewWriter(buf)
  133. files = append(files, [2]string{"Dockerfile", dockerfile})
  134. for _, file := range files {
  135. name, content := file[0], file[1]
  136. hdr := &tar.Header{
  137. Name: name,
  138. Size: int64(len(content)),
  139. }
  140. if err := tw.WriteHeader(hdr); err != nil {
  141. return nil, err
  142. }
  143. if _, err := tw.Write([]byte(content)); err != nil {
  144. return nil, err
  145. }
  146. }
  147. if err := tw.Close(); err != nil {
  148. return nil, err
  149. }
  150. return buf, nil
  151. }
  152. func (cli *DockerCli) CmdBuild(args ...string) error {
  153. cmd := Subcmd("build", "[OPTIONS] PATH | URL | -", "Build a new container image from the source code at PATH")
  154. tag := cmd.String("t", "", "Repository name (and optionally a tag) to be applied to the resulting image in case of success")
  155. suppressOutput := cmd.Bool("q", false, "Suppress verbose build output")
  156. noCache := cmd.Bool("no-cache", false, "Do not use cache when building the image")
  157. rm := cmd.Bool("rm", false, "Remove intermediate containers after a successful build")
  158. if err := cmd.Parse(args); err != nil {
  159. return nil
  160. }
  161. if cmd.NArg() != 1 {
  162. cmd.Usage()
  163. return nil
  164. }
  165. var (
  166. context archive.Archive
  167. isRemote bool
  168. err error
  169. )
  170. if cmd.Arg(0) == "-" {
  171. // As a special case, 'docker build -' will build from an empty context with the
  172. // contents of stdin as a Dockerfile
  173. dockerfile, err := ioutil.ReadAll(cli.in)
  174. if err != nil {
  175. return err
  176. }
  177. context, err = mkBuildContext(string(dockerfile), nil)
  178. } else if utils.IsURL(cmd.Arg(0)) || utils.IsGIT(cmd.Arg(0)) {
  179. isRemote = true
  180. } else {
  181. if _, err := os.Stat(cmd.Arg(0)); err != nil {
  182. return err
  183. }
  184. context, err = archive.Tar(cmd.Arg(0), archive.Uncompressed)
  185. }
  186. var body io.Reader
  187. // Setup an upload progress bar
  188. // FIXME: ProgressReader shouldn't be this annoying to use
  189. if context != nil {
  190. sf := utils.NewStreamFormatter(false)
  191. body = utils.ProgressReader(ioutil.NopCloser(context), 0, cli.err, sf.FormatProgress("", "Uploading context", "%v bytes%0.0s%0.0s"), sf, true)
  192. }
  193. // Upload the build context
  194. v := &url.Values{}
  195. v.Set("t", *tag)
  196. if *suppressOutput {
  197. v.Set("q", "1")
  198. }
  199. if isRemote {
  200. v.Set("remote", cmd.Arg(0))
  201. }
  202. if *noCache {
  203. v.Set("nocache", "1")
  204. }
  205. if *rm {
  206. v.Set("rm", "1")
  207. }
  208. req, err := http.NewRequest("POST", fmt.Sprintf("/v%g/build?%s", APIVERSION, v.Encode()), body)
  209. if err != nil {
  210. return err
  211. }
  212. if context != nil {
  213. req.Header.Set("Content-Type", "application/tar")
  214. }
  215. dial, err := net.Dial(cli.proto, cli.addr)
  216. if err != nil {
  217. return err
  218. }
  219. clientconn := httputil.NewClientConn(dial, nil)
  220. resp, err := clientconn.Do(req)
  221. defer clientconn.Close()
  222. if err != nil {
  223. return err
  224. }
  225. defer resp.Body.Close()
  226. // Check for errors
  227. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  228. body, err := ioutil.ReadAll(resp.Body)
  229. if err != nil {
  230. return err
  231. }
  232. if len(body) == 0 {
  233. return fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  234. }
  235. return fmt.Errorf("Error: %s", body)
  236. }
  237. // Output the result
  238. if _, err := io.Copy(cli.out, resp.Body); err != nil {
  239. return err
  240. }
  241. return nil
  242. }
  243. // 'docker login': login / register a user to registry service.
  244. func (cli *DockerCli) CmdLogin(args ...string) error {
  245. cmd := Subcmd("login", "[OPTIONS] [SERVER]", "Register or Login to a docker registry server, if no server is specified \""+auth.IndexServerAddress()+"\" is the default.")
  246. var username, password, email string
  247. cmd.StringVar(&username, "u", "", "username")
  248. cmd.StringVar(&password, "p", "", "password")
  249. cmd.StringVar(&email, "e", "", "email")
  250. err := cmd.Parse(args)
  251. if err != nil {
  252. return nil
  253. }
  254. serverAddress := auth.IndexServerAddress()
  255. if len(cmd.Args()) > 0 {
  256. serverAddress, err = registry.ExpandAndVerifyRegistryUrl(cmd.Arg(0))
  257. if err != nil {
  258. return err
  259. }
  260. fmt.Fprintf(cli.out, "Login against server at %s\n", serverAddress)
  261. }
  262. promptDefault := func(prompt string, configDefault string) {
  263. if configDefault == "" {
  264. fmt.Fprintf(cli.out, "%s: ", prompt)
  265. } else {
  266. fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault)
  267. }
  268. }
  269. readInput := func(in io.Reader, out io.Writer) string {
  270. reader := bufio.NewReader(in)
  271. line, _, err := reader.ReadLine()
  272. if err != nil {
  273. fmt.Fprintln(out, err.Error())
  274. os.Exit(1)
  275. }
  276. return string(line)
  277. }
  278. cli.LoadConfigFile()
  279. authconfig, ok := cli.configFile.Configs[serverAddress]
  280. if !ok {
  281. authconfig = auth.AuthConfig{}
  282. }
  283. if username == "" {
  284. promptDefault("Username", authconfig.Username)
  285. username = readInput(cli.in, cli.out)
  286. if username == "" {
  287. username = authconfig.Username
  288. }
  289. }
  290. if username != authconfig.Username {
  291. if password == "" {
  292. oldState, _ := term.SaveState(cli.terminalFd)
  293. fmt.Fprintf(cli.out, "Password: ")
  294. term.DisableEcho(cli.terminalFd, oldState)
  295. password = readInput(cli.in, cli.out)
  296. fmt.Fprint(cli.out, "\n")
  297. term.RestoreTerminal(cli.terminalFd, oldState)
  298. if password == "" {
  299. return fmt.Errorf("Error : Password Required")
  300. }
  301. }
  302. if email == "" {
  303. promptDefault("Email", authconfig.Email)
  304. email = readInput(cli.in, cli.out)
  305. if email == "" {
  306. email = authconfig.Email
  307. }
  308. }
  309. } else {
  310. password = authconfig.Password
  311. email = authconfig.Email
  312. }
  313. authconfig.Username = username
  314. authconfig.Password = password
  315. authconfig.Email = email
  316. authconfig.ServerAddress = serverAddress
  317. cli.configFile.Configs[serverAddress] = authconfig
  318. body, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress])
  319. if statusCode == 401 {
  320. delete(cli.configFile.Configs, serverAddress)
  321. auth.SaveConfig(cli.configFile)
  322. return err
  323. }
  324. if err != nil {
  325. return err
  326. }
  327. var out2 APIAuth
  328. err = json.Unmarshal(body, &out2)
  329. if err != nil {
  330. cli.configFile, _ = auth.LoadConfig(os.Getenv("HOME"))
  331. return err
  332. }
  333. auth.SaveConfig(cli.configFile)
  334. if out2.Status != "" {
  335. fmt.Fprintf(cli.out, "%s\n", out2.Status)
  336. }
  337. return nil
  338. }
  339. // 'docker wait': block until a container stops
  340. func (cli *DockerCli) CmdWait(args ...string) error {
  341. cmd := Subcmd("wait", "CONTAINER [CONTAINER...]", "Block until a container stops, then print its exit code.")
  342. if err := cmd.Parse(args); err != nil {
  343. return nil
  344. }
  345. if cmd.NArg() < 1 {
  346. cmd.Usage()
  347. return nil
  348. }
  349. for _, name := range cmd.Args() {
  350. status, err := waitForExit(cli, name)
  351. if err != nil {
  352. fmt.Fprintf(cli.err, "%s", err)
  353. } else {
  354. fmt.Fprintf(cli.out, "%d\n", status)
  355. }
  356. }
  357. return nil
  358. }
  359. // 'docker version': show version information
  360. func (cli *DockerCli) CmdVersion(args ...string) error {
  361. cmd := Subcmd("version", "", "Show the docker version information.")
  362. if err := cmd.Parse(args); err != nil {
  363. return nil
  364. }
  365. if cmd.NArg() > 0 {
  366. cmd.Usage()
  367. return nil
  368. }
  369. if VERSION != "" {
  370. fmt.Fprintf(cli.out, "Client version: %s\n", VERSION)
  371. }
  372. fmt.Fprintf(cli.out, "Go version (client): %s\n", runtime.Version())
  373. if GITCOMMIT != "" {
  374. fmt.Fprintf(cli.out, "Git commit (client): %s\n", GITCOMMIT)
  375. }
  376. body, _, err := cli.call("GET", "/version", nil)
  377. if err != nil {
  378. return err
  379. }
  380. var out APIVersion
  381. err = json.Unmarshal(body, &out)
  382. if err != nil {
  383. utils.Errorf("Error unmarshal: body: %s, err: %s\n", body, err)
  384. return err
  385. }
  386. if out.Version != "" {
  387. fmt.Fprintf(cli.out, "Server version: %s\n", out.Version)
  388. }
  389. if out.GitCommit != "" {
  390. fmt.Fprintf(cli.out, "Git commit (server): %s\n", out.GitCommit)
  391. }
  392. if out.GoVersion != "" {
  393. fmt.Fprintf(cli.out, "Go version (server): %s\n", out.GoVersion)
  394. }
  395. release := utils.GetReleaseVersion()
  396. if release != "" {
  397. fmt.Fprintf(cli.out, "Last stable version: %s", release)
  398. if (VERSION != "" || out.Version != "") && (strings.Trim(VERSION, "-dev") != release || strings.Trim(out.Version, "-dev") != release) {
  399. fmt.Fprintf(cli.out, ", please update docker")
  400. }
  401. fmt.Fprintf(cli.out, "\n")
  402. }
  403. return nil
  404. }
  405. // 'docker info': display system-wide information.
  406. func (cli *DockerCli) CmdInfo(args ...string) error {
  407. cmd := Subcmd("info", "", "Display system-wide information")
  408. if err := cmd.Parse(args); err != nil {
  409. return nil
  410. }
  411. if cmd.NArg() > 0 {
  412. cmd.Usage()
  413. return nil
  414. }
  415. body, _, err := cli.call("GET", "/info", nil)
  416. if err != nil {
  417. return err
  418. }
  419. var out APIInfo
  420. if err := json.Unmarshal(body, &out); err != nil {
  421. return err
  422. }
  423. fmt.Fprintf(cli.out, "Containers: %d\n", out.Containers)
  424. fmt.Fprintf(cli.out, "Images: %d\n", out.Images)
  425. if out.Debug || os.Getenv("DEBUG") != "" {
  426. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", out.Debug)
  427. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  428. fmt.Fprintf(cli.out, "Fds: %d\n", out.NFd)
  429. fmt.Fprintf(cli.out, "Goroutines: %d\n", out.NGoroutines)
  430. fmt.Fprintf(cli.out, "LXC Version: %s\n", out.LXCVersion)
  431. fmt.Fprintf(cli.out, "EventsListeners: %d\n", out.NEventsListener)
  432. fmt.Fprintf(cli.out, "Kernel Version: %s\n", out.KernelVersion)
  433. }
  434. if len(out.IndexServerAddress) != 0 {
  435. cli.LoadConfigFile()
  436. u := cli.configFile.Configs[out.IndexServerAddress].Username
  437. if len(u) > 0 {
  438. fmt.Fprintf(cli.out, "Username: %v\n", u)
  439. fmt.Fprintf(cli.out, "Registry: %v\n", out.IndexServerAddress)
  440. }
  441. }
  442. if !out.MemoryLimit {
  443. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  444. }
  445. if !out.SwapLimit {
  446. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  447. }
  448. if !out.IPv4Forwarding {
  449. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  450. }
  451. return nil
  452. }
  453. func (cli *DockerCli) CmdStop(args ...string) error {
  454. cmd := Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container (Send SIGTERM, and then SIGKILL after grace period)")
  455. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  456. if err := cmd.Parse(args); err != nil {
  457. return nil
  458. }
  459. if cmd.NArg() < 1 {
  460. cmd.Usage()
  461. return nil
  462. }
  463. v := url.Values{}
  464. v.Set("t", strconv.Itoa(*nSeconds))
  465. for _, name := range cmd.Args() {
  466. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  467. if err != nil {
  468. fmt.Fprintf(cli.err, "%s\n", err)
  469. } else {
  470. fmt.Fprintf(cli.out, "%s\n", name)
  471. }
  472. }
  473. return nil
  474. }
  475. func (cli *DockerCli) CmdRestart(args ...string) error {
  476. cmd := Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  477. nSeconds := cmd.Int("t", 10, "Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default=10")
  478. if err := cmd.Parse(args); err != nil {
  479. return nil
  480. }
  481. if cmd.NArg() < 1 {
  482. cmd.Usage()
  483. return nil
  484. }
  485. v := url.Values{}
  486. v.Set("t", strconv.Itoa(*nSeconds))
  487. for _, name := range cmd.Args() {
  488. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  489. if err != nil {
  490. fmt.Fprintf(cli.err, "%s\n", err)
  491. } else {
  492. fmt.Fprintf(cli.out, "%s\n", name)
  493. }
  494. }
  495. return nil
  496. }
  497. func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal {
  498. sigc := make(chan os.Signal, 1)
  499. utils.CatchAll(sigc)
  500. go func() {
  501. for s := range sigc {
  502. if _, _, err := cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%d", cid, s), nil); err != nil {
  503. utils.Debugf("Error sending signal: %s", err)
  504. }
  505. }
  506. }()
  507. return sigc
  508. }
  509. func (cli *DockerCli) CmdStart(args ...string) error {
  510. cmd := Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  511. attach := cmd.Bool("a", false, "Attach container's stdout/stderr and forward all signals to the process")
  512. openStdin := cmd.Bool("i", false, "Attach container's stdin")
  513. if err := cmd.Parse(args); err != nil {
  514. return nil
  515. }
  516. if cmd.NArg() < 1 {
  517. cmd.Usage()
  518. return nil
  519. }
  520. var cErr chan error
  521. if *attach || *openStdin {
  522. if cmd.NArg() > 1 {
  523. return fmt.Errorf("Impossible to start and attach multiple containers at once.")
  524. }
  525. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  526. if err != nil {
  527. return err
  528. }
  529. container := &Container{}
  530. err = json.Unmarshal(body, container)
  531. if err != nil {
  532. return err
  533. }
  534. if !container.Config.Tty {
  535. sigc := cli.forwardAllSignals(cmd.Arg(0))
  536. defer utils.StopCatch(sigc)
  537. }
  538. if container.Config.Tty && cli.isTerminal {
  539. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  540. return err
  541. }
  542. }
  543. var in io.ReadCloser
  544. v := url.Values{}
  545. v.Set("stream", "1")
  546. if *openStdin && container.Config.OpenStdin {
  547. v.Set("stdin", "1")
  548. in = cli.in
  549. }
  550. v.Set("stdout", "1")
  551. v.Set("stderr", "1")
  552. cErr = utils.Go(func() error {
  553. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil)
  554. })
  555. }
  556. var encounteredError error
  557. for _, name := range cmd.Args() {
  558. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  559. if err != nil {
  560. if !*attach || !*openStdin {
  561. fmt.Fprintf(cli.err, "%s\n", err)
  562. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  563. }
  564. } else {
  565. if !*attach || !*openStdin {
  566. fmt.Fprintf(cli.out, "%s\n", name)
  567. }
  568. }
  569. }
  570. if encounteredError != nil {
  571. if *openStdin || *attach {
  572. cli.in.Close()
  573. <-cErr
  574. }
  575. return encounteredError
  576. }
  577. if *openStdin || *attach {
  578. return <-cErr
  579. }
  580. return nil
  581. }
  582. func (cli *DockerCli) CmdInspect(args ...string) error {
  583. cmd := Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  584. if err := cmd.Parse(args); err != nil {
  585. return nil
  586. }
  587. if cmd.NArg() < 1 {
  588. cmd.Usage()
  589. return nil
  590. }
  591. indented := new(bytes.Buffer)
  592. status := 0
  593. for _, name := range args {
  594. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  595. if err != nil {
  596. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  597. if err != nil {
  598. if strings.Contains(err.Error(), "No such") {
  599. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  600. } else {
  601. fmt.Fprintf(cli.err, "%s", err)
  602. }
  603. status = 1
  604. continue
  605. }
  606. }
  607. if err = json.Indent(indented, obj, "", " "); err != nil {
  608. fmt.Fprintf(cli.err, "%s\n", err)
  609. status = 1
  610. continue
  611. }
  612. indented.WriteString(",")
  613. }
  614. if indented.Len() > 0 {
  615. // Remove trailing ','
  616. indented.Truncate(indented.Len() - 1)
  617. }
  618. fmt.Fprintf(cli.out, "[")
  619. if _, err := io.Copy(cli.out, indented); err != nil {
  620. return err
  621. }
  622. fmt.Fprintf(cli.out, "]")
  623. if status != 0 {
  624. return &utils.StatusError{Status: status}
  625. }
  626. return nil
  627. }
  628. func (cli *DockerCli) CmdTop(args ...string) error {
  629. cmd := Subcmd("top", "CONTAINER [ps OPTIONS]", "Lookup the running processes of a container")
  630. if err := cmd.Parse(args); err != nil {
  631. return nil
  632. }
  633. if cmd.NArg() == 0 {
  634. cmd.Usage()
  635. return nil
  636. }
  637. val := url.Values{}
  638. if cmd.NArg() > 1 {
  639. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  640. }
  641. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  642. if err != nil {
  643. return err
  644. }
  645. procs := APITop{}
  646. err = json.Unmarshal(body, &procs)
  647. if err != nil {
  648. return err
  649. }
  650. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  651. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  652. for _, proc := range procs.Processes {
  653. fmt.Fprintln(w, strings.Join(proc, "\t"))
  654. }
  655. w.Flush()
  656. return nil
  657. }
  658. func (cli *DockerCli) CmdPort(args ...string) error {
  659. cmd := Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  660. if err := cmd.Parse(args); err != nil {
  661. return nil
  662. }
  663. if cmd.NArg() != 2 {
  664. cmd.Usage()
  665. return nil
  666. }
  667. port := cmd.Arg(1)
  668. proto := "tcp"
  669. parts := strings.SplitN(port, "/", 2)
  670. if len(parts) == 2 && len(parts[1]) != 0 {
  671. port = parts[0]
  672. proto = parts[1]
  673. }
  674. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  675. if err != nil {
  676. return err
  677. }
  678. var out Container
  679. err = json.Unmarshal(body, &out)
  680. if err != nil {
  681. return err
  682. }
  683. if frontends, exists := out.NetworkSettings.Ports[Port(port+"/"+proto)]; exists {
  684. if frontends == nil {
  685. fmt.Fprintf(cli.out, "%s\n", port)
  686. } else {
  687. for _, frontend := range frontends {
  688. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  689. }
  690. }
  691. } else {
  692. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  693. }
  694. return nil
  695. }
  696. // 'docker rmi IMAGE' removes all images with the name IMAGE
  697. func (cli *DockerCli) CmdRmi(args ...string) error {
  698. cmd := Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  699. if err := cmd.Parse(args); err != nil {
  700. return nil
  701. }
  702. if cmd.NArg() < 1 {
  703. cmd.Usage()
  704. return nil
  705. }
  706. for _, name := range cmd.Args() {
  707. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  708. if err != nil {
  709. fmt.Fprintf(cli.err, "%s", err)
  710. } else {
  711. var outs []APIRmi
  712. err = json.Unmarshal(body, &outs)
  713. if err != nil {
  714. return err
  715. }
  716. for _, out := range outs {
  717. if out.Deleted != "" {
  718. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  719. } else {
  720. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  721. }
  722. }
  723. }
  724. }
  725. return nil
  726. }
  727. func (cli *DockerCli) CmdHistory(args ...string) error {
  728. cmd := Subcmd("history", "[OPTIONS] IMAGE", "Show the history of an image")
  729. quiet := cmd.Bool("q", false, "only show numeric IDs")
  730. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  731. if err := cmd.Parse(args); err != nil {
  732. return nil
  733. }
  734. if cmd.NArg() != 1 {
  735. cmd.Usage()
  736. return nil
  737. }
  738. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  739. if err != nil {
  740. return err
  741. }
  742. var outs []APIHistory
  743. err = json.Unmarshal(body, &outs)
  744. if err != nil {
  745. return err
  746. }
  747. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  748. if !*quiet {
  749. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  750. }
  751. for _, out := range outs {
  752. if !*quiet {
  753. if *noTrunc {
  754. fmt.Fprintf(w, "%s\t", out.ID)
  755. } else {
  756. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  757. }
  758. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  759. if *noTrunc {
  760. fmt.Fprintf(w, "%s\t", out.CreatedBy)
  761. } else {
  762. fmt.Fprintf(w, "%s\t", utils.Trunc(out.CreatedBy, 45))
  763. }
  764. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  765. } else {
  766. if *noTrunc {
  767. fmt.Fprintln(w, out.ID)
  768. } else {
  769. fmt.Fprintln(w, utils.TruncateID(out.ID))
  770. }
  771. }
  772. }
  773. w.Flush()
  774. return nil
  775. }
  776. func (cli *DockerCli) CmdRm(args ...string) error {
  777. cmd := Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  778. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  779. link := cmd.Bool("link", false, "Remove the specified link and not the underlying container")
  780. if err := cmd.Parse(args); err != nil {
  781. return nil
  782. }
  783. if cmd.NArg() < 1 {
  784. cmd.Usage()
  785. return nil
  786. }
  787. val := url.Values{}
  788. if *v {
  789. val.Set("v", "1")
  790. }
  791. if *link {
  792. val.Set("link", "1")
  793. }
  794. for _, name := range cmd.Args() {
  795. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  796. if err != nil {
  797. fmt.Fprintf(cli.err, "%s\n", err)
  798. } else {
  799. fmt.Fprintf(cli.out, "%s\n", name)
  800. }
  801. }
  802. return nil
  803. }
  804. // 'docker kill NAME' kills a running container
  805. func (cli *DockerCli) CmdKill(args ...string) error {
  806. cmd := Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container (send SIGKILL)")
  807. if err := cmd.Parse(args); err != nil {
  808. return nil
  809. }
  810. if cmd.NArg() < 1 {
  811. cmd.Usage()
  812. return nil
  813. }
  814. for _, name := range args {
  815. _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil)
  816. if err != nil {
  817. fmt.Fprintf(cli.err, "%s\n", err)
  818. } else {
  819. fmt.Fprintf(cli.out, "%s\n", name)
  820. }
  821. }
  822. return nil
  823. }
  824. func (cli *DockerCli) CmdImport(args ...string) error {
  825. cmd := Subcmd("import", "URL|- [REPOSITORY[:TAG]]", "Create a new filesystem image from the contents of a tarball(.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz).")
  826. if err := cmd.Parse(args); err != nil {
  827. return nil
  828. }
  829. if cmd.NArg() < 1 {
  830. cmd.Usage()
  831. return nil
  832. }
  833. src := cmd.Arg(0)
  834. repository, tag := utils.ParseRepositoryTag(cmd.Arg(1))
  835. v := url.Values{}
  836. v.Set("repo", repository)
  837. v.Set("tag", tag)
  838. v.Set("fromSrc", src)
  839. var in io.Reader
  840. if src == "-" {
  841. in = cli.in
  842. }
  843. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  844. }
  845. func (cli *DockerCli) CmdPush(args ...string) error {
  846. cmd := Subcmd("push", "NAME", "Push an image or a repository to the registry")
  847. if err := cmd.Parse(args); err != nil {
  848. return nil
  849. }
  850. name := cmd.Arg(0)
  851. if name == "" {
  852. cmd.Usage()
  853. return nil
  854. }
  855. cli.LoadConfigFile()
  856. // Resolve the Repository name from fqn to endpoint + name
  857. endpoint, _, err := registry.ResolveRepositoryName(name)
  858. if err != nil {
  859. return err
  860. }
  861. // Resolve the Auth config relevant for this server
  862. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  863. // If we're not using a custom registry, we know the restrictions
  864. // applied to repository names and can warn the user in advance.
  865. // Custom repositories can have different rules, and we must also
  866. // allow pushing by image ID.
  867. if len(strings.SplitN(name, "/", 2)) == 1 {
  868. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  869. if username == "" {
  870. username = "<user>"
  871. }
  872. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  873. }
  874. v := url.Values{}
  875. push := func(authConfig auth.AuthConfig) error {
  876. buf, err := json.Marshal(authConfig)
  877. if err != nil {
  878. return err
  879. }
  880. registryAuthHeader := []string{
  881. base64.URLEncoding.EncodeToString(buf),
  882. }
  883. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  884. "X-Registry-Auth": registryAuthHeader,
  885. })
  886. }
  887. if err := push(authConfig); err != nil {
  888. if err.Error() == registry.ErrLoginRequired.Error() {
  889. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  890. if err := cli.CmdLogin(endpoint); err != nil {
  891. return err
  892. }
  893. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  894. return push(authConfig)
  895. }
  896. return err
  897. }
  898. return nil
  899. }
  900. func (cli *DockerCli) CmdPull(args ...string) error {
  901. cmd := Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  902. tag := cmd.String("t", "", "Download tagged image in repository")
  903. if err := cmd.Parse(args); err != nil {
  904. return nil
  905. }
  906. if cmd.NArg() != 1 {
  907. cmd.Usage()
  908. return nil
  909. }
  910. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  911. if *tag == "" {
  912. *tag = parsedTag
  913. }
  914. // Resolve the Repository name from fqn to endpoint + name
  915. endpoint, _, err := registry.ResolveRepositoryName(remote)
  916. if err != nil {
  917. return err
  918. }
  919. cli.LoadConfigFile()
  920. // Resolve the Auth config relevant for this server
  921. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  922. v := url.Values{}
  923. v.Set("fromImage", remote)
  924. v.Set("tag", *tag)
  925. pull := func(authConfig auth.AuthConfig) error {
  926. buf, err := json.Marshal(authConfig)
  927. if err != nil {
  928. return err
  929. }
  930. registryAuthHeader := []string{
  931. base64.URLEncoding.EncodeToString(buf),
  932. }
  933. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  934. "X-Registry-Auth": registryAuthHeader,
  935. })
  936. }
  937. if err := pull(authConfig); err != nil {
  938. if err.Error() == registry.ErrLoginRequired.Error() {
  939. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  940. if err := cli.CmdLogin(endpoint); err != nil {
  941. return err
  942. }
  943. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  944. return pull(authConfig)
  945. }
  946. return err
  947. }
  948. return nil
  949. }
  950. func (cli *DockerCli) CmdImages(args ...string) error {
  951. cmd := Subcmd("images", "[OPTIONS] [NAME]", "List images")
  952. quiet := cmd.Bool("q", false, "only show numeric IDs")
  953. all := cmd.Bool("a", false, "show all images")
  954. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  955. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  956. flTree := cmd.Bool("tree", false, "output graph in tree format")
  957. if err := cmd.Parse(args); err != nil {
  958. return nil
  959. }
  960. if cmd.NArg() > 1 {
  961. cmd.Usage()
  962. return nil
  963. }
  964. if *flViz {
  965. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  966. if err != nil {
  967. return err
  968. }
  969. var outs []APIImages
  970. err = json.Unmarshal(body, &outs)
  971. if err != nil {
  972. return err
  973. }
  974. fmt.Fprintf(cli.out, "digraph docker {\n")
  975. for _, image := range outs {
  976. if image.ParentId == "" {
  977. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", utils.TruncateID(image.ID))
  978. } else {
  979. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", utils.TruncateID(image.ParentId), utils.TruncateID(image.ID))
  980. }
  981. if image.RepoTags[0] != "<none>:<none>" {
  982. fmt.Fprintf(cli.out, " \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n", utils.TruncateID(image.ID), utils.TruncateID(image.ID), strings.Join(image.RepoTags, "\\n"))
  983. }
  984. }
  985. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  986. } else if *flTree {
  987. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  988. if err != nil {
  989. return err
  990. }
  991. var outs []APIImages
  992. if err := json.Unmarshal(body, &outs); err != nil {
  993. return err
  994. }
  995. var (
  996. startImageArg = cmd.Arg(0)
  997. startImage APIImages
  998. roots []APIImages
  999. byParent = make(map[string][]APIImages)
  1000. )
  1001. for _, image := range outs {
  1002. if image.ParentId == "" {
  1003. roots = append(roots, image)
  1004. } else {
  1005. if children, exists := byParent[image.ParentId]; exists {
  1006. byParent[image.ParentId] = append(children, image)
  1007. } else {
  1008. byParent[image.ParentId] = []APIImages{image}
  1009. }
  1010. }
  1011. if startImageArg != "" {
  1012. if startImageArg == image.ID || startImageArg == utils.TruncateID(image.ID) {
  1013. startImage = image
  1014. }
  1015. for _, repotag := range image.RepoTags {
  1016. if repotag == startImageArg {
  1017. startImage = image
  1018. }
  1019. }
  1020. }
  1021. }
  1022. if startImageArg != "" {
  1023. WalkTree(cli, noTrunc, []APIImages{startImage}, byParent, "")
  1024. } else {
  1025. WalkTree(cli, noTrunc, roots, byParent, "")
  1026. }
  1027. } else {
  1028. v := url.Values{}
  1029. if cmd.NArg() == 1 {
  1030. v.Set("filter", cmd.Arg(0))
  1031. }
  1032. if *all {
  1033. v.Set("all", "1")
  1034. }
  1035. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  1036. if err != nil {
  1037. return err
  1038. }
  1039. var outs []APIImages
  1040. err = json.Unmarshal(body, &outs)
  1041. if err != nil {
  1042. return err
  1043. }
  1044. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1045. if !*quiet {
  1046. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tSIZE")
  1047. }
  1048. var repo string
  1049. var tag string
  1050. for _, out := range outs {
  1051. for _, repotag := range out.RepoTags {
  1052. components := strings.SplitN(repotag, ":", 2)
  1053. repo = components[0]
  1054. tag = components[1]
  1055. if !*noTrunc {
  1056. out.ID = utils.TruncateID(out.ID)
  1057. }
  1058. if !*quiet {
  1059. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t", repo, tag, out.ID, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
  1060. if out.VirtualSize > 0 {
  1061. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  1062. } else {
  1063. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  1064. }
  1065. } else {
  1066. fmt.Fprintln(w, out.ID)
  1067. }
  1068. }
  1069. }
  1070. if !*quiet {
  1071. w.Flush()
  1072. }
  1073. }
  1074. return nil
  1075. }
  1076. func WalkTree(cli *DockerCli, noTrunc *bool, images []APIImages, byParent map[string][]APIImages, prefix string) {
  1077. if len(images) > 1 {
  1078. length := len(images)
  1079. for index, image := range images {
  1080. if index+1 == length {
  1081. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1082. if subimages, exists := byParent[image.ID]; exists {
  1083. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1084. }
  1085. } else {
  1086. PrintTreeNode(cli, noTrunc, image, prefix+"|─")
  1087. if subimages, exists := byParent[image.ID]; exists {
  1088. WalkTree(cli, noTrunc, subimages, byParent, prefix+"| ")
  1089. }
  1090. }
  1091. }
  1092. } else {
  1093. for _, image := range images {
  1094. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1095. if subimages, exists := byParent[image.ID]; exists {
  1096. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1097. }
  1098. }
  1099. }
  1100. }
  1101. func PrintTreeNode(cli *DockerCli, noTrunc *bool, image APIImages, prefix string) {
  1102. var imageID string
  1103. if *noTrunc {
  1104. imageID = image.ID
  1105. } else {
  1106. imageID = utils.TruncateID(image.ID)
  1107. }
  1108. fmt.Fprintf(cli.out, "%s%s Size: %s (virtual %s)", prefix, imageID, utils.HumanSize(image.Size), utils.HumanSize(image.VirtualSize))
  1109. if image.RepoTags[0] != "<none>:<none>" {
  1110. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.RepoTags, ","))
  1111. } else {
  1112. fmt.Fprint(cli.out, "\n")
  1113. }
  1114. }
  1115. func displayablePorts(ports []APIPort) string {
  1116. result := []string{}
  1117. for _, port := range ports {
  1118. if port.IP == "" {
  1119. result = append(result, fmt.Sprintf("%d/%s", port.PublicPort, port.Type))
  1120. } else {
  1121. result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
  1122. }
  1123. }
  1124. sort.Strings(result)
  1125. return strings.Join(result, ", ")
  1126. }
  1127. func (cli *DockerCli) CmdPs(args ...string) error {
  1128. cmd := Subcmd("ps", "[OPTIONS]", "List containers")
  1129. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  1130. size := cmd.Bool("s", false, "Display sizes")
  1131. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  1132. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1133. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  1134. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  1135. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  1136. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  1137. if err := cmd.Parse(args); err != nil {
  1138. return nil
  1139. }
  1140. v := url.Values{}
  1141. if *last == -1 && *nLatest {
  1142. *last = 1
  1143. }
  1144. if *all {
  1145. v.Set("all", "1")
  1146. }
  1147. if *last != -1 {
  1148. v.Set("limit", strconv.Itoa(*last))
  1149. }
  1150. if *since != "" {
  1151. v.Set("since", *since)
  1152. }
  1153. if *before != "" {
  1154. v.Set("before", *before)
  1155. }
  1156. if *size {
  1157. v.Set("size", "1")
  1158. }
  1159. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  1160. if err != nil {
  1161. return err
  1162. }
  1163. var outs []APIContainers
  1164. err = json.Unmarshal(body, &outs)
  1165. if err != nil {
  1166. return err
  1167. }
  1168. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1169. if !*quiet {
  1170. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1171. if *size {
  1172. fmt.Fprintln(w, "\tSIZE")
  1173. } else {
  1174. fmt.Fprint(w, "\n")
  1175. }
  1176. }
  1177. for _, out := range outs {
  1178. if !*noTrunc {
  1179. out.ID = utils.TruncateID(out.ID)
  1180. }
  1181. // Remove the leading / from the names
  1182. for i := 0; i < len(out.Names); i++ {
  1183. out.Names[i] = out.Names[i][1:]
  1184. }
  1185. if !*quiet {
  1186. if !*noTrunc {
  1187. out.Command = utils.Trunc(out.Command, 20)
  1188. }
  1189. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", out.ID, out.Image, out.Command, utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, displayablePorts(out.Ports), strings.Join(out.Names, ","))
  1190. if *size {
  1191. if out.SizeRootFs > 0 {
  1192. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  1193. } else {
  1194. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1195. }
  1196. } else {
  1197. fmt.Fprint(w, "\n")
  1198. }
  1199. } else {
  1200. fmt.Fprintln(w, out.ID)
  1201. }
  1202. }
  1203. if !*quiet {
  1204. w.Flush()
  1205. }
  1206. return nil
  1207. }
  1208. func (cli *DockerCli) CmdCommit(args ...string) error {
  1209. cmd := Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1210. flComment := cmd.String("m", "", "Commit message")
  1211. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1212. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: {"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1213. if err := cmd.Parse(args); err != nil {
  1214. return nil
  1215. }
  1216. name := cmd.Arg(0)
  1217. repository, tag := utils.ParseRepositoryTag(cmd.Arg(1))
  1218. if name == "" {
  1219. cmd.Usage()
  1220. return nil
  1221. }
  1222. v := url.Values{}
  1223. v.Set("container", name)
  1224. v.Set("repo", repository)
  1225. v.Set("tag", tag)
  1226. v.Set("comment", *flComment)
  1227. v.Set("author", *flAuthor)
  1228. var config *Config
  1229. if *flConfig != "" {
  1230. config = &Config{}
  1231. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1232. return err
  1233. }
  1234. }
  1235. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1236. if err != nil {
  1237. return err
  1238. }
  1239. apiID := &APIID{}
  1240. err = json.Unmarshal(body, apiID)
  1241. if err != nil {
  1242. return err
  1243. }
  1244. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1245. return nil
  1246. }
  1247. func (cli *DockerCli) CmdEvents(args ...string) error {
  1248. cmd := Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1249. since := cmd.String("since", "", "Show events previously created (used for polling).")
  1250. if err := cmd.Parse(args); err != nil {
  1251. return nil
  1252. }
  1253. if cmd.NArg() != 0 {
  1254. cmd.Usage()
  1255. return nil
  1256. }
  1257. v := url.Values{}
  1258. if *since != "" {
  1259. v.Set("since", *since)
  1260. }
  1261. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1262. return err
  1263. }
  1264. return nil
  1265. }
  1266. func (cli *DockerCli) CmdExport(args ...string) error {
  1267. cmd := Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive")
  1268. if err := cmd.Parse(args); err != nil {
  1269. return nil
  1270. }
  1271. if cmd.NArg() != 1 {
  1272. cmd.Usage()
  1273. return nil
  1274. }
  1275. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1276. return err
  1277. }
  1278. return nil
  1279. }
  1280. func (cli *DockerCli) CmdDiff(args ...string) error {
  1281. cmd := Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1282. if err := cmd.Parse(args); err != nil {
  1283. return nil
  1284. }
  1285. if cmd.NArg() != 1 {
  1286. cmd.Usage()
  1287. return nil
  1288. }
  1289. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1290. if err != nil {
  1291. return err
  1292. }
  1293. changes := []Change{}
  1294. err = json.Unmarshal(body, &changes)
  1295. if err != nil {
  1296. return err
  1297. }
  1298. for _, change := range changes {
  1299. fmt.Fprintf(cli.out, "%s\n", change.String())
  1300. }
  1301. return nil
  1302. }
  1303. func (cli *DockerCli) CmdLogs(args ...string) error {
  1304. cmd := Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1305. if err := cmd.Parse(args); err != nil {
  1306. return nil
  1307. }
  1308. if cmd.NArg() != 1 {
  1309. cmd.Usage()
  1310. return nil
  1311. }
  1312. name := cmd.Arg(0)
  1313. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1314. if err != nil {
  1315. return err
  1316. }
  1317. container := &Container{}
  1318. err = json.Unmarshal(body, container)
  1319. if err != nil {
  1320. return err
  1321. }
  1322. if err := cli.hijack("POST", "/containers/"+name+"/attach?logs=1&stdout=1&stderr=1", container.Config.Tty, nil, cli.out, cli.err, nil); err != nil {
  1323. return err
  1324. }
  1325. return nil
  1326. }
  1327. func (cli *DockerCli) CmdAttach(args ...string) error {
  1328. cmd := Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1329. noStdin := cmd.Bool("nostdin", false, "Do not attach stdin")
  1330. proxy := cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1331. if err := cmd.Parse(args); err != nil {
  1332. return nil
  1333. }
  1334. if cmd.NArg() != 1 {
  1335. cmd.Usage()
  1336. return nil
  1337. }
  1338. name := cmd.Arg(0)
  1339. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1340. if err != nil {
  1341. return err
  1342. }
  1343. container := &Container{}
  1344. err = json.Unmarshal(body, container)
  1345. if err != nil {
  1346. return err
  1347. }
  1348. if !container.State.Running {
  1349. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1350. }
  1351. if container.Config.Tty && cli.isTerminal {
  1352. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1353. utils.Debugf("Error monitoring TTY size: %s", err)
  1354. }
  1355. }
  1356. var in io.ReadCloser
  1357. v := url.Values{}
  1358. v.Set("stream", "1")
  1359. if !*noStdin && container.Config.OpenStdin {
  1360. v.Set("stdin", "1")
  1361. in = cli.in
  1362. }
  1363. v.Set("stdout", "1")
  1364. v.Set("stderr", "1")
  1365. if *proxy && !container.Config.Tty {
  1366. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1367. defer utils.StopCatch(sigc)
  1368. }
  1369. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1370. return err
  1371. }
  1372. return nil
  1373. }
  1374. func (cli *DockerCli) CmdSearch(args ...string) error {
  1375. cmd := Subcmd("search", "TERM", "Search the docker index for images")
  1376. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1377. trusted := cmd.Bool("trusted", false, "Only show trusted builds")
  1378. stars := cmd.Int("stars", 0, "Only displays with at least xxx stars")
  1379. if err := cmd.Parse(args); err != nil {
  1380. return nil
  1381. }
  1382. if cmd.NArg() != 1 {
  1383. cmd.Usage()
  1384. return nil
  1385. }
  1386. v := url.Values{}
  1387. v.Set("term", cmd.Arg(0))
  1388. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1389. if err != nil {
  1390. return err
  1391. }
  1392. outs := []registry.SearchResult{}
  1393. err = json.Unmarshal(body, &outs)
  1394. if err != nil {
  1395. return err
  1396. }
  1397. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1398. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tTRUSTED\n")
  1399. for _, out := range outs {
  1400. if (*trusted && !out.IsTrusted) || (*stars > out.StarCount) {
  1401. continue
  1402. }
  1403. desc := strings.Replace(out.Description, "\n", " ", -1)
  1404. desc = strings.Replace(desc, "\r", " ", -1)
  1405. if !*noTrunc && len(desc) > 45 {
  1406. desc = utils.Trunc(desc, 42) + "..."
  1407. }
  1408. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Name, desc, out.StarCount)
  1409. if out.IsOfficial {
  1410. fmt.Fprint(w, "[OK]")
  1411. }
  1412. fmt.Fprint(w, "\t")
  1413. if out.IsTrusted {
  1414. fmt.Fprint(w, "[OK]")
  1415. }
  1416. fmt.Fprint(w, "\n")
  1417. }
  1418. w.Flush()
  1419. return nil
  1420. }
  1421. // Ports type - Used to parse multiple -p flags
  1422. type ports []int
  1423. // AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
  1424. type AttachOpts map[string]bool
  1425. func NewAttachOpts() AttachOpts {
  1426. return make(AttachOpts)
  1427. }
  1428. func (opts AttachOpts) String() string {
  1429. // Cast to underlying map type to avoid infinite recursion
  1430. return fmt.Sprintf("%v", map[string]bool(opts))
  1431. }
  1432. func (opts AttachOpts) Set(val string) error {
  1433. if val != "stdin" && val != "stdout" && val != "stderr" {
  1434. return fmt.Errorf("Unsupported stream name: %s", val)
  1435. }
  1436. opts[val] = true
  1437. return nil
  1438. }
  1439. func (opts AttachOpts) Get(val string) bool {
  1440. if res, exists := opts[val]; exists {
  1441. return res
  1442. }
  1443. return false
  1444. }
  1445. // PathOpts stores a unique set of absolute paths
  1446. type PathOpts map[string]struct{}
  1447. func NewPathOpts() PathOpts {
  1448. return make(PathOpts)
  1449. }
  1450. func (opts PathOpts) String() string {
  1451. return fmt.Sprintf("%v", map[string]struct{}(opts))
  1452. }
  1453. func (opts PathOpts) Set(val string) error {
  1454. var containerPath string
  1455. splited := strings.SplitN(val, ":", 2)
  1456. if len(splited) == 1 {
  1457. containerPath = splited[0]
  1458. val = filepath.Clean(splited[0])
  1459. } else {
  1460. containerPath = splited[1]
  1461. val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
  1462. }
  1463. if !filepath.IsAbs(containerPath) {
  1464. utils.Debugf("%s is not an absolute path", containerPath)
  1465. return fmt.Errorf("%s is not an absolute path", containerPath)
  1466. }
  1467. opts[val] = struct{}{}
  1468. return nil
  1469. }
  1470. func (cli *DockerCli) CmdTag(args ...string) error {
  1471. cmd := Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY[:TAG]", "Tag an image into a repository")
  1472. force := cmd.Bool("f", false, "Force")
  1473. if err := cmd.Parse(args); err != nil {
  1474. return nil
  1475. }
  1476. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1477. cmd.Usage()
  1478. return nil
  1479. }
  1480. v := url.Values{}
  1481. repository, tag := utils.ParseRepositoryTag(cmd.Arg(1))
  1482. v.Set("repo", repository)
  1483. v.Set("tag", tag)
  1484. if *force {
  1485. v.Set("force", "1")
  1486. }
  1487. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1488. return err
  1489. }
  1490. return nil
  1491. }
  1492. func (cli *DockerCli) CmdRun(args ...string) error {
  1493. config, hostConfig, cmd, err := ParseRun(args, nil)
  1494. if err != nil {
  1495. return err
  1496. }
  1497. if config.Image == "" {
  1498. cmd.Usage()
  1499. return nil
  1500. }
  1501. flRm := cmd.Lookup("rm")
  1502. autoRemove, _ := strconv.ParseBool(flRm.Value.String())
  1503. flSigProxy := cmd.Lookup("sig-proxy")
  1504. sigProxy, _ := strconv.ParseBool(flSigProxy.Value.String())
  1505. flName := cmd.Lookup("name")
  1506. if config.Tty {
  1507. sigProxy = false
  1508. }
  1509. var containerIDFile *os.File
  1510. if len(hostConfig.ContainerIDFile) > 0 {
  1511. if _, err := ioutil.ReadFile(hostConfig.ContainerIDFile); err == nil {
  1512. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1513. }
  1514. containerIDFile, err = os.Create(hostConfig.ContainerIDFile)
  1515. if err != nil {
  1516. return fmt.Errorf("failed to create the container ID file: %s", err)
  1517. }
  1518. defer containerIDFile.Close()
  1519. }
  1520. containerValues := url.Values{}
  1521. name := flName.Value.String()
  1522. if name != "" {
  1523. containerValues.Set("name", name)
  1524. }
  1525. //create the container
  1526. body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1527. //if image not found try to pull it
  1528. if statusCode == 404 {
  1529. _, tag := utils.ParseRepositoryTag(config.Image)
  1530. if tag == "" {
  1531. tag = DEFAULTTAG
  1532. }
  1533. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1534. v := url.Values{}
  1535. repos, tag := utils.ParseRepositoryTag(config.Image)
  1536. v.Set("fromImage", repos)
  1537. v.Set("tag", tag)
  1538. // Resolve the Repository name from fqn to endpoint + name
  1539. var endpoint string
  1540. endpoint, _, err = registry.ResolveRepositoryName(repos)
  1541. if err != nil {
  1542. return err
  1543. }
  1544. // Load the auth config file, to be able to pull the image
  1545. cli.LoadConfigFile()
  1546. // Resolve the Auth config relevant for this server
  1547. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1548. buf, err := json.Marshal(authConfig)
  1549. if err != nil {
  1550. return err
  1551. }
  1552. registryAuthHeader := []string{
  1553. base64.URLEncoding.EncodeToString(buf),
  1554. }
  1555. err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{
  1556. "X-Registry-Auth": registryAuthHeader,
  1557. })
  1558. if err != nil {
  1559. return err
  1560. }
  1561. body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1562. if err != nil {
  1563. return err
  1564. }
  1565. }
  1566. if err != nil {
  1567. return err
  1568. }
  1569. runResult := &APIRun{}
  1570. err = json.Unmarshal(body, runResult)
  1571. if err != nil {
  1572. return err
  1573. }
  1574. for _, warning := range runResult.Warnings {
  1575. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1576. }
  1577. if len(hostConfig.ContainerIDFile) > 0 {
  1578. if _, err = containerIDFile.WriteString(runResult.ID); err != nil {
  1579. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1580. }
  1581. }
  1582. if sigProxy {
  1583. sigc := cli.forwardAllSignals(runResult.ID)
  1584. defer utils.StopCatch(sigc)
  1585. }
  1586. var (
  1587. wait chan struct{}
  1588. errCh chan error
  1589. )
  1590. if !config.AttachStdout && !config.AttachStderr {
  1591. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1592. wait = make(chan struct{})
  1593. go func() {
  1594. defer close(wait)
  1595. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1596. }()
  1597. }
  1598. hijacked := make(chan bool)
  1599. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1600. v := url.Values{}
  1601. v.Set("stream", "1")
  1602. var out, stderr io.Writer
  1603. var in io.ReadCloser
  1604. if config.AttachStdin {
  1605. v.Set("stdin", "1")
  1606. in = cli.in
  1607. }
  1608. if config.AttachStdout {
  1609. v.Set("stdout", "1")
  1610. out = cli.out
  1611. }
  1612. if config.AttachStderr {
  1613. v.Set("stderr", "1")
  1614. if config.Tty {
  1615. stderr = cli.out
  1616. } else {
  1617. stderr = cli.err
  1618. }
  1619. }
  1620. errCh = utils.Go(func() error {
  1621. return cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1622. })
  1623. } else {
  1624. close(hijacked)
  1625. }
  1626. // Acknowledge the hijack before starting
  1627. select {
  1628. case <-hijacked:
  1629. case err := <-errCh:
  1630. if err != nil {
  1631. utils.Debugf("Error hijack: %s", err)
  1632. return err
  1633. }
  1634. }
  1635. //start the container
  1636. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1637. return err
  1638. }
  1639. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1640. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1641. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1642. }
  1643. }
  1644. if errCh != nil {
  1645. if err := <-errCh; err != nil {
  1646. utils.Debugf("Error hijack: %s", err)
  1647. return err
  1648. }
  1649. }
  1650. if !config.AttachStdout && !config.AttachStderr {
  1651. // Detached mode
  1652. <-wait
  1653. } else {
  1654. running, status, err := getExitCode(cli, runResult.ID)
  1655. if err != nil {
  1656. return err
  1657. }
  1658. if autoRemove {
  1659. if running {
  1660. return fmt.Errorf("Impossible to auto-remove a detached container")
  1661. }
  1662. // Wait for the process to
  1663. if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
  1664. return err
  1665. }
  1666. if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
  1667. return err
  1668. }
  1669. }
  1670. if status != 0 {
  1671. return &utils.StatusError{Status: status}
  1672. }
  1673. }
  1674. return nil
  1675. }
  1676. func (cli *DockerCli) CmdCp(args ...string) error {
  1677. cmd := Subcmd("cp", "CONTAINER:RESOURCE HOSTPATH", "Copy files/folders from the RESOURCE to the HOSTPATH")
  1678. if err := cmd.Parse(args); err != nil {
  1679. return nil
  1680. }
  1681. if cmd.NArg() != 2 {
  1682. cmd.Usage()
  1683. return nil
  1684. }
  1685. var copyData APICopy
  1686. info := strings.Split(cmd.Arg(0), ":")
  1687. if len(info) != 2 {
  1688. return fmt.Errorf("Error: Resource not specified")
  1689. }
  1690. copyData.Resource = info[1]
  1691. copyData.HostPath = cmd.Arg(1)
  1692. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1693. if err != nil {
  1694. return err
  1695. }
  1696. if statusCode == 200 {
  1697. r := bytes.NewReader(data)
  1698. if err := archive.Untar(r, copyData.HostPath, nil); err != nil {
  1699. return err
  1700. }
  1701. }
  1702. return nil
  1703. }
  1704. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1705. var params io.Reader
  1706. if data != nil {
  1707. buf, err := json.Marshal(data)
  1708. if err != nil {
  1709. return nil, -1, err
  1710. }
  1711. params = bytes.NewBuffer(buf)
  1712. }
  1713. // fixme: refactor client to support redirect
  1714. re := regexp.MustCompile("/+")
  1715. path = re.ReplaceAllString(path, "/")
  1716. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1717. if err != nil {
  1718. return nil, -1, err
  1719. }
  1720. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1721. req.Host = cli.addr
  1722. if data != nil {
  1723. req.Header.Set("Content-Type", "application/json")
  1724. } else if method == "POST" {
  1725. req.Header.Set("Content-Type", "plain/text")
  1726. }
  1727. dial, err := net.Dial(cli.proto, cli.addr)
  1728. if err != nil {
  1729. if strings.Contains(err.Error(), "connection refused") {
  1730. return nil, -1, ErrConnectionRefused
  1731. }
  1732. return nil, -1, err
  1733. }
  1734. clientconn := httputil.NewClientConn(dial, nil)
  1735. resp, err := clientconn.Do(req)
  1736. defer clientconn.Close()
  1737. if err != nil {
  1738. if strings.Contains(err.Error(), "connection refused") {
  1739. return nil, -1, ErrConnectionRefused
  1740. }
  1741. return nil, -1, err
  1742. }
  1743. defer resp.Body.Close()
  1744. body, err := ioutil.ReadAll(resp.Body)
  1745. if err != nil {
  1746. return nil, -1, err
  1747. }
  1748. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1749. if len(body) == 0 {
  1750. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1751. }
  1752. return nil, resp.StatusCode, fmt.Errorf("Error: %s", body)
  1753. }
  1754. return body, resp.StatusCode, nil
  1755. }
  1756. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1757. if (method == "POST" || method == "PUT") && in == nil {
  1758. in = bytes.NewReader([]byte{})
  1759. }
  1760. // fixme: refactor client to support redirect
  1761. re := regexp.MustCompile("/+")
  1762. path = re.ReplaceAllString(path, "/")
  1763. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1764. if err != nil {
  1765. return err
  1766. }
  1767. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1768. req.Host = cli.addr
  1769. if method == "POST" {
  1770. req.Header.Set("Content-Type", "plain/text")
  1771. }
  1772. if headers != nil {
  1773. for k, v := range headers {
  1774. req.Header[k] = v
  1775. }
  1776. }
  1777. dial, err := net.Dial(cli.proto, cli.addr)
  1778. if err != nil {
  1779. if strings.Contains(err.Error(), "connection refused") {
  1780. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1781. }
  1782. return err
  1783. }
  1784. clientconn := httputil.NewClientConn(dial, nil)
  1785. resp, err := clientconn.Do(req)
  1786. defer clientconn.Close()
  1787. if err != nil {
  1788. if strings.Contains(err.Error(), "connection refused") {
  1789. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1790. }
  1791. return err
  1792. }
  1793. defer resp.Body.Close()
  1794. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1795. body, err := ioutil.ReadAll(resp.Body)
  1796. if err != nil {
  1797. return err
  1798. }
  1799. if len(body) == 0 {
  1800. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  1801. }
  1802. return fmt.Errorf("Error: %s", body)
  1803. }
  1804. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  1805. return utils.DisplayJSONMessagesStream(resp.Body, out)
  1806. } else {
  1807. if _, err := io.Copy(out, resp.Body); err != nil {
  1808. return err
  1809. }
  1810. }
  1811. return nil
  1812. }
  1813. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan bool) error {
  1814. // fixme: refactor client to support redirect
  1815. re := regexp.MustCompile("/+")
  1816. path = re.ReplaceAllString(path, "/")
  1817. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  1818. if err != nil {
  1819. return err
  1820. }
  1821. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1822. req.Header.Set("Content-Type", "plain/text")
  1823. req.Host = cli.addr
  1824. dial, err := net.Dial(cli.proto, cli.addr)
  1825. if err != nil {
  1826. if strings.Contains(err.Error(), "connection refused") {
  1827. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  1828. }
  1829. return err
  1830. }
  1831. clientconn := httputil.NewClientConn(dial, nil)
  1832. defer clientconn.Close()
  1833. // Server hijacks the connection, error 'connection closed' expected
  1834. clientconn.Do(req)
  1835. rwc, br := clientconn.Hijack()
  1836. defer rwc.Close()
  1837. if started != nil {
  1838. started <- true
  1839. }
  1840. var receiveStdout chan error
  1841. if stdout != nil {
  1842. receiveStdout = utils.Go(func() (err error) {
  1843. // When TTY is ON, use regular copy
  1844. if setRawTerminal {
  1845. _, err = io.Copy(stdout, br)
  1846. } else {
  1847. _, err = utils.StdCopy(stdout, stderr, br)
  1848. }
  1849. utils.Debugf("[hijack] End of stdout")
  1850. return err
  1851. })
  1852. }
  1853. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  1854. oldState, err := term.SetRawTerminal(cli.terminalFd)
  1855. if err != nil {
  1856. return err
  1857. }
  1858. defer term.RestoreTerminal(cli.terminalFd, oldState)
  1859. }
  1860. sendStdin := utils.Go(func() error {
  1861. if in != nil {
  1862. io.Copy(rwc, in)
  1863. utils.Debugf("[hijack] End of stdin")
  1864. }
  1865. if tcpc, ok := rwc.(*net.TCPConn); ok {
  1866. if err := tcpc.CloseWrite(); err != nil {
  1867. utils.Errorf("Couldn't send EOF: %s\n", err)
  1868. }
  1869. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  1870. if err := unixc.CloseWrite(); err != nil {
  1871. utils.Errorf("Couldn't send EOF: %s\n", err)
  1872. }
  1873. }
  1874. // Discard errors due to pipe interruption
  1875. return nil
  1876. })
  1877. if stdout != nil {
  1878. if err := <-receiveStdout; err != nil {
  1879. utils.Errorf("Error receiveStdout: %s", err)
  1880. return err
  1881. }
  1882. }
  1883. if !cli.isTerminal {
  1884. if err := <-sendStdin; err != nil {
  1885. utils.Errorf("Error sendStdin: %s", err)
  1886. return err
  1887. }
  1888. }
  1889. return nil
  1890. }
  1891. func (cli *DockerCli) getTtySize() (int, int) {
  1892. if !cli.isTerminal {
  1893. return 0, 0
  1894. }
  1895. ws, err := term.GetWinsize(cli.terminalFd)
  1896. if err != nil {
  1897. utils.Errorf("Error getting size: %s", err)
  1898. if ws == nil {
  1899. return 0, 0
  1900. }
  1901. }
  1902. return int(ws.Height), int(ws.Width)
  1903. }
  1904. func (cli *DockerCli) resizeTty(id string) {
  1905. height, width := cli.getTtySize()
  1906. if height == 0 && width == 0 {
  1907. return
  1908. }
  1909. v := url.Values{}
  1910. v.Set("h", strconv.Itoa(height))
  1911. v.Set("w", strconv.Itoa(width))
  1912. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  1913. utils.Errorf("Error resize: %s", err)
  1914. }
  1915. }
  1916. func (cli *DockerCli) monitorTtySize(id string) error {
  1917. cli.resizeTty(id)
  1918. sigchan := make(chan os.Signal, 1)
  1919. signal.Notify(sigchan, syscall.SIGWINCH)
  1920. go func() {
  1921. for _ = range sigchan {
  1922. cli.resizeTty(id)
  1923. }
  1924. }()
  1925. return nil
  1926. }
  1927. func Subcmd(name, signature, description string) *flag.FlagSet {
  1928. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  1929. flags.Usage = func() {
  1930. // FIXME: use custom stdout or return error
  1931. fmt.Fprintf(os.Stdout, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  1932. flags.PrintDefaults()
  1933. }
  1934. return flags
  1935. }
  1936. func (cli *DockerCli) LoadConfigFile() (err error) {
  1937. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  1938. if err != nil {
  1939. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  1940. }
  1941. return err
  1942. }
  1943. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  1944. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  1945. if err != nil {
  1946. // If we can't connect, then the daemon probably died.
  1947. if err != ErrConnectionRefused {
  1948. return -1, err
  1949. }
  1950. return -1, nil
  1951. }
  1952. var out APIWait
  1953. if err := json.Unmarshal(body, &out); err != nil {
  1954. return -1, err
  1955. }
  1956. return out.StatusCode, nil
  1957. }
  1958. // getExitCode perform an inspect on the container. It returns
  1959. // the running state and the exit code.
  1960. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  1961. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  1962. if err != nil {
  1963. // If we can't connect, then the daemon probably died.
  1964. if err != ErrConnectionRefused {
  1965. return false, -1, err
  1966. }
  1967. return false, -1, nil
  1968. }
  1969. c := &Container{}
  1970. if err := json.Unmarshal(body, c); err != nil {
  1971. return false, -1, err
  1972. }
  1973. return c.State.Running, c.State.ExitCode, nil
  1974. }
  1975. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  1976. var (
  1977. isTerminal = false
  1978. terminalFd uintptr
  1979. )
  1980. if in != nil {
  1981. if file, ok := in.(*os.File); ok {
  1982. terminalFd = file.Fd()
  1983. isTerminal = term.IsTerminal(terminalFd)
  1984. }
  1985. }
  1986. if err == nil {
  1987. err = out
  1988. }
  1989. return &DockerCli{
  1990. proto: proto,
  1991. addr: addr,
  1992. in: in,
  1993. out: out,
  1994. err: err,
  1995. isTerminal: isTerminal,
  1996. terminalFd: terminalFd,
  1997. }
  1998. }
  1999. type DockerCli struct {
  2000. proto string
  2001. addr string
  2002. configFile *auth.ConfigFile
  2003. in io.ReadCloser
  2004. out io.Writer
  2005. err io.Writer
  2006. isTerminal bool
  2007. terminalFd uintptr
  2008. }