commands.go 54 KB

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