commands.go 67 KB

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