utils.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package client
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. gosignal "os/signal"
  10. "path/filepath"
  11. "runtime"
  12. "time"
  13. "golang.org/x/net/context"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/pkg/signal"
  16. "github.com/docker/docker/pkg/term"
  17. "github.com/docker/docker/registry"
  18. "github.com/docker/engine-api/client"
  19. "github.com/docker/engine-api/types"
  20. registrytypes "github.com/docker/engine-api/types/registry"
  21. )
  22. func (cli *DockerCli) electAuthServer(ctx context.Context) string {
  23. // The daemon `/info` endpoint informs us of the default registry being
  24. // used. This is essential in cross-platforms environment, where for
  25. // example a Linux client might be interacting with a Windows daemon, hence
  26. // the default registry URL might be Windows specific.
  27. serverAddress := registry.IndexServer
  28. if info, err := cli.client.Info(ctx); err != nil {
  29. fmt.Fprintf(cli.out, "Warning: failed to get default registry endpoint from daemon (%v). Using system default: %s\n", err, serverAddress)
  30. } else {
  31. serverAddress = info.IndexServerAddress
  32. }
  33. return serverAddress
  34. }
  35. // EncodeAuthToBase64 serializes the auth configuration as JSON base64 payload
  36. func EncodeAuthToBase64(authConfig types.AuthConfig) (string, error) {
  37. buf, err := json.Marshal(authConfig)
  38. if err != nil {
  39. return "", err
  40. }
  41. return base64.URLEncoding.EncodeToString(buf), nil
  42. }
  43. // RegistryAuthenticationPrivilegedFunc return a RequestPrivilegeFunc from the specified registry index info
  44. // for the given command.
  45. func (cli *DockerCli) RegistryAuthenticationPrivilegedFunc(index *registrytypes.IndexInfo, cmdName string) types.RequestPrivilegeFunc {
  46. return func() (string, error) {
  47. fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
  48. indexServer := registry.GetAuthConfigKey(index)
  49. authConfig, err := cli.configureAuth("", "", indexServer, false)
  50. if err != nil {
  51. return "", err
  52. }
  53. return EncodeAuthToBase64(authConfig)
  54. }
  55. }
  56. func (cli *DockerCli) resizeTty(ctx context.Context, id string, isExec bool) {
  57. height, width := cli.GetTtySize()
  58. cli.resizeTtyTo(ctx, id, height, width, isExec)
  59. }
  60. func (cli *DockerCli) resizeTtyTo(ctx context.Context, id string, height, width int, isExec bool) {
  61. if height == 0 && width == 0 {
  62. return
  63. }
  64. options := types.ResizeOptions{
  65. Height: height,
  66. Width: width,
  67. }
  68. var err error
  69. if isExec {
  70. err = cli.client.ContainerExecResize(ctx, id, options)
  71. } else {
  72. err = cli.client.ContainerResize(ctx, id, options)
  73. }
  74. if err != nil {
  75. logrus.Debugf("Error resize: %s", err)
  76. }
  77. }
  78. // GetExitCode perform an inspect on the container. It returns
  79. // the running state and the exit code.
  80. func (cli *DockerCli) GetExitCode(ctx context.Context, containerID string) (bool, int, error) {
  81. c, err := cli.client.ContainerInspect(ctx, containerID)
  82. if err != nil {
  83. // If we can't connect, then the daemon probably died.
  84. if err != client.ErrConnectionFailed {
  85. return false, -1, err
  86. }
  87. return false, -1, nil
  88. }
  89. return c.State.Running, c.State.ExitCode, nil
  90. }
  91. // getExecExitCode perform an inspect on the exec command. It returns
  92. // the running state and the exit code.
  93. func (cli *DockerCli) getExecExitCode(ctx context.Context, execID string) (bool, int, error) {
  94. resp, err := cli.client.ContainerExecInspect(ctx, execID)
  95. if err != nil {
  96. // If we can't connect, then the daemon probably died.
  97. if err != client.ErrConnectionFailed {
  98. return false, -1, err
  99. }
  100. return false, -1, nil
  101. }
  102. return resp.Running, resp.ExitCode, nil
  103. }
  104. // MonitorTtySize updates the container tty size when the terminal tty changes size
  105. func (cli *DockerCli) MonitorTtySize(ctx context.Context, id string, isExec bool) error {
  106. cli.resizeTty(ctx, id, isExec)
  107. if runtime.GOOS == "windows" {
  108. go func() {
  109. prevH, prevW := cli.GetTtySize()
  110. for {
  111. time.Sleep(time.Millisecond * 250)
  112. h, w := cli.GetTtySize()
  113. if prevW != w || prevH != h {
  114. cli.resizeTty(ctx, id, isExec)
  115. }
  116. prevH = h
  117. prevW = w
  118. }
  119. }()
  120. } else {
  121. sigchan := make(chan os.Signal, 1)
  122. gosignal.Notify(sigchan, signal.SIGWINCH)
  123. go func() {
  124. for range sigchan {
  125. cli.resizeTty(ctx, id, isExec)
  126. }
  127. }()
  128. }
  129. return nil
  130. }
  131. // GetTtySize returns the height and width in characters of the tty
  132. func (cli *DockerCli) GetTtySize() (int, int) {
  133. if !cli.isTerminalOut {
  134. return 0, 0
  135. }
  136. ws, err := term.GetWinsize(cli.outFd)
  137. if err != nil {
  138. logrus.Debugf("Error getting size: %s", err)
  139. if ws == nil {
  140. return 0, 0
  141. }
  142. }
  143. return int(ws.Height), int(ws.Width)
  144. }
  145. // CopyToFile writes the content of the reader to the specifed file
  146. func CopyToFile(outfile string, r io.Reader) error {
  147. tmpFile, err := ioutil.TempFile(filepath.Dir(outfile), ".docker_temp_")
  148. if err != nil {
  149. return err
  150. }
  151. tmpPath := tmpFile.Name()
  152. _, err = io.Copy(tmpFile, r)
  153. tmpFile.Close()
  154. if err != nil {
  155. os.Remove(tmpPath)
  156. return err
  157. }
  158. if err = os.Rename(tmpPath, outfile); err != nil {
  159. os.Remove(tmpPath)
  160. return err
  161. }
  162. return nil
  163. }
  164. // ResolveAuthConfig is like registry.ResolveAuthConfig, but if using the
  165. // default index, it uses the default index name for the daemon's platform,
  166. // not the client's platform.
  167. func (cli *DockerCli) ResolveAuthConfig(ctx context.Context, index *registrytypes.IndexInfo) types.AuthConfig {
  168. configKey := index.Name
  169. if index.Official {
  170. configKey = cli.electAuthServer(ctx)
  171. }
  172. a, _ := getCredentials(cli.configFile, configKey)
  173. return a
  174. }
  175. func (cli *DockerCli) retrieveAuthConfigs() map[string]types.AuthConfig {
  176. acs, _ := getAllCredentials(cli.configFile)
  177. return acs
  178. }
  179. // ForwardAllSignals forwards signals to the contianer
  180. // TODO: this can be unexported again once all container commands are under
  181. // api/client/container
  182. func (cli *DockerCli) ForwardAllSignals(ctx context.Context, cid string) chan os.Signal {
  183. sigc := make(chan os.Signal, 128)
  184. signal.CatchAll(sigc)
  185. go func() {
  186. for s := range sigc {
  187. if s == signal.SIGCHLD || s == signal.SIGPIPE {
  188. continue
  189. }
  190. var sig string
  191. for sigStr, sigN := range signal.SignalMap {
  192. if sigN == s {
  193. sig = sigStr
  194. break
  195. }
  196. }
  197. if sig == "" {
  198. fmt.Fprintf(cli.err, "Unsupported signal: %v. Discarding.\n", s)
  199. continue
  200. }
  201. if err := cli.client.ContainerKill(ctx, cid, sig); err != nil {
  202. logrus.Debugf("Error sending signal: %s", err)
  203. }
  204. }
  205. }()
  206. return sigc
  207. }