client.go 5.86 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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

	go func() {
		httpRes, err := http.DefaultClient.Do(httpReq)
		if err != nil {
			ec <- err
			return
		}
		// using the overridden JSON encoding in request
		res, err := getResponse(httpRes, req)
		if err != nil {
			ec <- err
			return
		}
		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
		}
132 133 134
	}
}

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

	args := req.Arguments()
143 144
	argDefs := req.Command().Arguments

145 146 147 148 149 150 151 152
	argDefIndex := 0

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

155 156 157 158
		query.Add("arg", arg)

		if len(argDefs) > argDefIndex+1 {
			argDefIndex++
159
		}
160
	}
161

162
	return query.Encode(), nil
163
}
164

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

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

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

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

	} 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)
192
			outputType := reflect.TypeOf(req.Command().Type)
193

Jeromy's avatar
Jeromy committed
194
			ctx := req.Context()
195

196
			for {
197 198 199 200 201 202 203 204
				var v interface{}
				var err error
				if outputType != nil {
					v = reflect.New(outputType).Interface()
					err = dec.Decode(v)
				} else {
					err = dec.Decode(&v)
				}
205 206 207 208
				if err != nil && err != io.EOF {
					fmt.Println(err.Error())
					return
				}
209 210 211 212 213 214 215 216

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

217 218
				if err == io.EOF {
					close(outChan)
219 220 221 222 223 224
					return
				}
				outChan <- v
			}
		}()

225
		res.SetOutput((<-chan interface{})(outChan))
226
		return res, nil
227 228 229 230 231 232
	}

	dec := json.NewDecoder(httpRes.Body)

	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

		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
			}
252 253 254 255 256
		}

		res.SetError(e, e.Code)

	} else {
257
		outputType := reflect.TypeOf(req.Command().Type)
258 259 260 261 262 263 264 265
		var v interface{}

		if outputType != nil {
			v = reflect.New(outputType).Interface()
			err = dec.Decode(v)
		} else {
			err = dec.Decode(&v)
		}
266
		if err != nil && err != io.EOF {
267 268
			return nil, err
		}
269 270 271
		if v != nil {
			res.SetOutput(v)
		}
272 273
	}

274 275
	return res, nil
}