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

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

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

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

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

25 26 27 28 29 30 31 32
// Client is the commands HTTP client interface.
type Client interface {
	Send(req cmds.Request) (cmds.Response, error)
}

type client struct {
	serverAddress string
}
33

34 35 36
func NewClient(address string) Client {
	return &client{address}
}
37

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

40 41 42 43 44 45 46 47
	if req.Context() == nil {
		log.Warningf("no context set in request")
		err := req.SetRootContext(context.TODO())
		if err != nil {
			return nil, err
		}
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
48 49 50 51 52 53 54
	// 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
55
	req.SetOption(cmds.EncShort, cmds.JSON)
56

57 58 59
	// stream channel output
	req.SetOption(cmds.ChanOpt, "true")

60
	query, err := getQuery(req)
61 62 63 64
	if err != nil {
		return nil, err
	}

65
	var fileReader *MultiFileReader
66 67
	var reader io.Reader

68
	if req.Files() != nil {
69
		fileReader = NewMultiFileReader(req.Files(), true)
70 71 72 73 74
		reader = fileReader
	} else {
		// if we have no file data, use an empty Reader
		// (http.NewRequest panics when a nil Reader is used)
		reader = strings.NewReader("")
75 76
	}

77 78 79
	path := strings.Join(req.Path(), "/")
	url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query)

80
	httpReq, err := http.NewRequest("POST", url, reader)
81 82 83 84 85 86 87 88 89 90 91 92 93 94
	if err != nil {
		return nil, err
	}

	// TODO extract string consts?
	if fileReader != nil {
		httpReq.Header.Set("Content-Type", "multipart/form-data; boundary="+fileReader.Boundary())
		httpReq.Header.Set("Content-Disposition", "form-data: name=\"files\"")
	} else {
		httpReq.Header.Set("Content-Type", "application/octet-stream")
	}
	version := config.CurrentVersionNumber
	httpReq.Header.Set("User-Agent", fmt.Sprintf("/go-ipfs/%s/", version))

95 96
	ec := make(chan error, 1)
	rc := make(chan cmds.Response, 1)
Jeromy's avatar
Jeromy committed
97
	dc := req.Context().Done()
98 99 100 101 102 103 104

	go func() {
		httpRes, err := http.DefaultClient.Do(httpReq)
		if err != nil {
			ec <- err
			return
		}
105

106 107 108 109 110 111
		// using the overridden JSON encoding in request
		res, err := getResponse(httpRes, req)
		if err != nil {
			ec <- err
			return
		}
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
		rc <- res
	}()

	for {
		select {
		case <-dc:
			log.Debug("Context cancelled, cancelling HTTP request...")
			tr := http.DefaultTransport.(*http.Transport)
			tr.CancelRequest(httpReq)
			dc = nil // Wait for ec or rc
		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)
			}
			return res, nil
		}
134 135 136
	}
}

137
func getQuery(req cmds.Request) (string, error) {
138
	query := url.Values{}
139
	for k, v := range req.Options() {
140
		str := fmt.Sprintf("%v", v)
141
		query.Set(k, str)
142
	}
143 144

	args := req.Arguments()
145 146
	argDefs := req.Command().Arguments

147 148 149 150 151 152 153 154
	argDefIndex := 0

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

157 158 159 160
		query.Add("arg", arg)

		if len(argDefs) > argDefIndex+1 {
			argDefIndex++
161
		}
162
	}
163

164
	return query.Encode(), nil
165
}
166

167 168 169
// getResponse decodes a http.Response to create a cmds.Response
func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
	var err error
170 171
	res := cmds.NewResponse(req)

172
	contentType := httpRes.Header.Get(contentTypeHeader)
173 174
	contentType = strings.Split(contentType, ";")[0]

175 176 177 178 179 180 181 182 183
	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)
	}

184 185
	res.SetCloser(httpRes.Body)

186
	if len(httpRes.Header.Get(streamHeader)) > 0 {
187
		// if output is a stream, we can just use the body reader
188
		res.SetOutput(httpRes.Body)
189
		return res, nil
190 191 192 193 194 195

	} else if len(httpRes.Header.Get(channelHeader)) > 0 {
		// if output is coming from a channel, decode each chunk
		outChan := make(chan interface{})
		go func() {
			dec := json.NewDecoder(httpRes.Body)
196
			outputType := reflect.TypeOf(req.Command().Type)
197

Jeromy's avatar
Jeromy committed
198
			ctx := req.Context()
199

200
			for {
201 202 203 204 205 206 207 208
				var v interface{}
				var err error
				if outputType != nil {
					v = reflect.New(outputType).Interface()
					err = dec.Decode(v)
				} else {
					err = dec.Decode(&v)
				}
209 210 211 212 213 214 215

				// since we are just looping reading on the response, the only way to
				// know we are 'done' is for the consumer to close the response body.
				// doing so doesnt throw an io.EOF, but we want to treat it like one.
				if err != nil && strings.Contains(err.Error(), "read on closed response body") {
					err = io.EOF
				}
216
				if err != nil && err != io.EOF {
217
					log.Error(err)
218 219
					return
				}
220 221 222 223 224 225 226 227

				select {
				case <-ctx.Done():
					close(outChan)
					return
				default:
				}

228 229
				if err == io.EOF {
					close(outChan)
230 231 232 233 234 235
					return
				}
				outChan <- v
			}
		}()

236
		res.SetOutput((<-chan interface{})(outChan))
237
		return res, nil
238 239 240 241 242 243
	}

	dec := json.NewDecoder(httpRes.Body)

	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

		if httpRes.StatusCode == http.StatusNotFound {
			// handle 404s
			e.Message = "Command not found."
			e.Code = cmds.ErrClient

		} else if contentType == "text/plain" {
			// handle non-marshalled errors
			buf := bytes.NewBuffer(nil)
			io.Copy(buf, httpRes.Body)
			e.Message = string(buf.Bytes())
			e.Code = cmds.ErrNormal

		} else {
			// handle marshalled errors
			err = dec.Decode(&e)
			if err != nil {
				return nil, err
			}
263 264 265 266 267
		}

		res.SetError(e, e.Code)

	} else {
268
		outputType := reflect.TypeOf(req.Command().Type)
269 270 271 272 273 274 275 276
		var v interface{}

		if outputType != nil {
			v = reflect.New(outputType).Interface()
			err = dec.Decode(v)
		} else {
			err = dec.Decode(&v)
		}
277
		if err != nil && err != io.EOF {
278 279
			return nil, err
		}
280 281 282
		if v != nil {
			res.SetOutput(v)
		}
283 284
	}

285 286
	return res, nil
}