commands.go 71 KB

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