commands.go 68 KB

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