commands.go 62 KB

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