client.go 6.9 KB
Newer Older
1 2 3
package http

import (
4
	"encoding/json"
5
	"errors"
6
	"fmt"
7
	"io"
8
	"io/ioutil"
9
	"net/http"
10
	"net/url"
11
	"reflect"
12
	"strconv"
13 14
	"strings"

15 16
	cmds "github.com/ipfs/go-ipfs/commands"
	config "github.com/ipfs/go-ipfs/repo/config"
17 18

	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
19 20
)

21
const (
22
	ApiUrlFormat = "http://%s%s/%s?%s"
23 24
	ApiPath      = "/api/v0" // TODO: make configurable
)
25

Jeromy's avatar
Jeromy committed
26 27 28 29
var OptionSkipMap = map[string]bool{
	"api": true,
}

30 31 32 33 34 35 36
// Client is the commands HTTP client interface.
type Client interface {
	Send(req cmds.Request) (cmds.Response, error)
}

type client struct {
	serverAddress string
rht's avatar
rht committed
37
	httpClient    *http.Client
38
}
39

40
func NewClient(address string) Client {
Jeromy's avatar
Jeromy committed
41 42 43
	// We cannot use the default transport because of a bug in go's connection reuse
	// code. It causes random failures in the connection including io.EOF and connection
	// refused on 'client.Do'
44 45
	return &client{
		serverAddress: address,
rht's avatar
rht committed
46
		httpClient: &http.Client{
47 48 49 50 51
			Transport: &http.Transport{
				DisableKeepAlives: true,
			},
		},
	}
52
}
53

54
func (c *client) Send(req cmds.Request) (cmds.Response, error) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
55

56 57
	if req.Context() == nil {
		log.Warningf("no context set in request")
58
		if err := req.SetRootContext(context.TODO()); err != nil {
59 60 61 62
			return nil, err
		}
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
63 64 65 66 67 68 69
	// save user-provided encoding
	previousUserProvidedEncoding, found, err := req.Option(cmds.EncShort).String()
	if err != nil {
		return nil, err
	}

	// override with json to send to server
70
	req.SetOption(cmds.EncShort, cmds.JSON)
71

72 73 74
	// stream channel output
	req.SetOption(cmds.ChanOpt, "true")

75
	query, err := getQuery(req)
76 77 78 79
	if err != nil {
		return nil, err
	}

80
	var fileReader *MultiFileReader
81 82
	var reader io.Reader

83
	if req.Files() != nil {
84
		fileReader = NewMultiFileReader(req.Files(), true)
85
		reader = fileReader
86 87
	}

Jeromy's avatar
Jeromy committed
88 89
	path := strings.Join(req.Path(), "/")
	url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query)
90

91
	httpReq, err := http.NewRequest("POST", url, reader)
92 93 94 95 96 97
	if err != nil {
		return nil, err
	}

	// TODO extract string consts?
	if fileReader != nil {
98
		httpReq.Header.Set(contentTypeHeader, "multipart/form-data; boundary="+fileReader.Boundary())
99
	} else {
100
		httpReq.Header.Set(contentTypeHeader, applicationOctetStream)
101
	}
rht's avatar
rht committed
102
	httpReq.Header.Set(uaHeader, config.ApiVersion)
103

104 105
	ec := make(chan error, 1)
	rc := make(chan cmds.Response, 1)
rht's avatar
rht committed
106
	httpReq.Cancel = req.Context().Done()
107 108

	go func() {
109
		httpRes, err := c.httpClient.Do(httpReq)
110 111 112 113
		if err != nil {
			ec <- err
			return
		}
114

115 116 117 118 119 120
		// using the overridden JSON encoding in request
		res, err := getResponse(httpRes, req)
		if err != nil {
			ec <- err
			return
		}
121

122 123 124
		rc <- res
	}()

rht's avatar
rht committed
125 126 127 128 129 130 131 132 133
	select {
	case err := <-ec:
		return nil, err
	case res := <-rc:
		if found && len(previousUserProvidedEncoding) > 0 {
			// reset to user provided encoding after sending request
			// NB: if user has provided an encoding but it is the empty string,
			// still leave it as JSON.
			req.SetOption(cmds.EncShort, previousUserProvidedEncoding)
134
		}
rht's avatar
rht committed
135
		return res, nil
136 137 138
	}
}

139
func getQuery(req cmds.Request) (string, error) {
140
	query := url.Values{}
141
	for k, v := range req.Options() {
Jeromy's avatar
Jeromy committed
142
		if OptionSkipMap[k] {
Jeromy's avatar
Jeromy committed
143 144
			continue
		}
145
		str := fmt.Sprintf("%v", v)
146
		query.Set(k, str)
147
	}
148 149

	args := req.Arguments()
150 151
	argDefs := req.Command().Arguments

152 153 154 155 156 157 158 159
	argDefIndex := 0

	for _, arg := range args {
		argDef := argDefs[argDefIndex]
		// skip ArgFiles
		for argDef.Type == cmds.ArgFile {
			argDefIndex++
			argDef = argDefs[argDefIndex]
160 161
		}

162 163 164 165
		query.Add("arg", arg)

		if len(argDefs) > argDefIndex+1 {
			argDefIndex++
166
		}
167
	}
168

169
	return query.Encode(), nil
170
}
171

