commands.go 59 KB

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