commands.go 66 KB

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