commands.go 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515
  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"
  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 := cli.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 := cli.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 := cli.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 := cli.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 := cli.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 := cli.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. fmt.Fprintf(cli.out, "Driver: %s\n", out.Driver)
  427. for _, pair := range out.DriverStatus {
  428. fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1])
  429. }
  430. if out.Debug || os.Getenv("DEBUG") != "" {
  431. fmt.Fprintf(cli.out, "Debug mode (server): %v\n", out.Debug)
  432. fmt.Fprintf(cli.out, "Debug mode (client): %v\n", os.Getenv("DEBUG") != "")
  433. fmt.Fprintf(cli.out, "Fds: %d\n", out.NFd)
  434. fmt.Fprintf(cli.out, "Goroutines: %d\n", out.NGoroutines)
  435. fmt.Fprintf(cli.out, "LXC Version: %s\n", out.LXCVersion)
  436. fmt.Fprintf(cli.out, "EventsListeners: %d\n", out.NEventsListener)
  437. fmt.Fprintf(cli.out, "Kernel Version: %s\n", out.KernelVersion)
  438. }
  439. if len(out.IndexServerAddress) != 0 {
  440. cli.LoadConfigFile()
  441. u := cli.configFile.Configs[out.IndexServerAddress].Username
  442. if len(u) > 0 {
  443. fmt.Fprintf(cli.out, "Username: %v\n", u)
  444. fmt.Fprintf(cli.out, "Registry: %v\n", out.IndexServerAddress)
  445. }
  446. }
  447. if !out.MemoryLimit {
  448. fmt.Fprintf(cli.err, "WARNING: No memory limit support\n")
  449. }
  450. if !out.SwapLimit {
  451. fmt.Fprintf(cli.err, "WARNING: No swap limit support\n")
  452. }
  453. if !out.IPv4Forwarding {
  454. fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n")
  455. }
  456. return nil
  457. }
  458. func (cli *DockerCli) CmdStop(args ...string) error {
  459. cmd := cli.Subcmd("stop", "[OPTIONS] CONTAINER [CONTAINER...]", "Stop a running container (Send SIGTERM, and then SIGKILL after grace period)")
  460. nSeconds := cmd.Int("t", 10, "Number of seconds to wait for the container to stop before killing it.")
  461. if err := cmd.Parse(args); err != nil {
  462. return nil
  463. }
  464. if cmd.NArg() < 1 {
  465. cmd.Usage()
  466. return nil
  467. }
  468. v := url.Values{}
  469. v.Set("t", strconv.Itoa(*nSeconds))
  470. var encounteredError error
  471. for _, name := range cmd.Args() {
  472. _, _, err := cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil)
  473. if err != nil {
  474. fmt.Fprintf(cli.err, "%s\n", err)
  475. encounteredError = fmt.Errorf("Error: failed to stop one or more containers")
  476. } else {
  477. fmt.Fprintf(cli.out, "%s\n", name)
  478. }
  479. }
  480. return encounteredError
  481. }
  482. func (cli *DockerCli) CmdRestart(args ...string) error {
  483. cmd := cli.Subcmd("restart", "[OPTIONS] CONTAINER [CONTAINER...]", "Restart a running container")
  484. 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")
  485. if err := cmd.Parse(args); err != nil {
  486. return nil
  487. }
  488. if cmd.NArg() < 1 {
  489. cmd.Usage()
  490. return nil
  491. }
  492. v := url.Values{}
  493. v.Set("t", strconv.Itoa(*nSeconds))
  494. var encounteredError error
  495. for _, name := range cmd.Args() {
  496. _, _, err := cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil)
  497. if err != nil {
  498. fmt.Fprintf(cli.err, "%s\n", err)
  499. encounteredError = fmt.Errorf("Error: failed to restart one or more containers")
  500. } else {
  501. fmt.Fprintf(cli.out, "%s\n", name)
  502. }
  503. }
  504. return encounteredError
  505. }
  506. func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal {
  507. sigc := make(chan os.Signal, 1)
  508. utils.CatchAll(sigc)
  509. go func() {
  510. for s := range sigc {
  511. if s == syscall.SIGCHLD {
  512. continue
  513. }
  514. if _, _, err := cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%d", cid, s), nil); err != nil {
  515. utils.Debugf("Error sending signal: %s", err)
  516. }
  517. }
  518. }()
  519. return sigc
  520. }
  521. func (cli *DockerCli) CmdStart(args ...string) error {
  522. cmd := cli.Subcmd("start", "CONTAINER [CONTAINER...]", "Restart a stopped container")
  523. attach := cmd.Bool("a", false, "Attach container's stdout/stderr and forward all signals to the process")
  524. openStdin := cmd.Bool("i", false, "Attach container's stdin")
  525. if err := cmd.Parse(args); err != nil {
  526. return nil
  527. }
  528. if cmd.NArg() < 1 {
  529. cmd.Usage()
  530. return nil
  531. }
  532. var cErr chan error
  533. var tty bool
  534. if *attach || *openStdin {
  535. if cmd.NArg() > 1 {
  536. return fmt.Errorf("Impossible to start and attach multiple containers at once.")
  537. }
  538. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  539. if err != nil {
  540. return err
  541. }
  542. container := &Container{}
  543. err = json.Unmarshal(body, container)
  544. if err != nil {
  545. return err
  546. }
  547. tty = container.Config.Tty
  548. if !container.Config.Tty {
  549. sigc := cli.forwardAllSignals(cmd.Arg(0))
  550. defer utils.StopCatch(sigc)
  551. }
  552. var in io.ReadCloser
  553. v := url.Values{}
  554. v.Set("stream", "1")
  555. if *openStdin && container.Config.OpenStdin {
  556. v.Set("stdin", "1")
  557. in = cli.in
  558. }
  559. v.Set("stdout", "1")
  560. v.Set("stderr", "1")
  561. cErr = utils.Go(func() error {
  562. return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil)
  563. })
  564. }
  565. var encounteredError error
  566. for _, name := range cmd.Args() {
  567. _, _, err := cli.call("POST", "/containers/"+name+"/start", nil)
  568. if err != nil {
  569. if !*attach || !*openStdin {
  570. fmt.Fprintf(cli.err, "%s\n", err)
  571. encounteredError = fmt.Errorf("Error: failed to start one or more containers")
  572. }
  573. } else {
  574. if !*attach || !*openStdin {
  575. fmt.Fprintf(cli.out, "%s\n", name)
  576. }
  577. }
  578. }
  579. if encounteredError != nil {
  580. if *openStdin || *attach {
  581. cli.in.Close()
  582. <-cErr
  583. }
  584. return encounteredError
  585. }
  586. if *openStdin || *attach {
  587. if tty && cli.isTerminal {
  588. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  589. utils.Errorf("Error monitoring TTY size: %s\n", err)
  590. }
  591. }
  592. return <-cErr
  593. }
  594. return nil
  595. }
  596. func (cli *DockerCli) CmdInspect(args ...string) error {
  597. cmd := cli.Subcmd("inspect", "CONTAINER|IMAGE [CONTAINER|IMAGE...]", "Return low-level information on a container/image")
  598. if err := cmd.Parse(args); err != nil {
  599. return nil
  600. }
  601. if cmd.NArg() < 1 {
  602. cmd.Usage()
  603. return nil
  604. }
  605. indented := new(bytes.Buffer)
  606. status := 0
  607. for _, name := range args {
  608. obj, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  609. if err != nil {
  610. obj, _, err = cli.call("GET", "/images/"+name+"/json", nil)
  611. if err != nil {
  612. if strings.Contains(err.Error(), "No such") {
  613. fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name)
  614. } else {
  615. fmt.Fprintf(cli.err, "%s", err)
  616. }
  617. status = 1
  618. continue
  619. }
  620. }
  621. if err = json.Indent(indented, obj, "", " "); err != nil {
  622. fmt.Fprintf(cli.err, "%s\n", err)
  623. status = 1
  624. continue
  625. }
  626. indented.WriteString(",")
  627. }
  628. if indented.Len() > 0 {
  629. // Remove trailing ','
  630. indented.Truncate(indented.Len() - 1)
  631. }
  632. fmt.Fprintf(cli.out, "[")
  633. if _, err := io.Copy(cli.out, indented); err != nil {
  634. return err
  635. }
  636. fmt.Fprintf(cli.out, "]")
  637. if status != 0 {
  638. return &utils.StatusError{Status: status}
  639. }
  640. return nil
  641. }
  642. func (cli *DockerCli) CmdTop(args ...string) error {
  643. cmd := cli.Subcmd("top", "CONTAINER [ps OPTIONS]", "Lookup the running processes of a container")
  644. if err := cmd.Parse(args); err != nil {
  645. return nil
  646. }
  647. if cmd.NArg() == 0 {
  648. cmd.Usage()
  649. return nil
  650. }
  651. val := url.Values{}
  652. if cmd.NArg() > 1 {
  653. val.Set("ps_args", strings.Join(cmd.Args()[1:], " "))
  654. }
  655. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil)
  656. if err != nil {
  657. return err
  658. }
  659. procs := APITop{}
  660. err = json.Unmarshal(body, &procs)
  661. if err != nil {
  662. return err
  663. }
  664. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  665. fmt.Fprintln(w, strings.Join(procs.Titles, "\t"))
  666. for _, proc := range procs.Processes {
  667. fmt.Fprintln(w, strings.Join(proc, "\t"))
  668. }
  669. w.Flush()
  670. return nil
  671. }
  672. func (cli *DockerCli) CmdPort(args ...string) error {
  673. cmd := cli.Subcmd("port", "CONTAINER PRIVATE_PORT", "Lookup the public-facing port which is NAT-ed to PRIVATE_PORT")
  674. if err := cmd.Parse(args); err != nil {
  675. return nil
  676. }
  677. if cmd.NArg() != 2 {
  678. cmd.Usage()
  679. return nil
  680. }
  681. port := cmd.Arg(1)
  682. proto := "tcp"
  683. parts := strings.SplitN(port, "/", 2)
  684. if len(parts) == 2 && len(parts[1]) != 0 {
  685. port = parts[0]
  686. proto = parts[1]
  687. }
  688. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil)
  689. if err != nil {
  690. return err
  691. }
  692. var out Container
  693. err = json.Unmarshal(body, &out)
  694. if err != nil {
  695. return err
  696. }
  697. if frontends, exists := out.NetworkSettings.Ports[Port(port+"/"+proto)]; exists {
  698. if frontends == nil {
  699. fmt.Fprintf(cli.out, "%s\n", port)
  700. } else {
  701. for _, frontend := range frontends {
  702. fmt.Fprintf(cli.out, "%s:%s\n", frontend.HostIp, frontend.HostPort)
  703. }
  704. }
  705. } else {
  706. return fmt.Errorf("Error: No private port '%s' allocated on %s", cmd.Arg(1), cmd.Arg(0))
  707. }
  708. return nil
  709. }
  710. // 'docker rmi IMAGE' removes all images with the name IMAGE
  711. func (cli *DockerCli) CmdRmi(args ...string) error {
  712. cmd := cli.Subcmd("rmi", "IMAGE [IMAGE...]", "Remove one or more images")
  713. if err := cmd.Parse(args); err != nil {
  714. return nil
  715. }
  716. if cmd.NArg() < 1 {
  717. cmd.Usage()
  718. return nil
  719. }
  720. var encounteredError error
  721. for _, name := range cmd.Args() {
  722. body, _, err := cli.call("DELETE", "/images/"+name, nil)
  723. if err != nil {
  724. fmt.Fprintf(cli.err, "%s\n", err)
  725. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  726. } else {
  727. var outs []APIRmi
  728. err = json.Unmarshal(body, &outs)
  729. if err != nil {
  730. fmt.Fprintf(cli.err, "%s\n", err)
  731. encounteredError = fmt.Errorf("Error: failed to remove one or more images")
  732. continue
  733. }
  734. for _, out := range outs {
  735. if out.Deleted != "" {
  736. fmt.Fprintf(cli.out, "Deleted: %s\n", out.Deleted)
  737. } else {
  738. fmt.Fprintf(cli.out, "Untagged: %s\n", out.Untagged)
  739. }
  740. }
  741. }
  742. }
  743. return encounteredError
  744. }
  745. func (cli *DockerCli) CmdHistory(args ...string) error {
  746. cmd := cli.Subcmd("history", "[OPTIONS] IMAGE", "Show the history of an image")
  747. quiet := cmd.Bool("q", false, "only show numeric IDs")
  748. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  749. if err := cmd.Parse(args); err != nil {
  750. return nil
  751. }
  752. if cmd.NArg() != 1 {
  753. cmd.Usage()
  754. return nil
  755. }
  756. body, _, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil)
  757. if err != nil {
  758. return err
  759. }
  760. var outs []APIHistory
  761. err = json.Unmarshal(body, &outs)
  762. if err != nil {
  763. return err
  764. }
  765. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  766. if !*quiet {
  767. fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE")
  768. }
  769. for _, out := range outs {
  770. if !*quiet {
  771. if *noTrunc {
  772. fmt.Fprintf(w, "%s\t", out.ID)
  773. } else {
  774. fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
  775. }
  776. fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.Created, 0))))
  777. if *noTrunc {
  778. fmt.Fprintf(w, "%s\t", out.CreatedBy)
  779. } else {
  780. fmt.Fprintf(w, "%s\t", utils.Trunc(out.CreatedBy, 45))
  781. }
  782. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  783. } else {
  784. if *noTrunc {
  785. fmt.Fprintln(w, out.ID)
  786. } else {
  787. fmt.Fprintln(w, utils.TruncateID(out.ID))
  788. }
  789. }
  790. }
  791. w.Flush()
  792. return nil
  793. }
  794. func (cli *DockerCli) CmdRm(args ...string) error {
  795. cmd := cli.Subcmd("rm", "[OPTIONS] CONTAINER [CONTAINER...]", "Remove one or more containers")
  796. v := cmd.Bool("v", false, "Remove the volumes associated to the container")
  797. link := cmd.Bool("link", false, "Remove the specified link and not the underlying container")
  798. if err := cmd.Parse(args); err != nil {
  799. return nil
  800. }
  801. if cmd.NArg() < 1 {
  802. cmd.Usage()
  803. return nil
  804. }
  805. val := url.Values{}
  806. if *v {
  807. val.Set("v", "1")
  808. }
  809. if *link {
  810. val.Set("link", "1")
  811. }
  812. var encounteredError error
  813. for _, name := range cmd.Args() {
  814. _, _, err := cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil)
  815. if err != nil {
  816. fmt.Fprintf(cli.err, "%s\n", err)
  817. encounteredError = fmt.Errorf("Error: failed to remove one or more containers")
  818. } else {
  819. fmt.Fprintf(cli.out, "%s\n", name)
  820. }
  821. }
  822. return encounteredError
  823. }
  824. // 'docker kill NAME' kills a running container
  825. func (cli *DockerCli) CmdKill(args ...string) error {
  826. cmd := cli.Subcmd("kill", "CONTAINER [CONTAINER...]", "Kill a running container (send SIGKILL)")
  827. if err := cmd.Parse(args); err != nil {
  828. return nil
  829. }
  830. if cmd.NArg() < 1 {
  831. cmd.Usage()
  832. return nil
  833. }
  834. var encounteredError error
  835. for _, name := range args {
  836. if _, _, err := cli.call("POST", "/containers/"+name+"/kill", nil); err != nil {
  837. fmt.Fprintf(cli.err, "%s\n", err)
  838. encounteredError = fmt.Errorf("Error: failed to kill one or more containers")
  839. } else {
  840. fmt.Fprintf(cli.out, "%s\n", name)
  841. }
  842. }
  843. return encounteredError
  844. }
  845. func (cli *DockerCli) CmdImport(args ...string) error {
  846. cmd := cli.Subcmd("import", "URL|- [REPOSITORY[:TAG]]", "Create a new filesystem image from the contents of a tarball(.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz).")
  847. if err := cmd.Parse(args); err != nil {
  848. return nil
  849. }
  850. if cmd.NArg() < 1 {
  851. cmd.Usage()
  852. return nil
  853. }
  854. var src, repository, tag string
  855. if cmd.NArg() == 3 {
  856. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'URL|- [REPOSITORY [TAG]]' as been deprecated. Please use URL|- [REPOSITORY[:TAG]]\n")
  857. src, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  858. } else {
  859. src = cmd.Arg(0)
  860. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  861. }
  862. v := url.Values{}
  863. v.Set("repo", repository)
  864. v.Set("tag", tag)
  865. v.Set("fromSrc", src)
  866. var in io.Reader
  867. if src == "-" {
  868. in = cli.in
  869. }
  870. return cli.stream("POST", "/images/create?"+v.Encode(), in, cli.out, nil)
  871. }
  872. func (cli *DockerCli) CmdPush(args ...string) error {
  873. cmd := cli.Subcmd("push", "NAME", "Push an image or a repository to the registry")
  874. if err := cmd.Parse(args); err != nil {
  875. return nil
  876. }
  877. name := cmd.Arg(0)
  878. if name == "" {
  879. cmd.Usage()
  880. return nil
  881. }
  882. cli.LoadConfigFile()
  883. // Resolve the Repository name from fqn to endpoint + name
  884. endpoint, _, err := registry.ResolveRepositoryName(name)
  885. if err != nil {
  886. return err
  887. }
  888. // Resolve the Auth config relevant for this server
  889. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  890. // If we're not using a custom registry, we know the restrictions
  891. // applied to repository names and can warn the user in advance.
  892. // Custom repositories can have different rules, and we must also
  893. // allow pushing by image ID.
  894. if len(strings.SplitN(name, "/", 2)) == 1 {
  895. username := cli.configFile.Configs[auth.IndexServerAddress()].Username
  896. if username == "" {
  897. username = "<user>"
  898. }
  899. return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
  900. }
  901. v := url.Values{}
  902. push := func(authConfig auth.AuthConfig) error {
  903. buf, err := json.Marshal(authConfig)
  904. if err != nil {
  905. return err
  906. }
  907. registryAuthHeader := []string{
  908. base64.URLEncoding.EncodeToString(buf),
  909. }
  910. return cli.stream("POST", "/images/"+name+"/push?"+v.Encode(), nil, cli.out, map[string][]string{
  911. "X-Registry-Auth": registryAuthHeader,
  912. })
  913. }
  914. if err := push(authConfig); err != nil {
  915. if err.Error() == registry.ErrLoginRequired.Error() {
  916. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  917. if err := cli.CmdLogin(endpoint); err != nil {
  918. return err
  919. }
  920. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  921. return push(authConfig)
  922. }
  923. return err
  924. }
  925. return nil
  926. }
  927. func (cli *DockerCli) CmdPull(args ...string) error {
  928. cmd := cli.Subcmd("pull", "NAME", "Pull an image or a repository from the registry")
  929. tag := cmd.String("t", "", "Download tagged image in repository")
  930. if err := cmd.Parse(args); err != nil {
  931. return nil
  932. }
  933. if cmd.NArg() != 1 {
  934. cmd.Usage()
  935. return nil
  936. }
  937. remote, parsedTag := utils.ParseRepositoryTag(cmd.Arg(0))
  938. if *tag == "" {
  939. *tag = parsedTag
  940. }
  941. // Resolve the Repository name from fqn to endpoint + name
  942. endpoint, _, err := registry.ResolveRepositoryName(remote)
  943. if err != nil {
  944. return err
  945. }
  946. cli.LoadConfigFile()
  947. // Resolve the Auth config relevant for this server
  948. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  949. v := url.Values{}
  950. v.Set("fromImage", remote)
  951. v.Set("tag", *tag)
  952. pull := func(authConfig auth.AuthConfig) error {
  953. buf, err := json.Marshal(authConfig)
  954. if err != nil {
  955. return err
  956. }
  957. registryAuthHeader := []string{
  958. base64.URLEncoding.EncodeToString(buf),
  959. }
  960. return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{
  961. "X-Registry-Auth": registryAuthHeader,
  962. })
  963. }
  964. if err := pull(authConfig); err != nil {
  965. if err.Error() == registry.ErrLoginRequired.Error() {
  966. fmt.Fprintln(cli.out, "\nPlease login prior to push:")
  967. if err := cli.CmdLogin(endpoint); err != nil {
  968. return err
  969. }
  970. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  971. return pull(authConfig)
  972. }
  973. return err
  974. }
  975. return nil
  976. }
  977. func (cli *DockerCli) CmdImages(args ...string) error {
  978. cmd := cli.Subcmd("images", "[OPTIONS] [NAME]", "List images")
  979. quiet := cmd.Bool("q", false, "only show numeric IDs")
  980. all := cmd.Bool("a", false, "show all images (by default filter out the intermediate images used to build)")
  981. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  982. flViz := cmd.Bool("viz", false, "output graph in graphviz format")
  983. flTree := cmd.Bool("tree", false, "output graph in tree format")
  984. if err := cmd.Parse(args); err != nil {
  985. return nil
  986. }
  987. if cmd.NArg() > 1 {
  988. cmd.Usage()
  989. return nil
  990. }
  991. if *flViz {
  992. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  993. if err != nil {
  994. return err
  995. }
  996. var outs []APIImages
  997. err = json.Unmarshal(body, &outs)
  998. if err != nil {
  999. return err
  1000. }
  1001. fmt.Fprintf(cli.out, "digraph docker {\n")
  1002. for _, image := range outs {
  1003. if image.ParentId == "" {
  1004. fmt.Fprintf(cli.out, " base -> \"%s\" [style=invis]\n", utils.TruncateID(image.ID))
  1005. } else {
  1006. fmt.Fprintf(cli.out, " \"%s\" -> \"%s\"\n", utils.TruncateID(image.ParentId), utils.TruncateID(image.ID))
  1007. }
  1008. if image.RepoTags[0] != "<none>:<none>" {
  1009. 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"))
  1010. }
  1011. }
  1012. fmt.Fprintf(cli.out, " base [style=invisible]\n}\n")
  1013. } else if *flTree {
  1014. body, _, err := cli.call("GET", "/images/json?all=1", nil)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. var outs []APIImages
  1019. if err := json.Unmarshal(body, &outs); err != nil {
  1020. return err
  1021. }
  1022. var (
  1023. startImageArg = cmd.Arg(0)
  1024. startImage APIImages
  1025. roots []APIImages
  1026. byParent = make(map[string][]APIImages)
  1027. )
  1028. for _, image := range outs {
  1029. if image.ParentId == "" {
  1030. roots = append(roots, image)
  1031. } else {
  1032. if children, exists := byParent[image.ParentId]; exists {
  1033. byParent[image.ParentId] = append(children, image)
  1034. } else {
  1035. byParent[image.ParentId] = []APIImages{image}
  1036. }
  1037. }
  1038. if startImageArg != "" {
  1039. if startImageArg == image.ID || startImageArg == utils.TruncateID(image.ID) {
  1040. startImage = image
  1041. }
  1042. for _, repotag := range image.RepoTags {
  1043. if repotag == startImageArg {
  1044. startImage = image
  1045. }
  1046. }
  1047. }
  1048. }
  1049. if startImageArg != "" {
  1050. WalkTree(cli, noTrunc, []APIImages{startImage}, byParent, "")
  1051. } else {
  1052. WalkTree(cli, noTrunc, roots, byParent, "")
  1053. }
  1054. } else {
  1055. v := url.Values{}
  1056. if cmd.NArg() == 1 {
  1057. v.Set("filter", cmd.Arg(0))
  1058. }
  1059. if *all {
  1060. v.Set("all", "1")
  1061. }
  1062. body, _, err := cli.call("GET", "/images/json?"+v.Encode(), nil)
  1063. if err != nil {
  1064. return err
  1065. }
  1066. var outs []APIImages
  1067. err = json.Unmarshal(body, &outs)
  1068. if err != nil {
  1069. return err
  1070. }
  1071. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1072. if !*quiet {
  1073. fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tSIZE")
  1074. }
  1075. for _, out := range outs {
  1076. for _, repotag := range out.RepoTags {
  1077. repo, tag := utils.ParseRepositoryTag(repotag)
  1078. if !*noTrunc {
  1079. out.ID = utils.TruncateID(out.ID)
  1080. }
  1081. if !*quiet {
  1082. fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t", repo, tag, out.ID, utils.HumanDuration(time.Now().UTC().Sub(time.Unix(out.Created, 0))))
  1083. if out.VirtualSize > 0 {
  1084. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
  1085. } else {
  1086. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
  1087. }
  1088. } else {
  1089. fmt.Fprintln(w, out.ID)
  1090. }
  1091. }
  1092. }
  1093. if !*quiet {
  1094. w.Flush()
  1095. }
  1096. }
  1097. return nil
  1098. }
  1099. func WalkTree(cli *DockerCli, noTrunc *bool, images []APIImages, byParent map[string][]APIImages, prefix string) {
  1100. if len(images) > 1 {
  1101. length := len(images)
  1102. for index, image := range images {
  1103. if index+1 == length {
  1104. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1105. if subimages, exists := byParent[image.ID]; exists {
  1106. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1107. }
  1108. } else {
  1109. PrintTreeNode(cli, noTrunc, image, prefix+"|─")
  1110. if subimages, exists := byParent[image.ID]; exists {
  1111. WalkTree(cli, noTrunc, subimages, byParent, prefix+"| ")
  1112. }
  1113. }
  1114. }
  1115. } else {
  1116. for _, image := range images {
  1117. PrintTreeNode(cli, noTrunc, image, prefix+"└─")
  1118. if subimages, exists := byParent[image.ID]; exists {
  1119. WalkTree(cli, noTrunc, subimages, byParent, prefix+" ")
  1120. }
  1121. }
  1122. }
  1123. }
  1124. func PrintTreeNode(cli *DockerCli, noTrunc *bool, image APIImages, prefix string) {
  1125. var imageID string
  1126. if *noTrunc {
  1127. imageID = image.ID
  1128. } else {
  1129. imageID = utils.TruncateID(image.ID)
  1130. }
  1131. fmt.Fprintf(cli.out, "%s%s Size: %s (virtual %s)", prefix, imageID, utils.HumanSize(image.Size), utils.HumanSize(image.VirtualSize))
  1132. if image.RepoTags[0] != "<none>:<none>" {
  1133. fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.RepoTags, ", "))
  1134. } else {
  1135. fmt.Fprint(cli.out, "\n")
  1136. }
  1137. }
  1138. func displayablePorts(ports []APIPort) string {
  1139. result := []string{}
  1140. for _, port := range ports {
  1141. if port.IP == "" {
  1142. result = append(result, fmt.Sprintf("%d/%s", port.PublicPort, port.Type))
  1143. } else {
  1144. result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type))
  1145. }
  1146. }
  1147. sort.Strings(result)
  1148. return strings.Join(result, ", ")
  1149. }
  1150. func (cli *DockerCli) CmdPs(args ...string) error {
  1151. cmd := cli.Subcmd("ps", "[OPTIONS]", "List containers")
  1152. quiet := cmd.Bool("q", false, "Only display numeric IDs")
  1153. size := cmd.Bool("s", false, "Display sizes")
  1154. all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.")
  1155. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1156. nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.")
  1157. since := cmd.String("sinceId", "", "Show only containers created since Id, include non-running ones.")
  1158. before := cmd.String("beforeId", "", "Show only container created before Id, include non-running ones.")
  1159. last := cmd.Int("n", -1, "Show n last created containers, include non-running ones.")
  1160. if err := cmd.Parse(args); err != nil {
  1161. return nil
  1162. }
  1163. v := url.Values{}
  1164. if *last == -1 && *nLatest {
  1165. *last = 1
  1166. }
  1167. if *all {
  1168. v.Set("all", "1")
  1169. }
  1170. if *last != -1 {
  1171. v.Set("limit", strconv.Itoa(*last))
  1172. }
  1173. if *since != "" {
  1174. v.Set("since", *since)
  1175. }
  1176. if *before != "" {
  1177. v.Set("before", *before)
  1178. }
  1179. if *size {
  1180. v.Set("size", "1")
  1181. }
  1182. body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. var outs []APIContainers
  1187. err = json.Unmarshal(body, &outs)
  1188. if err != nil {
  1189. return err
  1190. }
  1191. w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0)
  1192. if !*quiet {
  1193. fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES")
  1194. if *size {
  1195. fmt.Fprintln(w, "\tSIZE")
  1196. } else {
  1197. fmt.Fprint(w, "\n")
  1198. }
  1199. }
  1200. for _, out := range outs {
  1201. if !*noTrunc {
  1202. out.ID = utils.TruncateID(out.ID)
  1203. }
  1204. // Remove the leading / from the names
  1205. for i := 0; i < len(out.Names); i++ {
  1206. out.Names[i] = out.Names[i][1:]
  1207. }
  1208. if !*quiet {
  1209. if !*noTrunc {
  1210. out.Command = utils.Trunc(out.Command, 20)
  1211. }
  1212. 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().UTC().Sub(time.Unix(out.Created, 0))), out.Status, displayablePorts(out.Ports), strings.Join(out.Names, ","))
  1213. if *size {
  1214. if out.SizeRootFs > 0 {
  1215. fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs))
  1216. } else {
  1217. fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw))
  1218. }
  1219. } else {
  1220. fmt.Fprint(w, "\n")
  1221. }
  1222. } else {
  1223. fmt.Fprintln(w, out.ID)
  1224. }
  1225. }
  1226. if !*quiet {
  1227. w.Flush()
  1228. }
  1229. return nil
  1230. }
  1231. func (cli *DockerCli) CmdCommit(args ...string) error {
  1232. cmd := cli.Subcmd("commit", "[OPTIONS] CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes")
  1233. flComment := cmd.String("m", "", "Commit message")
  1234. flAuthor := cmd.String("author", "", "Author (eg. \"John Hannibal Smith <hannibal@a-team.com>\"")
  1235. flConfig := cmd.String("run", "", "Config automatically applied when the image is run. "+`(ex: -run='{"Cmd": ["cat", "/world"], "PortSpecs": ["22"]}')`)
  1236. if err := cmd.Parse(args); err != nil {
  1237. return nil
  1238. }
  1239. var name, repository, tag string
  1240. if cmd.NArg() == 3 {
  1241. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'CONTAINER [REPOSITORY [TAG]]' as been deprecated. Please use CONTAINER [REPOSITORY[:TAG]]\n")
  1242. name, repository, tag = cmd.Arg(0), cmd.Arg(1), cmd.Arg(2)
  1243. } else {
  1244. name = cmd.Arg(0)
  1245. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1246. }
  1247. if name == "" {
  1248. cmd.Usage()
  1249. return nil
  1250. }
  1251. v := url.Values{}
  1252. v.Set("container", name)
  1253. v.Set("repo", repository)
  1254. v.Set("tag", tag)
  1255. v.Set("comment", *flComment)
  1256. v.Set("author", *flAuthor)
  1257. var config *Config
  1258. if *flConfig != "" {
  1259. config = &Config{}
  1260. if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
  1261. return err
  1262. }
  1263. }
  1264. body, _, err := cli.call("POST", "/commit?"+v.Encode(), config)
  1265. if err != nil {
  1266. return err
  1267. }
  1268. apiID := &APIID{}
  1269. err = json.Unmarshal(body, apiID)
  1270. if err != nil {
  1271. return err
  1272. }
  1273. fmt.Fprintf(cli.out, "%s\n", apiID.ID)
  1274. return nil
  1275. }
  1276. func (cli *DockerCli) CmdEvents(args ...string) error {
  1277. cmd := cli.Subcmd("events", "[OPTIONS]", "Get real time events from the server")
  1278. since := cmd.String("since", "", "Show previously created events and then stream.")
  1279. if err := cmd.Parse(args); err != nil {
  1280. return nil
  1281. }
  1282. if cmd.NArg() != 0 {
  1283. cmd.Usage()
  1284. return nil
  1285. }
  1286. v := url.Values{}
  1287. if *since != "" {
  1288. loc := time.FixedZone(time.Now().Zone())
  1289. format := "2006-01-02 15:04:05 -0700 MST"
  1290. if len(*since) < len(format) {
  1291. format = format[:len(*since)]
  1292. }
  1293. if t, err := time.ParseInLocation(format, *since, loc); err == nil {
  1294. v.Set("since", strconv.FormatInt(t.Unix(), 10))
  1295. } else {
  1296. v.Set("since", *since)
  1297. }
  1298. }
  1299. if err := cli.stream("GET", "/events?"+v.Encode(), nil, cli.out, nil); err != nil {
  1300. return err
  1301. }
  1302. return nil
  1303. }
  1304. func (cli *DockerCli) CmdExport(args ...string) error {
  1305. cmd := cli.Subcmd("export", "CONTAINER", "Export the contents of a filesystem as a tar archive to STDOUT")
  1306. if err := cmd.Parse(args); err != nil {
  1307. return nil
  1308. }
  1309. if cmd.NArg() != 1 {
  1310. cmd.Usage()
  1311. return nil
  1312. }
  1313. if err := cli.stream("GET", "/containers/"+cmd.Arg(0)+"/export", nil, cli.out, nil); err != nil {
  1314. return err
  1315. }
  1316. return nil
  1317. }
  1318. func (cli *DockerCli) CmdDiff(args ...string) error {
  1319. cmd := cli.Subcmd("diff", "CONTAINER", "Inspect changes on a container's filesystem")
  1320. if err := cmd.Parse(args); err != nil {
  1321. return nil
  1322. }
  1323. if cmd.NArg() != 1 {
  1324. cmd.Usage()
  1325. return nil
  1326. }
  1327. body, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil)
  1328. if err != nil {
  1329. return err
  1330. }
  1331. changes := []Change{}
  1332. err = json.Unmarshal(body, &changes)
  1333. if err != nil {
  1334. return err
  1335. }
  1336. for _, change := range changes {
  1337. fmt.Fprintf(cli.out, "%s\n", change.String())
  1338. }
  1339. return nil
  1340. }
  1341. func (cli *DockerCli) CmdLogs(args ...string) error {
  1342. cmd := cli.Subcmd("logs", "CONTAINER", "Fetch the logs of a container")
  1343. if err := cmd.Parse(args); err != nil {
  1344. return nil
  1345. }
  1346. if cmd.NArg() != 1 {
  1347. cmd.Usage()
  1348. return nil
  1349. }
  1350. name := cmd.Arg(0)
  1351. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1352. if err != nil {
  1353. return err
  1354. }
  1355. container := &Container{}
  1356. err = json.Unmarshal(body, container)
  1357. if err != nil {
  1358. return err
  1359. }
  1360. 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 {
  1361. return err
  1362. }
  1363. return nil
  1364. }
  1365. func (cli *DockerCli) CmdAttach(args ...string) error {
  1366. cmd := cli.Subcmd("attach", "[OPTIONS] CONTAINER", "Attach to a running container")
  1367. noStdin := cmd.Bool("nostdin", false, "Do not attach stdin")
  1368. proxy := cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1369. if err := cmd.Parse(args); err != nil {
  1370. return nil
  1371. }
  1372. if cmd.NArg() != 1 {
  1373. cmd.Usage()
  1374. return nil
  1375. }
  1376. name := cmd.Arg(0)
  1377. body, _, err := cli.call("GET", "/containers/"+name+"/json", nil)
  1378. if err != nil {
  1379. return err
  1380. }
  1381. container := &Container{}
  1382. err = json.Unmarshal(body, container)
  1383. if err != nil {
  1384. return err
  1385. }
  1386. if !container.State.IsRunning() {
  1387. return fmt.Errorf("Impossible to attach to a stopped container, start it first")
  1388. }
  1389. if container.Config.Tty && cli.isTerminal {
  1390. if err := cli.monitorTtySize(cmd.Arg(0)); err != nil {
  1391. utils.Debugf("Error monitoring TTY size: %s", err)
  1392. }
  1393. }
  1394. var in io.ReadCloser
  1395. v := url.Values{}
  1396. v.Set("stream", "1")
  1397. if !*noStdin && container.Config.OpenStdin {
  1398. v.Set("stdin", "1")
  1399. in = cli.in
  1400. }
  1401. v.Set("stdout", "1")
  1402. v.Set("stderr", "1")
  1403. if *proxy && !container.Config.Tty {
  1404. sigc := cli.forwardAllSignals(cmd.Arg(0))
  1405. defer utils.StopCatch(sigc)
  1406. }
  1407. if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), container.Config.Tty, in, cli.out, cli.err, nil); err != nil {
  1408. return err
  1409. }
  1410. return nil
  1411. }
  1412. func (cli *DockerCli) CmdSearch(args ...string) error {
  1413. cmd := cli.Subcmd("search", "TERM", "Search the docker index for images")
  1414. noTrunc := cmd.Bool("notrunc", false, "Don't truncate output")
  1415. trusted := cmd.Bool("trusted", false, "Only show trusted builds")
  1416. stars := cmd.Int("stars", 0, "Only displays with at least xxx stars")
  1417. if err := cmd.Parse(args); err != nil {
  1418. return nil
  1419. }
  1420. if cmd.NArg() != 1 {
  1421. cmd.Usage()
  1422. return nil
  1423. }
  1424. v := url.Values{}
  1425. v.Set("term", cmd.Arg(0))
  1426. body, _, err := cli.call("GET", "/images/search?"+v.Encode(), nil)
  1427. if err != nil {
  1428. return err
  1429. }
  1430. outs := []registry.SearchResult{}
  1431. err = json.Unmarshal(body, &outs)
  1432. if err != nil {
  1433. return err
  1434. }
  1435. w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0)
  1436. fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tTRUSTED\n")
  1437. for _, out := range outs {
  1438. if (*trusted && !out.IsTrusted) || (*stars > out.StarCount) {
  1439. continue
  1440. }
  1441. desc := strings.Replace(out.Description, "\n", " ", -1)
  1442. desc = strings.Replace(desc, "\r", " ", -1)
  1443. if !*noTrunc && len(desc) > 45 {
  1444. desc = utils.Trunc(desc, 42) + "..."
  1445. }
  1446. fmt.Fprintf(w, "%s\t%s\t%d\t", out.Name, desc, out.StarCount)
  1447. if out.IsOfficial {
  1448. fmt.Fprint(w, "[OK]")
  1449. }
  1450. fmt.Fprint(w, "\t")
  1451. if out.IsTrusted {
  1452. fmt.Fprint(w, "[OK]")
  1453. }
  1454. fmt.Fprint(w, "\n")
  1455. }
  1456. w.Flush()
  1457. return nil
  1458. }
  1459. // Ports type - Used to parse multiple -p flags
  1460. type ports []int
  1461. func (cli *DockerCli) CmdTag(args ...string) error {
  1462. cmd := cli.Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY[:TAG]", "Tag an image into a repository")
  1463. force := cmd.Bool("f", false, "Force")
  1464. if err := cmd.Parse(args); err != nil {
  1465. return nil
  1466. }
  1467. if cmd.NArg() != 2 && cmd.NArg() != 3 {
  1468. cmd.Usage()
  1469. return nil
  1470. }
  1471. var repository, tag string
  1472. if cmd.NArg() == 3 {
  1473. fmt.Fprintf(cli.err, "[DEPRECATED] The format 'IMAGE [REPOSITORY [TAG]]' as been deprecated. Please use IMAGE [REPOSITORY[:TAG]]\n")
  1474. repository, tag = cmd.Arg(1), cmd.Arg(2)
  1475. } else {
  1476. repository, tag = utils.ParseRepositoryTag(cmd.Arg(1))
  1477. }
  1478. v := url.Values{}
  1479. v.Set("repo", repository)
  1480. v.Set("tag", tag)
  1481. if *force {
  1482. v.Set("force", "1")
  1483. }
  1484. if _, _, err := cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil); err != nil {
  1485. return err
  1486. }
  1487. return nil
  1488. }
  1489. //FIXME Only used in tests
  1490. func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1491. cmd := flag.NewFlagSet("run", flag.ContinueOnError)
  1492. cmd.SetOutput(ioutil.Discard)
  1493. cmd.Usage = nil
  1494. return parseRun(cmd, args, capabilities)
  1495. }
  1496. func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
  1497. var (
  1498. // FIXME: use utils.ListOpts for attach and volumes?
  1499. flAttach = NewListOpts(ValidateAttach)
  1500. flVolumes = NewListOpts(ValidatePath)
  1501. flLinks = NewListOpts(ValidateLink)
  1502. flEnv = NewListOpts(ValidateEnv)
  1503. flPublish ListOpts
  1504. flExpose ListOpts
  1505. flDns ListOpts
  1506. flVolumesFrom ListOpts
  1507. flLxcOpts ListOpts
  1508. flAutoRemove = cmd.Bool("rm", false, "Automatically remove the container when it exits (incompatible with -d)")
  1509. flDetach = cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id")
  1510. flNetwork = cmd.Bool("n", true, "Enable networking for this container")
  1511. flPrivileged = cmd.Bool("privileged", false, "Give extended privileges to this container")
  1512. flPublishAll = cmd.Bool("P", false, "Publish all exposed ports to the host interfaces")
  1513. flStdin = cmd.Bool("i", false, "Keep stdin open even if not attached")
  1514. flTty = cmd.Bool("t", false, "Allocate a pseudo-tty")
  1515. flContainerIDFile = cmd.String("cidfile", "", "Write the container ID to the file")
  1516. flEntrypoint = cmd.String("entrypoint", "", "Overwrite the default entrypoint of the image")
  1517. flHostname = cmd.String("h", "", "Container host name")
  1518. flMemoryString = cmd.String("m", "", "Memory limit (format: <number><optional unit>, where unit = b, k, m or g)")
  1519. flUser = cmd.String("u", "", "Username or UID")
  1520. flWorkingDir = cmd.String("w", "", "Working directory inside the container")
  1521. flCpuShares = cmd.Int64("c", 0, "CPU shares (relative weight)")
  1522. // For documentation purpose
  1523. _ = cmd.Bool("sig-proxy", true, "Proxify all received signal to the process (even in non-tty mode)")
  1524. _ = cmd.String("name", "", "Assign a name to the container")
  1525. )
  1526. cmd.Var(&flAttach, "a", "Attach to stdin, stdout or stderr.")
  1527. cmd.Var(&flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
  1528. cmd.Var(&flLinks, "link", "Add link to another container (name:alias)")
  1529. cmd.Var(&flEnv, "e", "Set environment variables")
  1530. cmd.Var(&flPublish, "p", fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", PortSpecTemplateFormat))
  1531. cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host")
  1532. cmd.Var(&flDns, "dns", "Set custom dns servers")
  1533. cmd.Var(&flVolumesFrom, "volumes-from", "Mount volumes from the specified container(s)")
  1534. cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
  1535. if err := cmd.Parse(args); err != nil {
  1536. return nil, nil, cmd, err
  1537. }
  1538. // Check if the kernel supports memory limit cgroup.
  1539. if capabilities != nil && *flMemoryString != "" && !capabilities.MemoryLimit {
  1540. *flMemoryString = ""
  1541. }
  1542. // Validate input params
  1543. if *flDetach && flAttach.Len() > 0 {
  1544. return nil, nil, cmd, ErrConflictAttachDetach
  1545. }
  1546. if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
  1547. return nil, nil, cmd, ErrInvalidWorikingDirectory
  1548. }
  1549. if *flDetach && *flAutoRemove {
  1550. return nil, nil, cmd, ErrConflictDetachAutoRemove
  1551. }
  1552. // If neither -d or -a are set, attach to everything by default
  1553. if flAttach.Len() == 0 && !*flDetach {
  1554. if !*flDetach {
  1555. flAttach.Set("stdout")
  1556. flAttach.Set("stderr")
  1557. if *flStdin {
  1558. flAttach.Set("stdin")
  1559. }
  1560. }
  1561. }
  1562. var flMemory int64
  1563. if *flMemoryString != "" {
  1564. parsedMemory, err := utils.RAMInBytes(*flMemoryString)
  1565. if err != nil {
  1566. return nil, nil, cmd, err
  1567. }
  1568. flMemory = parsedMemory
  1569. }
  1570. var binds []string
  1571. // add any bind targets to the list of container volumes
  1572. for bind := range flVolumes.GetMap() {
  1573. if arr := strings.Split(bind, ":"); len(arr) > 1 {
  1574. if arr[0] == "/" {
  1575. return nil, nil, cmd, fmt.Errorf("Invalid bind mount: source can't be '/'")
  1576. }
  1577. dstDir := arr[1]
  1578. flVolumes.Set(dstDir)
  1579. binds = append(binds, bind)
  1580. flVolumes.Delete(bind)
  1581. }
  1582. }
  1583. var (
  1584. parsedArgs = cmd.Args()
  1585. runCmd []string
  1586. entrypoint []string
  1587. image string
  1588. )
  1589. if len(parsedArgs) >= 1 {
  1590. image = cmd.Arg(0)
  1591. }
  1592. if len(parsedArgs) > 1 {
  1593. runCmd = parsedArgs[1:]
  1594. }
  1595. if *flEntrypoint != "" {
  1596. entrypoint = []string{*flEntrypoint}
  1597. }
  1598. lxcConf, err := parseLxcConfOpts(flLxcOpts)
  1599. if err != nil {
  1600. return nil, nil, cmd, err
  1601. }
  1602. var (
  1603. domainname string
  1604. hostname = *flHostname
  1605. parts = strings.SplitN(hostname, ".", 2)
  1606. )
  1607. if len(parts) > 1 {
  1608. hostname = parts[0]
  1609. domainname = parts[1]
  1610. }
  1611. ports, portBindings, err := parsePortSpecs(flPublish.GetAll())
  1612. if err != nil {
  1613. return nil, nil, cmd, err
  1614. }
  1615. // Merge in exposed ports to the map of published ports
  1616. for _, e := range flExpose.GetAll() {
  1617. if strings.Contains(e, ":") {
  1618. return nil, nil, cmd, fmt.Errorf("Invalid port format for -expose: %s", e)
  1619. }
  1620. p := NewPort(splitProtoPort(e))
  1621. if _, exists := ports[p]; !exists {
  1622. ports[p] = struct{}{}
  1623. }
  1624. }
  1625. config := &Config{
  1626. Hostname: hostname,
  1627. Domainname: domainname,
  1628. PortSpecs: nil, // Deprecated
  1629. ExposedPorts: ports,
  1630. User: *flUser,
  1631. Tty: *flTty,
  1632. NetworkDisabled: !*flNetwork,
  1633. OpenStdin: *flStdin,
  1634. Memory: flMemory,
  1635. CpuShares: *flCpuShares,
  1636. AttachStdin: flAttach.Get("stdin"),
  1637. AttachStdout: flAttach.Get("stdout"),
  1638. AttachStderr: flAttach.Get("stderr"),
  1639. Env: flEnv.GetAll(),
  1640. Cmd: runCmd,
  1641. Dns: flDns.GetAll(),
  1642. Image: image,
  1643. Volumes: flVolumes.GetMap(),
  1644. VolumesFrom: strings.Join(flVolumesFrom.GetAll(), ","),
  1645. Entrypoint: entrypoint,
  1646. WorkingDir: *flWorkingDir,
  1647. }
  1648. hostConfig := &HostConfig{
  1649. Binds: binds,
  1650. ContainerIDFile: *flContainerIDFile,
  1651. LxcConf: lxcConf,
  1652. Privileged: *flPrivileged,
  1653. PortBindings: portBindings,
  1654. Links: flLinks.GetAll(),
  1655. PublishAllPorts: *flPublishAll,
  1656. }
  1657. if capabilities != nil && flMemory > 0 && !capabilities.SwapLimit {
  1658. //fmt.Fprintf(stdout, "WARNING: Your kernel does not support swap limit capabilities. Limitation discarded.\n")
  1659. config.MemorySwap = -1
  1660. }
  1661. // When allocating stdin in attached mode, close stdin at client disconnect
  1662. if config.OpenStdin && config.AttachStdin {
  1663. config.StdinOnce = true
  1664. }
  1665. return config, hostConfig, cmd, nil
  1666. }
  1667. func (cli *DockerCli) CmdRun(args ...string) error {
  1668. config, hostConfig, cmd, err := parseRun(cli.Subcmd("run", "[OPTIONS] IMAGE [COMMAND] [ARG...]", "Run a command in a new container"), args, nil)
  1669. if err != nil {
  1670. return err
  1671. }
  1672. if config.Image == "" {
  1673. cmd.Usage()
  1674. return nil
  1675. }
  1676. // Retrieve relevant client-side config
  1677. var (
  1678. flName = cmd.Lookup("name")
  1679. flRm = cmd.Lookup("rm")
  1680. flSigProxy = cmd.Lookup("sig-proxy")
  1681. autoRemove, _ = strconv.ParseBool(flRm.Value.String())
  1682. sigProxy, _ = strconv.ParseBool(flSigProxy.Value.String())
  1683. )
  1684. // Disable sigProxy in case on TTY
  1685. if config.Tty {
  1686. sigProxy = false
  1687. }
  1688. var containerIDFile io.WriteCloser
  1689. if len(hostConfig.ContainerIDFile) > 0 {
  1690. if _, err := os.Stat(hostConfig.ContainerIDFile); err == nil {
  1691. return fmt.Errorf("cid file found, make sure the other container isn't running or delete %s", hostConfig.ContainerIDFile)
  1692. }
  1693. if containerIDFile, err = os.Create(hostConfig.ContainerIDFile); err != nil {
  1694. return fmt.Errorf("failed to create the container ID file: %s", err)
  1695. }
  1696. defer containerIDFile.Close()
  1697. }
  1698. containerValues := url.Values{}
  1699. if name := flName.Value.String(); name != "" {
  1700. containerValues.Set("name", name)
  1701. }
  1702. //create the container
  1703. body, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), config)
  1704. //if image not found try to pull it
  1705. if statusCode == 404 {
  1706. _, tag := utils.ParseRepositoryTag(config.Image)
  1707. if tag == "" {
  1708. tag = DEFAULTTAG
  1709. }
  1710. fmt.Fprintf(cli.err, "Unable to find image '%s' (tag: %s) locally\n", config.Image, tag)
  1711. v := url.Values{}
  1712. repos, tag := utils.ParseRepositoryTag(config.Image)
  1713. v.Set("fromImage", repos)
  1714. v.Set("tag", tag)
  1715. // Resolve the Repository name from fqn to endpoint + name
  1716. endpoint, _, err := registry.ResolveRepositoryName(repos)
  1717. if err != nil {
  1718. return err
  1719. }
  1720. // Load the auth config file, to be able to pull the image
  1721. cli.LoadConfigFile()
  1722. // Resolve the Auth config relevant for this server
  1723. authConfig := cli.configFile.ResolveAuthConfig(endpoint)
  1724. buf, err := json.Marshal(authConfig)
  1725. if err != nil {
  1726. return err
  1727. }
  1728. registryAuthHeader := []string{
  1729. base64.URLEncoding.EncodeToString(buf),
  1730. }
  1731. if err = cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.err, map[string][]string{"X-Registry-Auth": registryAuthHeader}); err != nil {
  1732. return err
  1733. }
  1734. if body, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), config); err != nil {
  1735. return err
  1736. }
  1737. } else if err != nil {
  1738. return err
  1739. }
  1740. var runResult APIRun
  1741. if err := json.Unmarshal(body, &runResult); err != nil {
  1742. return err
  1743. }
  1744. for _, warning := range runResult.Warnings {
  1745. fmt.Fprintf(cli.err, "WARNING: %s\n", warning)
  1746. }
  1747. if len(hostConfig.ContainerIDFile) > 0 {
  1748. if _, err = containerIDFile.Write([]byte(runResult.ID)); err != nil {
  1749. return fmt.Errorf("failed to write the container ID to the file: %s", err)
  1750. }
  1751. }
  1752. if sigProxy {
  1753. sigc := cli.forwardAllSignals(runResult.ID)
  1754. defer utils.StopCatch(sigc)
  1755. }
  1756. var (
  1757. waitDisplayId chan struct{}
  1758. errCh chan error
  1759. )
  1760. if !config.AttachStdout && !config.AttachStderr {
  1761. // Make this asynchrone in order to let the client write to stdin before having to read the ID
  1762. waitDisplayId = make(chan struct{})
  1763. go func() {
  1764. defer close(waitDisplayId)
  1765. fmt.Fprintf(cli.out, "%s\n", runResult.ID)
  1766. }()
  1767. }
  1768. // We need to instanciate the chan because the select needs it. It can
  1769. // be closed but can't be uninitialized.
  1770. hijacked := make(chan io.Closer)
  1771. // Block the return until the chan gets closed
  1772. defer func() {
  1773. utils.Debugf("End of CmdRun(), Waiting for hijack to finish.")
  1774. if _, ok := <-hijacked; ok {
  1775. utils.Errorf("Hijack did not finish (chan still open)")
  1776. }
  1777. }()
  1778. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  1779. var (
  1780. out, stderr io.Writer
  1781. in io.ReadCloser
  1782. v = url.Values{}
  1783. )
  1784. v.Set("stream", "1")
  1785. if config.AttachStdin {
  1786. v.Set("stdin", "1")
  1787. in = cli.in
  1788. }
  1789. if config.AttachStdout {
  1790. v.Set("stdout", "1")
  1791. out = cli.out
  1792. }
  1793. if config.AttachStderr {
  1794. v.Set("stderr", "1")
  1795. if config.Tty {
  1796. stderr = cli.out
  1797. } else {
  1798. stderr = cli.err
  1799. }
  1800. }
  1801. errCh = utils.Go(func() error {
  1802. return cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked)
  1803. })
  1804. } else {
  1805. close(hijacked)
  1806. }
  1807. // Acknowledge the hijack before starting
  1808. select {
  1809. case closer := <-hijacked:
  1810. // Make sure that hijack gets closed when returning. (result
  1811. // in closing hijack chan and freeing server's goroutines.
  1812. if closer != nil {
  1813. defer closer.Close()
  1814. }
  1815. case err := <-errCh:
  1816. if err != nil {
  1817. utils.Debugf("Error hijack: %s", err)
  1818. return err
  1819. }
  1820. }
  1821. //start the container
  1822. if _, _, err = cli.call("POST", "/containers/"+runResult.ID+"/start", hostConfig); err != nil {
  1823. return err
  1824. }
  1825. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminal {
  1826. if err := cli.monitorTtySize(runResult.ID); err != nil {
  1827. utils.Errorf("Error monitoring TTY size: %s\n", err)
  1828. }
  1829. }
  1830. if errCh != nil {
  1831. if err := <-errCh; err != nil {
  1832. utils.Debugf("Error hijack: %s", err)
  1833. return err
  1834. }
  1835. }
  1836. // Detached mode: wait for the id to be displayed and return.
  1837. if !config.AttachStdout && !config.AttachStderr {
  1838. // Detached mode
  1839. <-waitDisplayId
  1840. return nil
  1841. }
  1842. var status int
  1843. // Attached mode
  1844. if autoRemove {
  1845. // Autoremove: wait for the container to finish, retrieve
  1846. // the exit code and remove the container
  1847. if _, _, err := cli.call("POST", "/containers/"+runResult.ID+"/wait", nil); err != nil {
  1848. return err
  1849. }
  1850. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1851. return err
  1852. }
  1853. if _, _, err := cli.call("DELETE", "/containers/"+runResult.ID, nil); err != nil {
  1854. return err
  1855. }
  1856. } else {
  1857. // No Autoremove: Simply retrieve the exit code
  1858. if _, status, err = getExitCode(cli, runResult.ID); err != nil {
  1859. return err
  1860. }
  1861. }
  1862. if status != 0 {
  1863. return &utils.StatusError{Status: status}
  1864. }
  1865. return nil
  1866. }
  1867. func (cli *DockerCli) CmdCp(args ...string) error {
  1868. cmd := cli.Subcmd("cp", "CONTAINER:PATH HOSTPATH", "Copy files/folders from the PATH to the HOSTPATH")
  1869. if err := cmd.Parse(args); err != nil {
  1870. return nil
  1871. }
  1872. if cmd.NArg() != 2 {
  1873. cmd.Usage()
  1874. return nil
  1875. }
  1876. var copyData APICopy
  1877. info := strings.Split(cmd.Arg(0), ":")
  1878. if len(info) != 2 {
  1879. return fmt.Errorf("Error: Path not specified")
  1880. }
  1881. copyData.Resource = info[1]
  1882. copyData.HostPath = cmd.Arg(1)
  1883. data, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData)
  1884. if err != nil {
  1885. return err
  1886. }
  1887. if statusCode == 200 {
  1888. r := bytes.NewReader(data)
  1889. if err := archive.Untar(r, copyData.HostPath, nil); err != nil {
  1890. return err
  1891. }
  1892. }
  1893. return nil
  1894. }
  1895. func (cli *DockerCli) CmdSave(args ...string) error {
  1896. cmd := cli.Subcmd("save", "IMAGE DESTINATION", "Save an image to a tar archive")
  1897. if err := cmd.Parse(args); err != nil {
  1898. return err
  1899. }
  1900. if cmd.NArg() != 1 {
  1901. cmd.Usage()
  1902. return nil
  1903. }
  1904. image := cmd.Arg(0)
  1905. if err := cli.stream("GET", "/images/"+image+"/get", nil, cli.out, nil); err != nil {
  1906. return err
  1907. }
  1908. return nil
  1909. }
  1910. func (cli *DockerCli) CmdLoad(args ...string) error {
  1911. cmd := cli.Subcmd("load", "SOURCE", "Load an image from a tar archive")
  1912. if err := cmd.Parse(args); err != nil {
  1913. return err
  1914. }
  1915. if cmd.NArg() != 0 {
  1916. cmd.Usage()
  1917. return nil
  1918. }
  1919. if err := cli.stream("POST", "/images/load", cli.in, cli.out, nil); err != nil {
  1920. return err
  1921. }
  1922. return nil
  1923. }
  1924. func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
  1925. var params io.Reader
  1926. if data != nil {
  1927. buf, err := json.Marshal(data)
  1928. if err != nil {
  1929. return nil, -1, err
  1930. }
  1931. params = bytes.NewBuffer(buf)
  1932. }
  1933. // fixme: refactor client to support redirect
  1934. re := regexp.MustCompile("/+")
  1935. path = re.ReplaceAllString(path, "/")
  1936. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), params)
  1937. if err != nil {
  1938. return nil, -1, err
  1939. }
  1940. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1941. req.Host = cli.addr
  1942. if data != nil {
  1943. req.Header.Set("Content-Type", "application/json")
  1944. } else if method == "POST" {
  1945. req.Header.Set("Content-Type", "plain/text")
  1946. }
  1947. dial, err := net.Dial(cli.proto, cli.addr)
  1948. if err != nil {
  1949. if strings.Contains(err.Error(), "connection refused") {
  1950. return nil, -1, ErrConnectionRefused
  1951. }
  1952. return nil, -1, err
  1953. }
  1954. clientconn := httputil.NewClientConn(dial, nil)
  1955. resp, err := clientconn.Do(req)
  1956. defer clientconn.Close()
  1957. if err != nil {
  1958. if strings.Contains(err.Error(), "connection refused") {
  1959. return nil, -1, ErrConnectionRefused
  1960. }
  1961. return nil, -1, err
  1962. }
  1963. defer resp.Body.Close()
  1964. body, err := ioutil.ReadAll(resp.Body)
  1965. if err != nil {
  1966. return nil, -1, err
  1967. }
  1968. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  1969. if len(body) == 0 {
  1970. return nil, resp.StatusCode, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
  1971. }
  1972. return nil, resp.StatusCode, fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  1973. }
  1974. return body, resp.StatusCode, nil
  1975. }
  1976. func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error {
  1977. if (method == "POST" || method == "PUT") && in == nil {
  1978. in = bytes.NewReader([]byte{})
  1979. }
  1980. // fixme: refactor client to support redirect
  1981. re := regexp.MustCompile("/+")
  1982. path = re.ReplaceAllString(path, "/")
  1983. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), in)
  1984. if err != nil {
  1985. return err
  1986. }
  1987. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  1988. req.Host = cli.addr
  1989. if method == "POST" {
  1990. req.Header.Set("Content-Type", "plain/text")
  1991. }
  1992. if headers != nil {
  1993. for k, v := range headers {
  1994. req.Header[k] = v
  1995. }
  1996. }
  1997. dial, err := net.Dial(cli.proto, cli.addr)
  1998. if err != nil {
  1999. if strings.Contains(err.Error(), "connection refused") {
  2000. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2001. }
  2002. return err
  2003. }
  2004. clientconn := httputil.NewClientConn(dial, nil)
  2005. resp, err := clientconn.Do(req)
  2006. defer clientconn.Close()
  2007. if err != nil {
  2008. if strings.Contains(err.Error(), "connection refused") {
  2009. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2010. }
  2011. return err
  2012. }
  2013. defer resp.Body.Close()
  2014. if resp.StatusCode < 200 || resp.StatusCode >= 400 {
  2015. body, err := ioutil.ReadAll(resp.Body)
  2016. if err != nil {
  2017. return err
  2018. }
  2019. if len(body) == 0 {
  2020. return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode))
  2021. }
  2022. return fmt.Errorf("Error: %s", bytes.TrimSpace(body))
  2023. }
  2024. if matchesContentType(resp.Header.Get("Content-Type"), "application/json") {
  2025. return utils.DisplayJSONMessagesStream(resp.Body, out, cli.isTerminal)
  2026. }
  2027. if _, err := io.Copy(out, resp.Body); err != nil {
  2028. return err
  2029. }
  2030. return nil
  2031. }
  2032. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer) error {
  2033. defer func() {
  2034. if started != nil {
  2035. close(started)
  2036. }
  2037. }()
  2038. // fixme: refactor client to support redirect
  2039. re := regexp.MustCompile("/+")
  2040. path = re.ReplaceAllString(path, "/")
  2041. req, err := http.NewRequest(method, fmt.Sprintf("/v%g%s", APIVERSION, path), nil)
  2042. if err != nil {
  2043. return err
  2044. }
  2045. req.Header.Set("User-Agent", "Docker-Client/"+VERSION)
  2046. req.Header.Set("Content-Type", "plain/text")
  2047. req.Host = cli.addr
  2048. dial, err := net.Dial(cli.proto, cli.addr)
  2049. if err != nil {
  2050. if strings.Contains(err.Error(), "connection refused") {
  2051. return fmt.Errorf("Can't connect to docker daemon. Is 'docker -d' running on this host?")
  2052. }
  2053. return err
  2054. }
  2055. clientconn := httputil.NewClientConn(dial, nil)
  2056. defer clientconn.Close()
  2057. // Server hijacks the connection, error 'connection closed' expected
  2058. clientconn.Do(req)
  2059. rwc, br := clientconn.Hijack()
  2060. defer rwc.Close()
  2061. if started != nil {
  2062. started <- rwc
  2063. }
  2064. var receiveStdout chan error
  2065. if stdout != nil {
  2066. receiveStdout = utils.Go(func() (err error) {
  2067. // When TTY is ON, use regular copy
  2068. if setRawTerminal {
  2069. _, err = io.Copy(stdout, br)
  2070. } else {
  2071. _, err = utils.StdCopy(stdout, stderr, br)
  2072. }
  2073. utils.Debugf("[hijack] End of stdout")
  2074. return err
  2075. })
  2076. }
  2077. if in != nil && setRawTerminal && cli.isTerminal && os.Getenv("NORAW") == "" {
  2078. oldState, err := term.SetRawTerminal(cli.terminalFd)
  2079. if err != nil {
  2080. return err
  2081. }
  2082. defer term.RestoreTerminal(cli.terminalFd, oldState)
  2083. }
  2084. sendStdin := utils.Go(func() error {
  2085. if in != nil {
  2086. io.Copy(rwc, in)
  2087. utils.Debugf("[hijack] End of stdin")
  2088. }
  2089. if tcpc, ok := rwc.(*net.TCPConn); ok {
  2090. if err := tcpc.CloseWrite(); err != nil {
  2091. utils.Errorf("Couldn't send EOF: %s\n", err)
  2092. }
  2093. } else if unixc, ok := rwc.(*net.UnixConn); ok {
  2094. if err := unixc.CloseWrite(); err != nil {
  2095. utils.Errorf("Couldn't send EOF: %s\n", err)
  2096. }
  2097. }
  2098. // Discard errors due to pipe interruption
  2099. return nil
  2100. })
  2101. if stdout != nil {
  2102. if err := <-receiveStdout; err != nil {
  2103. utils.Errorf("Error receiveStdout: %s", err)
  2104. return err
  2105. }
  2106. }
  2107. if !cli.isTerminal {
  2108. if err := <-sendStdin; err != nil {
  2109. utils.Errorf("Error sendStdin: %s", err)
  2110. return err
  2111. }
  2112. }
  2113. return nil
  2114. }
  2115. func (cli *DockerCli) getTtySize() (int, int) {
  2116. if !cli.isTerminal {
  2117. return 0, 0
  2118. }
  2119. ws, err := term.GetWinsize(cli.terminalFd)
  2120. if err != nil {
  2121. utils.Errorf("Error getting size: %s", err)
  2122. if ws == nil {
  2123. return 0, 0
  2124. }
  2125. }
  2126. return int(ws.Height), int(ws.Width)
  2127. }
  2128. func (cli *DockerCli) resizeTty(id string) {
  2129. height, width := cli.getTtySize()
  2130. if height == 0 && width == 0 {
  2131. return
  2132. }
  2133. v := url.Values{}
  2134. v.Set("h", strconv.Itoa(height))
  2135. v.Set("w", strconv.Itoa(width))
  2136. if _, _, err := cli.call("POST", "/containers/"+id+"/resize?"+v.Encode(), nil); err != nil {
  2137. utils.Errorf("Error resize: %s", err)
  2138. }
  2139. }
  2140. func (cli *DockerCli) monitorTtySize(id string) error {
  2141. cli.resizeTty(id)
  2142. sigchan := make(chan os.Signal, 1)
  2143. signal.Notify(sigchan, syscall.SIGWINCH)
  2144. go func() {
  2145. for _ = range sigchan {
  2146. cli.resizeTty(id)
  2147. }
  2148. }()
  2149. return nil
  2150. }
  2151. func (cli *DockerCli) Subcmd(name, signature, description string) *flag.FlagSet {
  2152. flags := flag.NewFlagSet(name, flag.ContinueOnError)
  2153. flags.Usage = func() {
  2154. fmt.Fprintf(cli.err, "\nUsage: docker %s %s\n\n%s\n\n", name, signature, description)
  2155. flags.PrintDefaults()
  2156. os.Exit(2)
  2157. }
  2158. return flags
  2159. }
  2160. func (cli *DockerCli) LoadConfigFile() (err error) {
  2161. cli.configFile, err = auth.LoadConfig(os.Getenv("HOME"))
  2162. if err != nil {
  2163. fmt.Fprintf(cli.err, "WARNING: %s\n", err)
  2164. }
  2165. return err
  2166. }
  2167. func waitForExit(cli *DockerCli, containerId string) (int, error) {
  2168. body, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil)
  2169. if err != nil {
  2170. // If we can't connect, then the daemon probably died.
  2171. if err != ErrConnectionRefused {
  2172. return -1, err
  2173. }
  2174. return -1, nil
  2175. }
  2176. var out APIWait
  2177. if err := json.Unmarshal(body, &out); err != nil {
  2178. return -1, err
  2179. }
  2180. return out.StatusCode, nil
  2181. }
  2182. // getExitCode perform an inspect on the container. It returns
  2183. // the running state and the exit code.
  2184. func getExitCode(cli *DockerCli, containerId string) (bool, int, error) {
  2185. body, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil)
  2186. if err != nil {
  2187. // If we can't connect, then the daemon probably died.
  2188. if err != ErrConnectionRefused {
  2189. return false, -1, err
  2190. }
  2191. return false, -1, nil
  2192. }
  2193. c := &Container{}
  2194. if err := json.Unmarshal(body, c); err != nil {
  2195. return false, -1, err
  2196. }
  2197. return c.State.IsRunning(), c.State.GetExitCode(), nil
  2198. }
  2199. func NewDockerCli(in io.ReadCloser, out, err io.Writer, proto, addr string) *DockerCli {
  2200. var (
  2201. isTerminal = false
  2202. terminalFd uintptr
  2203. )
  2204. if in != nil {
  2205. if file, ok := in.(*os.File); ok {
  2206. terminalFd = file.Fd()
  2207. isTerminal = term.IsTerminal(terminalFd)
  2208. }
  2209. }
  2210. if err == nil {
  2211. err = out
  2212. }
  2213. return &DockerCli{
  2214. proto: proto,
  2215. addr: addr,
  2216. in: in,
  2217. out: out,
  2218. err: err,
  2219. isTerminal: isTerminal,
  2220. terminalFd: terminalFd,
  2221. }
  2222. }
  2223. type DockerCli struct {
  2224. proto string
  2225. addr string
  2226. configFile *auth.ConfigFile
  2227. in io.ReadCloser
  2228. out io.Writer
  2229. err io.Writer
  2230. isTerminal bool
  2231. terminalFd uintptr
  2232. }