client.go 6.49 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 {
41 42
	return &client{
		serverAddress: address,
rht's avatar
rht committed
43
		httpClient:    http.DefaultClient,
44
	}
45
}
46

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

49 50
	if req.Context() == nil {
		log.Warningf("no context set in request")
51
		if err := req.SetRootContext(context.TODO()); err != nil {
52 53 54 55
			return nil, err
		}
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
56 57 58 59 60 61 62
	// 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
63
	req.SetOption(cmds.EncShort, cmds.JSON)
64

65 66 67
	// stream channel output
	req.SetOption(cmds.ChanOpt, "true")

68
	query, err := getQuery(req)
69 70 71 72
	if err != nil {
		return nil, err
	}

73
	var fileReader *MultiFileReader
74 75
	var reader io.Reader

76
	if req.Files() != nil {
77
		fileReader = NewMultiFileReader(req.Files(), true)
78
		reader = fileReader
79 80
	}

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

84
	httpReq, err := http.NewRequest("POST", url, reader)
85 86 87 88 89 90
	if err != nil {
		return nil, err
	}

	// TODO extract string consts?
	if fileReader != nil {
91
		httpReq.Header.Set(contentTypeHeader, "multipart/form-data; boundary="+fileReader.Boundary())
92
	} else {
93
		httpReq.Header.Set(contentTypeHeader, applicationOctetStream)
94
	}
rht's avatar
rht committed
95
	httpReq.Header.Set(uaHeader, config.ApiVersion)
96

rht's avatar
rht committed
97
	httpReq.Cancel = req.Context().Done()
rht's avatar
rht committed
98
	httpReq.Close = true
99

rht's avatar
rht committed
100 101 102 103
	httpRes, err := c.httpClient.Do(httpReq)
	if err != nil {
		return nil, err
	}
104

rht's avatar
rht committed
105 106 107
	// using the overridden JSON encoding in request
	res, err := getResponse(httpRes, req)
	if err != nil {
rht's avatar
rht committed
108
		return nil, err
109
	}
rht's avatar
rht committed
110 111 112 113 114 115 116 117 118

	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)
	}

	return res, nil
119 120
}

121
func getQuery(req cmds.Request) (string, error) {
122
	query := url.Values{}
123
	for k, v := range req.Options() {
Jeromy's avatar
Jeromy committed
124
		if OptionSkipMap[k] {
Jeromy's avatar
Jeromy committed
125 126
			continue
		}
127
		str := fmt.Sprintf("%v", v)
128
		query.Set(k, str)
129
	}
130 131

	args := req.Arguments()
132 133
	argDefs := req.Command().Arguments

134 135 136 137 138 139 140 141
	argDefIndex := 0

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

144 145 146 147
		query.Add("arg", arg)

		if len(argDefs) > argDefIndex+1 {
			argDefIndex++
148
		}
149
	}
150

151
	return query.Encode(), nil
152
}
153

154 155 156
// getResponse decodes a http.Response to create a cmds.Response
func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
	var err error
157 158
	res := cmds.NewResponse(req)

159
	contentType := httpRes.Header.Get(contentTypeHeader)
160 161
	contentType = strings.Split(contentType, ";")[0]

162 163 164 165 166 167 168 169 170
	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)
	}

171 172
	rr := &httpResponseReader{httpRes}
	res.SetCloser(rr)
173

174
	if contentType != applicationJson {
Jeromy's avatar
Jeromy committed
175
		// for all non json output types, just stream back the output
176
		res.SetOutput(rr)
177
		return res, nil
178 179 180 181

	} 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
182

183
		go readStreamedJson(req, rr, outChan)
184

185
		res.SetOutput((<-chan interface{})(outChan))
186
		return res, nil
187 188
	}

189
	dec := json.NewDecoder(rr)
190

Jeromy's avatar
Jeromy committed
191
	// If we ran into an error
192 193
	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
194

Jeromy's avatar
Jeromy committed
195 196
		switch {
		case httpRes.StatusCode == http.StatusNotFound:
197 198 199 200
			// handle 404s
			e.Message = "Command not found."
			e.Code = cmds.ErrClient

201
		case contentType == plainText:
202
			// handle non-marshalled errors
203 204 205 206 207
			mes, err := ioutil.ReadAll(rr)
			if err != nil {
				return nil, err
			}
			e.Message = string(mes)
208 209
			e.Code = cmds.ErrNormal

Jeromy's avatar
Jeromy committed
210
		default:
211 212 213 214 215
			// handle marshalled errors
			err = dec.Decode(&e)
			if err != nil {
				return nil, err
			}
216 217 218 219
		}

		res.SetError(e, e.Code)

Jeromy's avatar
Jeromy committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233
		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
234 235
// read json objects off of the given stream, and write the objects out to
// the 'out' channel
236
func readStreamedJson(req cmds.Request, rr io.Reader, out chan<- interface{}) {
Jeromy's avatar
Jeromy committed
237
	defer close(out)
238
	dec := json.NewDecoder(rr)
Jeromy's avatar
Jeromy committed
239 240 241 242 243 244 245
	outputType := reflect.TypeOf(req.Command().Type)

	ctx := req.Context()

	for {
		v, err := decodeTypedVal(outputType, dec)
		if err != nil {
246
			if err != io.EOF {
Jeromy's avatar
Jeromy committed
247 248 249
				log.Error(err)
			}
			return
250
		}
Jeromy's avatar
Jeromy committed
251 252 253 254 255

		select {
		case <-ctx.Done():
			return
		case out <- v:
256
		}
257
	}
Jeromy's avatar
Jeromy committed
258
}
259

Jeromy's avatar
Jeromy committed
260 261
// decode a value of the given type, if the type is nil, attempt to decode into
// an interface{} anyways
Jeromy's avatar
Jeromy committed
262 263 264 265 266 267 268 269 270 271 272
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
273
}
274

Jeromy's avatar
Jeromy committed
275 276 277
// 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.
278 279 280 281 282 283
type httpResponseReader struct {
	resp *http.Response
}

func (r *httpResponseReader) Read(b []byte) (int, error) {
	n, err := r.resp.Body.Read(b)
284 285 286 287 288

	// 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
	}
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
	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()
}