172 173 174
// getResponse decodes a http.Response to create a cmds.Response
func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
	var err error
175 176
	res := cmds.NewResponse(req)

177
	contentType := httpRes.Header.Get(contentTypeHeader)
178 179
	contentType = strings.Split(contentType, ";")[0]

180 181 182 183 184 185 186 187 188
	lengthHeader := httpRes.Header.Get(contentLengthHeader)
	if len(lengthHeader) > 0 {
		length, err := strconv.ParseUint(lengthHeader, 10, 64)
		if err != nil {
			return nil, err
		}
		res.SetLength(length)
	}

189 190
	rr := &httpResponseReader{httpRes}
	res.SetCloser(rr)
191

192
	if contentType != applicationJson {
Jeromy's avatar
Jeromy committed
193
		// for all non json output types, just stream back the output
194
		res.SetOutput(rr)
195
		return res, nil
196 197 198 199

	} else if len(httpRes.Header.Get(channelHeader)) > 0 {
		// if output is coming from a channel, decode each chunk
		outChan := make(chan interface{})
Jeromy's avatar
Jeromy committed
200

201
		go readStreamedJson(req, rr, outChan)
202

203
		res.SetOutput((<-chan interface{})(outChan))
204
		return res, nil
205 206
	}

207
	dec := json.NewDecoder(rr)
208

Jeromy's avatar
Jeromy committed
209
	// If we ran into an error
210 211
	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
212

Jeromy's avatar
Jeromy committed
213 214
		switch {
		case httpRes.StatusCode == http.StatusNotFound:
215 216 217 218
			// handle 404s
			e.Message = "Command not found."
			e.Code = cmds.ErrClient

219
		case contentType == plainText:
220
			// handle non-marshalled errors
221 222 223 224 225
			mes, err := ioutil.ReadAll(rr)
			if err != nil {
				return nil, err
			}
			e.Message = string(mes)
226 227
			e.Code = cmds.ErrNormal

Jeromy's avatar
Jeromy committed
228
		default:
229 230 231 232 233
			// handle marshalled errors
			err = dec.Decode(&e)
			if err != nil {
				return nil, err
			}
234 235 236 237
		}

		res.SetError(e, e.Code)

Jeromy's avatar
Jeromy committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251
		return res, nil
	}

	outputType := reflect.TypeOf(req.Command().Type)
	v, err := decodeTypedVal(outputType, dec)
	if err != nil && err != io.EOF {
		return nil, err
	}

	res.SetOutput(v)

	return res, nil
}

Jeromy's avatar
Jeromy committed
252 253
// read json objects off of the given stream, and write the objects out to
// the 'out' channel
254
func readStreamedJson(req cmds.Request, rr io.Reader, out chan<- interface{}) {
Jeromy's avatar
Jeromy committed
255
	defer close(out)
256
	dec := json.NewDecoder(rr)
Jeromy's avatar
Jeromy committed
257 258 259 260 261 262 263
	outputType := reflect.TypeOf(req.Command().Type)

	ctx := req.Context()

	for {
		v, err := decodeTypedVal(outputType, dec)
		if err != nil {
264
			if err != io.EOF {
Jeromy's avatar
Jeromy committed
265 266 267
				log.Error(err)
			}
			return
268
		}
Jeromy's avatar
Jeromy committed
269 270 271 272 273

		select {
		case <-ctx.Done():
			return
		case out <- v:
274
		}
275
	}
Jeromy's avatar
Jeromy committed
276
}
277

Jeromy's avatar
Jeromy committed
278 279
// decode a value of the given type, if the type is nil, attempt to decode into
// an interface{} anyways
Jeromy's avatar
Jeromy committed
280 281 282 283 284 285 286 287 288 289 290
func decodeTypedVal(t reflect.Type, dec *json.Decoder) (interface{}, error) {
	var v interface{}
	var err error
	if t != nil {
		v = reflect.New(t).Interface()
		err = dec.Decode(v)
	} else {
		err = dec.Decode(&v)
	}

	return v, err
291
}
292

Jeromy's avatar
Jeromy committed
293 294 295
// httpResponseReader reads from the response body, and checks for an error
// in the http trailer upon EOF, this error if present is returned instead
// of the EOF.
296 297 298 299 300 301
type httpResponseReader struct {
	resp *http.Response
}

func (r *httpResponseReader) Read(b []byte) (int, error) {
	n, err := r.resp.Body.Read(b)
302 303 304 305 306

	// reading on a closed response body is as good as an io.EOF here
	if err != nil && strings.Contains(err.Error(), "read on closed response body") {
		err = io.EOF
	}
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	if err == io.EOF {
		_ = r.resp.Body.Close()
		trailerErr := r.checkError()
		if trailerErr != nil {
			return n, trailerErr
		}
	}
	return n, err
}

func (r *httpResponseReader) checkError() error {
	if e := r.resp.Trailer.Get(StreamErrHeader); e != "" {
		return errors.New(e)
	}
	return nil
}

func (r *httpResponseReader) Close() error {
	return r.resp.Body.Close()
}