commands.go 73 KB

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