// TODO should be moved upstream
165336
func RelativizeClientConfigPaths(cfg *clientcmdapi.Config, base string) (err error) {
	for k, cluster := range cfg.Clusters {
		if len(cluster.CertificateAuthority) > 0 {
			if cluster.CertificateAuthority, err = util.MakeAbs(cluster.CertificateAuthority, ""); err != nil {
				return err
			}
			if cluster.CertificateAuthority, err = util.MakeRelative(cluster.CertificateAuthority, base); err != nil {
				return err
			}
			cfg.Clusters[k] = cluster
		}
	}
	for k, authInfo := range cfg.AuthInfos {
		if len(authInfo.ClientCertificate) > 0 {
			if authInfo.ClientCertificate, err = util.MakeAbs(authInfo.ClientCertificate, ""); err != nil {
				return err
			}
			if authInfo.ClientCertificate, err = util.MakeRelative(authInfo.ClientCertificate, base); err != nil {
				return err
			}
		}
		if len(authInfo.ClientKey) > 0 {
			if authInfo.ClientKey, err = util.MakeAbs(authInfo.ClientKey, ""); err != nil {
				return err
			}
			if authInfo.ClientKey, err = util.MakeRelative(authInfo.ClientKey, base); err != nil {
				return err
			}
		}
		cfg.AuthInfos[k] = authInfo
	}
	return nil
}
422773
func (c *ChannelsUnarchiveCall) Do(ctx context.Context) error {
	const endpoint = "channels.unarchive"
	v, err := c.Values()
	if err != nil {
		return err
	}
	var res struct {
		objects.GenericResponse
	}
	if err := c.service.client.postForm(ctx, endpoint, v, &res); err != nil {
		return errors.Wrap(err, `failed to post to channels.unarchive`)
	}
	if !res.OK {
		return errors.New(res.Error.String())
	}

	return nil
}
100333
func (pool *LoadBalancedPool) Do(req *http.Request) (resp *http.Response, err error) {
	return pool.DoWithTimeout(req, 0)
}
518388
func (r *receiver) flowTopUp() {
	if r.prefetch {
		_ = r.engine().Inject(func() { r.flow(r.maxFlow()) })
	}
}
987490
func (d *domainClient) MoveTo(ctx context.Context, args *MoveToArgs) (reply *MoveToReply, err error) {
	reply = new(MoveToReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "DOM.moveTo", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "DOM.moveTo", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "DOM", Op: "MoveTo", Err: err}
	}
	return
}
212510
func (c *Client) Do(opts interface{}) (interface{}, error) {
	// Bucket
	if _, ok := opts.(*RpbListKeysReq); ok {
		return c.listKeys(opts.(*RpbListKeysReq), string(opts.(*RpbListKeysReq).GetBucket()))
	}
	if _, ok := opts.(*RpbGetBucketReq); ok {
		return c.getBucket(opts.(*RpbGetBucketReq), string(opts.(*RpbGetBucketReq).GetBucket()))
	}
	if _, ok := opts.(*RpbSetBucketReq); ok {
		nval := opts.(*RpbSetBucketReq).Props.GetNVal()
		allowMulti := opts.(*RpbSetBucketReq).Props.GetAllowMult()
		return c.setBucket(opts.(*RpbSetBucketReq), string(opts.(*RpbSetBucketReq).GetBucket()), &nval, &allowMulti)
	}

	// Object
	if _, ok := opts.(*RpbGetReq); ok {
		return c.fetchObject(opts.(*RpbGetReq), string(opts.(*RpbGetReq).GetBucket()), string(opts.(*RpbGetReq).GetKey()))
	}
	if _, ok := opts.(*RpbDelReq); ok {
		return c.deleteObject(opts.(*RpbDelReq), string(opts.(*RpbDelReq).GetBucket()), string(opts.(*RpbDelReq).GetKey()))
	}

	// Query
	if _, ok := opts.(*RpbMapRedReq); ok {
		return c.mapReduce(opts.(*RpbMapRedReq), string(opts.(*RpbMapRedReq).GetRequest()), string(opts.(*RpbMapRedReq).GetContentType()))
	}
	if _, ok := opts.(*RpbIndexReq); ok {
		return c.index(opts.(*RpbIndexReq), string(opts.(*RpbIndexReq).GetBucket()), string(opts.(*RpbIndexReq).GetIndex()), string(opts.(*RpbIndexReq).GetKey()), string(opts.(*RpbIndexReq).GetRangeMin()), string(opts.(*RpbIndexReq).GetRangeMax()))
	}
	if _, ok := opts.(*RpbSearchQueryReq); ok {
		return c.search(opts.(*RpbSearchQueryReq), string(opts.(*RpbSearchQueryReq).GetIndex()), string(opts.(*RpbSearchQueryReq).GetQ()))
	}

	// Server
	if _, ok := opts.(*RpbSetClientIdReq); ok {
		return c.setClientId(opts.(*RpbSetClientIdReq), string(opts.(*RpbSetClientIdReq).GetClientId()))
	}

	return nil, nil
}
435526
func (c *vstConnection) do(ctx context.Context, req driver.Request, transport messageTransport) (driver.Response, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	vstReq, ok := req.(*vstRequest)
	if !ok {
		return nil, driver.WithStack(driver.InvalidArgumentError{Message: "request is not a *vstRequest"})
	}
	msgParts, err := vstReq.createMessageParts()
	if err != nil {
		return nil, driver.WithStack(err)
	}
	resp, err := transport.Send(ctx, msgParts...)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	// All data was send now
	vstReq.WroteRequest()

	// Wait for response
	var msg protocol.Message
	select {
	case msg, ok = <-resp:
		if !ok {
			// Message was canceled / timeout
			return nil, driver.WithStack(context.DeadlineExceeded)
		}
	case <-ctx.Done():
		// Context canceled while waiting here
		return nil, driver.WithStack(ctx.Err())
	}

	//fmt.Printf("Received msg: %d\n", msg.ID)
	var rawResponse *[]byte
	if ctx != nil {
		if v := ctx.Value(keyRawResponse); v != nil {
			if buf, ok := v.(*[]byte); ok {
				rawResponse = buf
			}
		}
	}

	vstResp, err := newResponse(msg.Data, c.endpoint.String(), rawResponse)
	if err != nil {
		fmt.Printf("Cannot decode msg %d: %#v\n", msg.ID, err)
		return nil, driver.WithStack(err)
	}
	if ctx != nil {
		if v := ctx.Value(keyResponse); v != nil {
			if respPtr, ok := v.(*driver.Response); ok {
				*respPtr = vstResp
			}
		}
	}
	return vstResp, nil
}
1360694
func (c *clusterConnection) Do(ctx context.Context, req driver.Request) (driver.Response, error) {
	followLeaderRedirect := true
	if ctx == nil {
		ctx = context.Background()
	} else {
		if v := ctx.Value(keyFollowLeaderRedirect); v != nil {
			if on, ok := v.(bool); ok {
				followLeaderRedirect = on
			}
		}
	}
	// Timeout management.
	// We take the given timeout and divide it in 3 so we allow for other servers
	// to give it a try if an earlier server fails.
	deadline, hasDeadline := ctx.Deadline()
	var timeout time.Duration
	if hasDeadline {
		timeout = deadline.Sub(time.Now())
	} else {
		timeout = c.defaultTimeout
	}

	serverCount := len(c.servers)
	var specificServer driver.Connection
	if v := ctx.Value(keyEndpoint); v != nil {
		if endpoint, ok := v.(string); ok {
			// Specific endpoint specified
			serverCount = 1
			var err error
			specificServer, err = c.getSpecificServer(endpoint)
			if err != nil {
				return nil, driver.WithStack(err)
			}
		}
	}

	timeoutDivider := math.Max(1.0, math.Min(3.0, float64(serverCount)))
	attempt := 1
	s := specificServer
	if s == nil {
		s = c.getCurrentServer()
	}
	for {
		// Send request to specific endpoint with a 1/3 timeout (so we get 3 attempts)
		serverCtx, cancel := context.WithTimeout(ctx, time.Duration(float64(timeout)/timeoutDivider))
		resp, err := s.Do(serverCtx, req)
		cancel()

		isNoLeaderResponse := false
		if err == nil && resp.StatusCode() == 503 {
			// Service unavailable, parse the body, perhaps this is a "no leader"
			// case where we have to failover.
			var aerr driver.ArangoError
			if perr := resp.ParseBody("", &aerr); perr == nil && aerr.HasError {
				if driver.IsNoLeader(aerr) {
					isNoLeaderResponse = true
					// Save error in case we have no more servers
					err = aerr
				}
			}

		}
		if !isNoLeaderResponse || !followLeaderRedirect {
			if err == nil {
				// We're done
				return resp, nil
			}
			// No success yet
			if driver.IsCanceled(err) {
				// Request was cancelled, we return directly.
				return nil, driver.WithStack(err)
			}
			// If we've completely written the request, we return the error,
			// otherwise we'll failover to a new server.
			if req.Written() {
				// Request has been written to network, do not failover
				if driver.IsArangoError(err) {
					// ArangoError, so we got an error response from server.
					return nil, driver.WithStack(err)
				}
				// Not an ArangoError, so it must be some kind of timeout, network ... error.
				return nil, driver.WithStack(&driver.ResponseError{Err: err})
			}
		}

		// Failed, try next server
		attempt++
		if specificServer != nil {
			// A specific server was specified, no failover.
			return nil, driver.WithStack(err)
		}
		if attempt > len(c.servers) {
			// We've tried all servers. Giving up.
			return nil, driver.WithStack(err)
		}
		s = c.getNextServer()
	}
}
558234
func (f DoerFunc) Do(req *http.Request) (resp *http.Response, err error) {
	return f(req)
}
253824
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error {
	var query string
	switch op {
	case queryOperation:
		query = constructQuery(v, variables)
	case mutationOperation:
		query = constructMutation(v, variables)
	}
	in := struct {
		Query     string                 `json:"query"`
		Variables map[string]interface{} `json:"variables,omitempty"`
	}{
		Query:     query,
		Variables: variables,
	}
	var buf bytes.Buffer
	err := json.NewEncoder(&buf).Encode(in)
	if err != nil {
		return err
	}
	resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		body, _ := ioutil.ReadAll(resp.Body)
		return fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body)
	}
	var out struct {
		Data   *json.RawMessage
		Errors errors
		//Extensions interface{} // Unused.
	}
	err = json.NewDecoder(resp.Body).Decode(&out)
	if err != nil {
		// TODO: Consider including response body in returned error, if deemed helpful.
		return err
	}
	if out.Data != nil {
		err := jsonutil.UnmarshalGraphQL(*out.Data, v)
		if err != nil {
			// TODO: Consider including response body in returned error, if deemed helpful.
			return err
		}
	}
	if len(out.Errors) > 0 {
		return out.Errors
	}
	return nil
}
997788
func (s *Service) post(w http.ResponseWriter, r *http.Request, _ mux.Params) {
	// Read request body's json payload into buffer.
	b, err := ioutil.ReadAll(r.Body)
	todo, err := decode(b)
	if err != nil {
		http.Error(w, err.Error(), 500)
	}

	// Use the url path as key.
	key := []byte(r.URL.String())

	// Put key/buffer into todos bucket.
	if err := s.todos.Put(key, b); err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	if verbose {
		log.Printf("server: %s: %v", key, todo.Task)
	}

	w.Header().Set("Content-Type", "text/plain")
	fmt.Fprintf(w, "put todo for %s: %s\n", key, todo)
}
915977
func (r *Request) Do() error {
	err := r.send()
	if err != nil {
		return err
	}

	err = r.unpack()
	if err != nil {
		return err
	}
	return nil
}
245762
func (p Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	// start by selecting most specific matching upstream config
	upstream := p.match(r)
	if upstream == nil {
		return p.Next.ServeHTTP(w, r)
	}

	// this replacer is used to fill in header field values
	replacer := httpserver.NewReplacer(r, nil, "")

	// outreq is the request that makes a roundtrip to the backend
	outreq, cancel := createUpstreamRequest(w, r)
	defer cancel()

	// If we have more than one upstream host defined and if retrying is enabled
	// by setting try_duration to a non-zero value, caddy will try to
	// retry the request at a different host if the first one failed.
	//
	// This requires us to possibly rewind and replay the request body though,
	// which in turn requires us to buffer the request body first.
	//
	// An unbuffered request is usually preferrable, because it reduces latency
	// as well as memory usage. Furthermore it enables different kinds of
	// HTTP streaming applications like gRPC for instance.
	requiresBuffering := upstream.GetHostCount() > 1 && upstream.GetTryDuration() != 0

	if requiresBuffering {
		body, err := newBufferedBody(outreq.Body)
		if err != nil {
			return http.StatusBadRequest, errors.New("failed to read downstream request body")
		}
		if body != nil {
			outreq.Body = body
		}
	}

	// The keepRetrying function will return true if we should
	// loop and try to select another host, or false if we
	// should break and stop retrying.
	start := time.Now()
	keepRetrying := func(backendErr error) bool {
		// if downstream has canceled the request, break
		if backendErr == context.Canceled {
			return false
		}
		// if we've tried long enough, break
		if time.Since(start) >= upstream.GetTryDuration() {
			return false
		}
		// otherwise, wait and try the next available host
		time.Sleep(upstream.GetTryInterval())
		return true
	}

	var backendErr error
	for {
		// since Select() should give us "up" hosts, keep retrying
		// hosts until timeout (or until we get a nil host).
		host := upstream.Select(r)
		if host == nil {
			if backendErr == nil {
				backendErr = errors.New("no hosts available upstream")
			}
			if !keepRetrying(backendErr) {
				break
			}
			continue
		}
		if rr, ok := w.(*httpserver.ResponseRecorder); ok && rr.Replacer != nil {
			rr.Replacer.Set("upstream", host.Name)
		}

		proxy := host.ReverseProxy

		// a backend's name may contain more than just the host,
		// so we parse it as a URL to try to isolate the host.
		if nameURL, err := url.Parse(host.Name); err == nil {
			outreq.Host = nameURL.Host
			if proxy == nil {
				proxy = NewSingleHostReverseProxy(nameURL,
					host.WithoutPathPrefix,
					http.DefaultMaxIdleConnsPerHost,
					upstream.GetTimeout(),
					upstream.GetFallbackDelay(),
				)
			}

			// use upstream credentials by default
			if outreq.Header.Get("Authorization") == "" && nameURL.User != nil {
				pwd, _ := nameURL.User.Password()
				outreq.SetBasicAuth(nameURL.User.Username(), pwd)
			}
		} else {
			outreq.Host = host.Name
		}
		if proxy == nil {
			return http.StatusInternalServerError, errors.New("proxy for host '" + host.Name + "' is nil")
		}

		// set headers for request going upstream
		if host.UpstreamHeaders != nil {
			// modify headers for request that will be sent to the upstream host
			mutateHeadersByRules(outreq.Header, host.UpstreamHeaders, replacer, host.UpstreamHeaderReplacements)
			if hostHeaders, ok := outreq.Header["Host"]; ok && len(hostHeaders) > 0 {
				outreq.Host = hostHeaders[len(hostHeaders)-1]
			}
		}

		// prepare a function that will update response
		// headers coming back downstream
		var downHeaderUpdateFn respUpdateFn
		if host.DownstreamHeaders != nil {
			downHeaderUpdateFn = createRespHeaderUpdateFn(host.DownstreamHeaders, replacer, host.DownstreamHeaderReplacements)
		}

		// Before we retry the request we have to make sure
		// that the body is rewound to it's beginning.
		if bb, ok := outreq.Body.(*bufferedBody); ok {
			if err := bb.rewind(); err != nil {
				return http.StatusInternalServerError, errors.New("unable to rewind downstream request body")
			}
		}

		// tell the proxy to serve the request
		//
		// NOTE:
		//   The call to proxy.ServeHTTP can theoretically panic.
		//   To prevent host.Conns from getting out-of-sync we thus have to
		//   make sure that it's _always_ correctly decremented afterwards.
		func() {
			atomic.AddInt64(&host.Conns, 1)
			defer atomic.AddInt64(&host.Conns, -1)
			backendErr = proxy.ServeHTTP(w, outreq, downHeaderUpdateFn)
		}()

		// if no errors, we're done here
		if backendErr == nil {
			return 0, nil
		}

		if backendErr == httpserver.ErrMaxBytesExceeded {
			return http.StatusRequestEntityTooLarge, backendErr
		}

		if backendErr == context.Canceled {
			return CustomStatusContextCancelled, backendErr
		}

		// failover; remember this failure for some time if
		// request failure counting is enabled
		timeout := host.FailTimeout
		if timeout > 0 {
			atomic.AddInt32(&host.Fails, 1)
			go func(host *UpstreamHost, timeout time.Duration) {
				time.Sleep(timeout)
				atomic.AddInt32(&host.Fails, -1)
			}(host, timeout)
		}

		// if we've tried long enough, break
		if !keepRetrying(backendErr) {
			break
		}
	}

	return http.StatusBadGateway, backendErr
}
285257
func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
	if client == nil {
		client = http.DefaultClient
	}

	// Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go.
	cancel := canceler(client, req)

	type responseAndError struct {
		resp *http.Response
		err  error
	}
	result := make(chan responseAndError, 1)

	go func() {
		resp, err := client.Do(req)
		result <- responseAndError{resp, err}
	}()

	select {
	case <-ctx.Done():
		cancel()
		return nil, ctx.Err()
	case r := <-result:
		return r.resp, r.err
	}
}
508220
func (m *MetaClient) Do(ctx context.Context, path, method string, authorizer influx.Authorizer, params map[string]string, body io.Reader) (*http.Response, error) {
	type result struct {
		Response *http.Response
		Err      error
	}

	resps := make(chan (result))
	go func() {
		resp, err := m.client.Do(m.URL, path, method, authorizer, params, body)
		resps <- result{resp, err}
	}()

	select {
	case resp := <-resps:
		return resp.Response, resp.Err
	case <-ctx.Done():
		return nil, chronograf.ErrUpstreamTimeout
	}
}
557361
func toDate(ts time.Time) *storagetransfer.Date {
	return &storagetransfer.Date{
		Day:   int64(ts.Day()),
		Month: int64(ts.Month()),
		Year:  int64(ts.Year()),
	}
}
1268831
func (c *client) do(method, resource string, payload map[string]string, authNeeded bool) (response []byte, err error) {
	respCh := make(chan []byte)
	errCh := make(chan error)
	<-c.throttle
	go c.makeReq(method, resource, payload, authNeeded, respCh, errCh)
	response = <-respCh
	err = <-errCh
	return
}