commands.go 68 KB

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