github.com/chenchun/docker@v1.3.2-0.20150629222414-20467faf132b/api/client/utils.go (about)

     1  package client
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"encoding/json"
     7  	"errors"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"net/http"
    12  	"net/url"
    13  	"os"
    14  	gosignal "os/signal"
    15  	"runtime"
    16  	"strconv"
    17  	"strings"
    18  	"time"
    19  
    20  	"github.com/Sirupsen/logrus"
    21  	"github.com/docker/docker/api"
    22  	"github.com/docker/docker/api/types"
    23  	"github.com/docker/docker/autogen/dockerversion"
    24  	"github.com/docker/docker/cliconfig"
    25  	"github.com/docker/docker/pkg/jsonmessage"
    26  	"github.com/docker/docker/pkg/signal"
    27  	"github.com/docker/docker/pkg/stdcopy"
    28  	"github.com/docker/docker/pkg/term"
    29  	"github.com/docker/docker/registry"
    30  )
    31  
    32  var (
    33  	errConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
    34  )
    35  
    36  type serverResponse struct {
    37  	body       io.ReadCloser
    38  	header     http.Header
    39  	statusCode int
    40  }
    41  
    42  // HTTPClient creates a new HTTP client with the cli's client transport instance.
    43  func (cli *DockerCli) HTTPClient() *http.Client {
    44  	return &http.Client{Transport: cli.transport}
    45  }
    46  
    47  func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) {
    48  	params := bytes.NewBuffer(nil)
    49  	if data != nil {
    50  		if err := json.NewEncoder(params).Encode(data); err != nil {
    51  			return nil, err
    52  		}
    53  	}
    54  	return params, nil
    55  }
    56  
    57  func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (*serverResponse, error) {
    58  
    59  	serverResp := &serverResponse{
    60  		body:       nil,
    61  		statusCode: -1,
    62  	}
    63  
    64  	expectedPayload := (method == "POST" || method == "PUT")
    65  	if expectedPayload && in == nil {
    66  		in = bytes.NewReader([]byte{})
    67  	}
    68  	req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.Version, path), in)
    69  	if err != nil {
    70  		return serverResp, err
    71  	}
    72  
    73  	// Add CLI Config's HTTP Headers BEFORE we set the Docker headers
    74  	// then the user can't change OUR headers
    75  	for k, v := range cli.configFile.HttpHeaders {
    76  		req.Header.Set(k, v)
    77  	}
    78  
    79  	req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
    80  	req.URL.Host = cli.addr
    81  	req.URL.Scheme = cli.scheme
    82  
    83  	if headers != nil {
    84  		for k, v := range headers {
    85  			req.Header[k] = v
    86  		}
    87  	}
    88  
    89  	if expectedPayload && req.Header.Get("Content-Type") == "" {
    90  		req.Header.Set("Content-Type", "text/plain")
    91  	}
    92  
    93  	resp, err := cli.HTTPClient().Do(req)
    94  	if resp != nil {
    95  		serverResp.statusCode = resp.StatusCode
    96  	}
    97  	if err != nil {
    98  		if strings.Contains(err.Error(), "connection refused") {
    99  			return serverResp, errConnectionRefused
   100  		}
   101  
   102  		if cli.tlsConfig == nil {
   103  			return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?\n* Is your docker daemon up and running?", err)
   104  		}
   105  		if cli.tlsConfig != nil && strings.Contains(err.Error(), "remote error: bad certificate") {
   106  			return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err)
   107  		}
   108  
   109  		return serverResp, fmt.Errorf("An error occurred trying to connect: %v", err)
   110  	}
   111  
   112  	if serverResp.statusCode < 200 || serverResp.statusCode >= 400 {
   113  		body, err := ioutil.ReadAll(resp.Body)
   114  		if err != nil {
   115  			return serverResp, err
   116  		}
   117  		if len(body) == 0 {
   118  			return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL)
   119  		}
   120  		return serverResp, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body))
   121  	}
   122  
   123  	serverResp.body = resp.Body
   124  	serverResp.header = resp.Header
   125  	return serverResp, nil
   126  }
   127  
   128  func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) {
   129  	cmdAttempt := func(authConfig cliconfig.AuthConfig) (io.ReadCloser, int, error) {
   130  		buf, err := json.Marshal(authConfig)
   131  		if err != nil {
   132  			return nil, -1, err
   133  		}
   134  		registryAuthHeader := []string{
   135  			base64.URLEncoding.EncodeToString(buf),
   136  		}
   137  
   138  		// begin the request
   139  		serverResp, err := cli.clientRequest(method, path, in, map[string][]string{
   140  			"X-Registry-Auth": registryAuthHeader,
   141  		})
   142  		if err == nil && out != nil {
   143  			// If we are streaming output, complete the stream since
   144  			// errors may not appear until later.
   145  			err = cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), true, out, nil)
   146  		}
   147  		if err != nil {
   148  			// Since errors in a stream appear after status 200 has been written,
   149  			// we may need to change the status code.
   150  			if strings.Contains(err.Error(), "Authentication is required") ||
   151  				strings.Contains(err.Error(), "Status 401") ||
   152  				strings.Contains(err.Error(), "status code 401") {
   153  				serverResp.statusCode = http.StatusUnauthorized
   154  			}
   155  		}
   156  		return serverResp.body, serverResp.statusCode, err
   157  	}
   158  
   159  	// Resolve the Auth config relevant for this server
   160  	authConfig := registry.ResolveAuthConfig(cli.configFile, index)
   161  	body, statusCode, err := cmdAttempt(authConfig)
   162  	if statusCode == http.StatusUnauthorized {
   163  		fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName)
   164  		if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil {
   165  			return nil, -1, err
   166  		}
   167  		authConfig = registry.ResolveAuthConfig(cli.configFile, index)
   168  		return cmdAttempt(authConfig)
   169  	}
   170  	return body, statusCode, err
   171  }
   172  
   173  func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) {
   174  	params, err := cli.encodeData(data)
   175  	if err != nil {
   176  		return nil, nil, -1, err
   177  	}
   178  
   179  	if data != nil {
   180  		if headers == nil {
   181  			headers = make(map[string][]string)
   182  		}
   183  		headers["Content-Type"] = []string{"application/json"}
   184  	}
   185  
   186  	serverResp, err := cli.clientRequest(method, path, params, headers)
   187  	return serverResp.body, serverResp.header, serverResp.statusCode, err
   188  }
   189  
   190  type streamOpts struct {
   191  	rawTerminal bool
   192  	in          io.Reader
   193  	out         io.Writer
   194  	err         io.Writer
   195  	headers     map[string][]string
   196  }
   197  
   198  func (cli *DockerCli) stream(method, path string, opts *streamOpts) (*serverResponse, error) {
   199  	serverResp, err := cli.clientRequest(method, path, opts.in, opts.headers)
   200  	if err != nil {
   201  		return serverResp, err
   202  	}
   203  	return serverResp, cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), opts.rawTerminal, opts.out, opts.err)
   204  }
   205  
   206  func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, rawTerminal bool, stdout, stderr io.Writer) error {
   207  	defer body.Close()
   208  
   209  	if api.MatchesContentType(contentType, "application/json") {
   210  		return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut)
   211  	}
   212  	if stdout != nil || stderr != nil {
   213  		// When TTY is ON, use regular copy
   214  		var err error
   215  		if rawTerminal {
   216  			_, err = io.Copy(stdout, body)
   217  		} else {
   218  			_, err = stdcopy.StdCopy(stdout, stderr, body)
   219  		}
   220  		logrus.Debugf("[stream] End of stdout")
   221  		return err
   222  	}
   223  	return nil
   224  }
   225  
   226  func (cli *DockerCli) resizeTty(id string, isExec bool) {
   227  	height, width := cli.getTtySize()
   228  	if height == 0 && width == 0 {
   229  		return
   230  	}
   231  	v := url.Values{}
   232  	v.Set("h", strconv.Itoa(height))
   233  	v.Set("w", strconv.Itoa(width))
   234  
   235  	path := ""
   236  	if !isExec {
   237  		path = "/containers/" + id + "/resize?"
   238  	} else {
   239  		path = "/exec/" + id + "/resize?"
   240  	}
   241  
   242  	if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil {
   243  		logrus.Debugf("Error resize: %s", err)
   244  	}
   245  }
   246  
   247  func waitForExit(cli *DockerCli, containerID string) (int, error) {
   248  	stream, _, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
   249  	if err != nil {
   250  		return -1, err
   251  	}
   252  
   253  	var res types.ContainerWaitResponse
   254  	if err := json.NewDecoder(stream).Decode(&res); err != nil {
   255  		return -1, err
   256  	}
   257  
   258  	return res.StatusCode, nil
   259  }
   260  
   261  // getExitCode perform an inspect on the container. It returns
   262  // the running state and the exit code.
   263  func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
   264  	stream, _, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil)
   265  	if err != nil {
   266  		// If we can't connect, then the daemon probably died.
   267  		if err != errConnectionRefused {
   268  			return false, -1, err
   269  		}
   270  		return false, -1, nil
   271  	}
   272  
   273  	var c types.ContainerJSON
   274  	if err := json.NewDecoder(stream).Decode(&c); err != nil {
   275  		return false, -1, err
   276  	}
   277  
   278  	return c.State.Running, c.State.ExitCode, nil
   279  }
   280  
   281  // getExecExitCode perform an inspect on the exec command. It returns
   282  // the running state and the exit code.
   283  func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) {
   284  	stream, _, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil)
   285  	if err != nil {
   286  		// If we can't connect, then the daemon probably died.
   287  		if err != errConnectionRefused {
   288  			return false, -1, err
   289  		}
   290  		return false, -1, nil
   291  	}
   292  
   293  	//TODO: Should we reconsider having a type in api/types?
   294  	//this is a response to exex/id/json not container
   295  	var c struct {
   296  		Running  bool
   297  		ExitCode int
   298  	}
   299  
   300  	if err := json.NewDecoder(stream).Decode(&c); err != nil {
   301  		return false, -1, err
   302  	}
   303  
   304  	return c.Running, c.ExitCode, nil
   305  }
   306  
   307  func (cli *DockerCli) monitorTtySize(id string, isExec bool) error {
   308  	cli.resizeTty(id, isExec)
   309  
   310  	if runtime.GOOS == "windows" {
   311  		go func() {
   312  			prevH, prevW := cli.getTtySize()
   313  			for {
   314  				time.Sleep(time.Millisecond * 250)
   315  				h, w := cli.getTtySize()
   316  
   317  				if prevW != w || prevH != h {
   318  					cli.resizeTty(id, isExec)
   319  				}
   320  				prevH = h
   321  				prevW = w
   322  			}
   323  		}()
   324  	} else {
   325  		sigchan := make(chan os.Signal, 1)
   326  		gosignal.Notify(sigchan, signal.SIGWINCH)
   327  		go func() {
   328  			for range sigchan {
   329  				cli.resizeTty(id, isExec)
   330  			}
   331  		}()
   332  	}
   333  	return nil
   334  }
   335  
   336  func (cli *DockerCli) getTtySize() (int, int) {
   337  	if !cli.isTerminalOut {
   338  		return 0, 0
   339  	}
   340  	ws, err := term.GetWinsize(cli.outFd)
   341  	if err != nil {
   342  		logrus.Debugf("Error getting size: %s", err)
   343  		if ws == nil {
   344  			return 0, 0
   345  		}
   346  	}
   347  	return int(ws.Height), int(ws.Width)
   348  }
   349  
   350  func readBody(stream io.ReadCloser, hdr http.Header, statusCode int, err error) ([]byte, int, error) {
   351  	if stream != nil {
   352  		defer stream.Close()
   353  	}
   354  	if err != nil {
   355  		return nil, statusCode, err
   356  	}
   357  	body, err := ioutil.ReadAll(stream)
   358  	if err != nil {
   359  		return nil, -1, err
   360  	}
   361  	return body, statusCode, nil
   362  }