commands.go 69 KB

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