// runRequest runs the given request and sends the reply.
165181
func (conn *Conn) runRequest(
	req boundRequest,
	arg reflect.Value,
	version int,
	recorder Recorder,
) {
	// If the request causes a panic, ensure we log that before closing the connection.
	defer func() {
		if panicResult := recover(); panicResult != nil {
			logger.Criticalf(
				"panic running request %+v with arg %+v: %v\n%v", req, arg, panicResult, string(debug.Stack()))
			conn.writeErrorResponse(&req.hdr, errors.Errorf("%v", panicResult), recorder)
		}
	}()
	defer conn.srvPending.Done()

	// Create a request-specific context, cancelled when the
	// request returns.
	//
	// TODO(axw) provide a means for clients to cancel a request.
	ctx, cancel := context.WithCancel(conn.context)
	defer cancel()

	rv, err := req.Call(ctx, req.hdr.Request.Id, arg)
	if err != nil {
		err = conn.writeErrorResponse(&req.hdr, req.transformErrors(err), recorder)
	} else {
		hdr := &Header{
			RequestId: req.hdr.RequestId,
			Version:   version,
		}
		var rvi interface{}
		if rv.IsValid() {
			rvi = rv.Interface()
		} else {
			rvi = struct{}{}
		}
		if err := recorder.HandleReply(req.hdr.Request, hdr, rvi); err != nil {
			logger.Errorf("error recording reply %+v: %T %+v", hdr, err, err)
		}
		conn.sending.Lock()
		err = conn.codec.WriteMessage(hdr, rvi)
		conn.sending.Unlock()
	}
	if err != nil {
		// If the message failed due to the other end closing the socket, that
		// is expected when an agent restarts so no need to log an  error.
		// The error type here is errors.errorString so all we can do is a match
		// on the error string content.
		msg := err.Error()
		if !strings.Contains(msg, "websocket: close sent") &&
			!strings.Contains(msg, "write: broken pipe") {
			logger.Errorf("error writing response: %T %+v", err, err)
		}
	}
}
268230
func (c *UDPClient) execRequest(message *proto.Msg) (*proto.Msg, error) {
	err := c.conn.SetDeadline(time.Now().Add(c.timeout))
	if err != nil {
		return nil, err
	}
	data, err := pb.Marshal(message)
	if err != nil {
		return nil, err
	}
	if len(data) > MaxUDPSize {
		return nil, fmt.Errorf("unable to send message, too large for udp")
	}
	if _, err = c.conn.Write(data); err != nil {
		return nil, err
	}
	return nil, nil
}
938593
func (c *Client) request(params *url.Values, v *Response) error {
	var body string
	if params != nil {
		body = params.Encode()
	}

	method := "GET"
	requestURL := fmt.Sprintf("%v/?%s", c.BaseURL, body)
	var requestBody io.Reader
	if c.UsePost {
		method = "POST"
		requestURL = c.BaseURL.String()
		requestBody = strings.NewReader(body)
	}
	request, err := http.NewRequest(method, requestURL, requestBody)
	if err != nil {
		return err
	}

	log.Debugf("HTTP REQUEST: %s %s %s", method, requestURL, body)

	if c.UsePost {
		request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}
	request.Header.Add("Accept", "application/json")
	request.Header.Add("User-Agent", "LinodeGo/"+ClientVersion+" Go/"+runtime.Version())

	response, err := c.HTTPClient.Do(request)
	if err != nil {
		log.Errorf("Failed to get API response: %v", err)
		return err
	}

	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Errorf("Failed to parse API response: %v", err)
		return err
	}

	log.Debugf("HTTP RESPONSE: %s", string(responseBody))

	// Status code 500 is a server error and means nothing can be done at this point.
	if response.StatusCode != 200 {
		return ErrUnexpectedResponse
	}

	if err = json.Unmarshal(responseBody, v); err != nil {
		return err
	}

	if len(v.Errors) > 0 {
		if v.Errors[0].ErrorCode == 4 {
			return ErrAuthentication
		}
		// Need to return all errors to client. Perhaps wrap the error structure as a property for a custom error class
		return errors.New(fmt.Sprintf("API Error: %s, Code %d", v.Errors[0].ErrorMessage, v.Errors[0].ErrorCode))
	}

	return nil
}
289140
func (flcliapi *Flcliapi) Request(request []string) (reply []string, err error) {
	flcliapi.pipe.SendMessage("REQUEST", request)
	reply, err = flcliapi.pipe.RecvMessage(0)
	if err == nil {
		status := reply[0]
		reply = reply[1:]
		if status == "FAILED" {
			reply = reply[0:0]
		}
	}
	return
}
1095097
func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, urlStr, body)
	if err != nil {
		return nil, err
	}
	req.Header.Add(HeaderContentType, JSONMime)
	req.Header.Add(HeaderAccept, JSONMime)
	return req, nil
}
546367
func (c *HTTPClient) doRequest(req *http.Request) (resp *http.Response, err error) {
	debugRequest(req) //DEBUG
	req.SetBasicAuth(c.apiKeyPublic, c.apiKeyPrivate)
	for attempt := 0; attempt < NbAttempt; attempt++ {
		if resp != nil {
			resp.Body.Close()
		}
		resp, err = c.client.Do(req)
		if err != nil || (resp != nil && resp.StatusCode != 500) {
			break
		}
	}
	defer debugResponse(resp) //DEBUG
	if err != nil {
		return resp, fmt.Errorf("Error getting %s: %s", req.URL, err)
	}
	err = checkResponseError(resp)
	return resp, err
}
1077941
func (c *budgetCommand) Run(ctx *cmd.Context) error {
	modelUUID, err := c.getModelUUID()
	if err != nil {
		return errors.Annotate(err, "failed to get model uuid")
	}
	client, err := c.BakeryClient()
	if err != nil {
		return errors.Annotate(err, "failed to create an http client")
	}
	apiRoot, err := rcmd.GetMeteringURLForModelCmd(&c.ModelCommandBase)
	if err != nil {
		return errors.Trace(err)
	}
	api, err := c.newBudgetAPIClient(apiRoot, client)
	if err != nil {
		return errors.Annotate(err, "failed to create an api client")
	}
	resp, err := api.UpdateBudget(modelUUID, c.Wallet, c.Limit)
	if err != nil {
		return errors.Annotate(err, "failed to update the budget")
	}
	fmt.Fprintln(ctx.Stdout, resp)
	return nil
}
980114
func (c *setPlanCommand) Run(ctx *cmd.Context) error {
	root, err := c.NewAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	client := application.NewClient(root)
	credentials, err := c.requestMetricCredentials(client, ctx)
	if err != nil {
		return errors.Trace(err)
	}
	err = client.SetMetricCredentials(c.Application, credentials)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
863164
func (self *HttpClient) Request(method string, urlpath string, body io.Reader, headers map[string]string) (req *http.Request) {
	if u, err := self.BaseURL.Parse(urlpath); err != nil {
		log.Fatal(err)
	} else {
		urlpath = u.String()
	}

	req, err := http.NewRequest(strings.ToUpper(method), urlpath, body)
	if err != nil {
		log.Fatal(err)
	}

	req.Close = self.Close
	req.Host = self.Host

	self.addHeaders(req, headers)

	return
}
592392
func (c *Client) PerformRequest(method, path string, params url.Values, body interface{}) (*Response, error) {
	start := time.Now().UTC()

	c.mu.RLock()
	timeout := c.healthcheckTimeout
	retries := c.maxRetries
	c.mu.RUnlock()

	var err error
	var conn *conn
	var req *Request
	var resp *Response
	var retried bool

	// We wait between retries, using simple exponential back-off.
	// TODO: Make this configurable, including the jitter.
	retryWaitMsec := int64(100 + (rand.Intn(20) - 10))

	for {
		pathWithParams := path
		if len(params) > 0 {
			pathWithParams += "?" + params.Encode()
		}

		// Get a connection
		conn, err = c.next()
		if err == ErrNoClient {
			if !retried {
				// Force a healtcheck as all connections seem to be dead.
				c.healthcheck(timeout, false)
			}
			retries -= 1
			if retries <= 0 {
				return nil, err
			}
			retried = true
			time.Sleep(time.Duration(retryWaitMsec) * time.Millisecond)
			retryWaitMsec += retryWaitMsec
			continue // try again
		}
		if err != nil {
			c.errorf("elastic: cannot get connection from pool")
			return nil, err
		}

		req, err = NewRequest(method, conn.URL()+pathWithParams)
		if err != nil {
			c.errorf("elastic: cannot create request for %s %s: %v", strings.ToUpper(method), conn.URL()+pathWithParams, err)
			return nil, err
		}

		if c.basicAuth {
			((*http.Request)(req)).SetBasicAuth(c.basicAuthUsername, c.basicAuthPassword)
		}

		// Set body
		if body != nil {
			switch b := body.(type) {
			case string:
				req.SetBodyString(b)
				break
			default:
				req.SetBodyJson(body)
				break
			}
		}

		// Tracing
		c.dumpRequest((*http.Request)(req))

		// Get response
		res, err := c.c.Do((*http.Request)(req))
		if err != nil {
			retries -= 1
			if retries <= 0 {
				c.errorf("elastic: %s is dead", conn.URL())
				conn.MarkAsDead()
				return nil, err
			}
			retried = true
			time.Sleep(time.Duration(retryWaitMsec) * time.Millisecond)
			retryWaitMsec += retryWaitMsec
			continue // try again
		}
		if res.Body != nil {
			defer res.Body.Close()
		}

		// Check for errors
		if err := checkResponse(res); err != nil {
			retries -= 1
			if retries <= 0 {
				return nil, err
			}
			retried = true
			time.Sleep(time.Duration(retryWaitMsec) * time.Millisecond)
			retryWaitMsec += retryWaitMsec
			continue // try again
		}

		// Tracing
		c.dumpResponse(res)

		// We successfully made a request with this connection
		conn.MarkAsHealthy()

		resp, err = c.newResponse(res)
		if err != nil {
			return nil, err
		}

		break
	}

	duration := time.Now().UTC().Sub(start)
	c.infof("%s %s [status:%d, request:%.3fs]",
		strings.ToUpper(method),
		req.URL,
		resp.StatusCode,
		float64(int64(duration/time.Millisecond))/1000)

	return resp, nil
}
187751
func (c *EmailChange) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("EmailChange#Run", func() error { return err })()

	if !libkb.CheckEmail.F(c.arg.NewEmail) {
		return libkb.BadEmailError{}
	}

	var me *libkb.User
	me, err = libkb.LoadMe(libkb.NewLoadUserArgWithMetaContext(m).WithForceReload())
	if err != nil {
		return err
	}

	// need unlocked signing key
	ska := libkb.SecretKeyArg{
		Me:      me,
		KeyType: libkb.DeviceSigningKeyType,
	}
	arg := m.SecretKeyPromptArg(ska, "tracking signature")
	signingKey, err := m.G().Keyrings.GetSecretKeyWithPrompt(m, arg)
	if err != nil {
		return err
	}
	if signingKey == nil {
		return libkb.NoSecretKeyError{}
	}
	var proof *jsonw.Wrapper
	proof, err = me.UpdateEmailProof(m, signingKey, c.arg.NewEmail)
	if err != nil {
		return err
	}
	var sig string
	sig, _, _, err = libkb.SignJSON(proof, signingKey)
	if err != nil {
		return err
	}

	_, err = m.G().API.Post(m, libkb.APIArg{
		Endpoint:    "account/email_update_signed",
		SessionType: libkb.APISessionTypeREQUIRED,
		Args: libkb.HTTPArgs{
			"sig":         libkb.S{Val: sig},
			"signing_kid": libkb.S{Val: signingKey.GetKID().String()},
		},
	})

	if err != nil {
		return err
	}

	return nil
}
420497
func (a *netAPI) doRequest(ctx context.Context, requestPath string, req proto.Message, resp proto.Message) error {
	p, err := proto.Marshal(req)
	if err != nil {
		return err
	}

	u := *a.url // Make a copy of URL
	u.Path = requestPath
	httpReq, err := http.NewRequest("POST", u.String(), bytes.NewReader(p))
	httpReq.Header.Add("Content-Type", "application/x-protobuf")
	httpReq = httpReq.WithContext(ctx)
	httpResp, err := a.client.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != 200 {
		return fmt.Errorf("safebrowsing: unexpected server response code: %d", httpResp.StatusCode)
	}
	body, err := ioutil.ReadAll(httpResp.Body)
	if err != nil {
		return err
	}
	return proto.Unmarshal(body, resp)
}
537745
func (ss *simpleSource) Run() error {

	out, err := exec.Command(ss.command, ss.args...).Output()
	if err != nil {
		return err
	}

	ss.rawData = out
	return nil
}
1014132
func (l *Linode) Request(action string, params Parameters, result interface{}) (*Response, error) {
	// Initialize the request.
	req, err := http.NewRequest("GET", l.apiEndpoint, nil)
	if err != nil {
		return nil, NewError(err)
	}
	params.Set(apiAction, action)
	params.Set(apiKey, l.apiKey)
	req.URL.RawQuery = params.Encode()

	// Make the request.
	resp, err := client.Do(req)
	if err != nil {
		return nil, NewError(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, NewError(fmt.Errorf("Expected status code %d, received %d", http.StatusOK, resp.StatusCode))
	}

	// Decode the response.
	var response *Response
	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&response); err != nil {
		return nil, NewError(err)
	}

	// Decode the raw data into action-specific data.
	if result != nil {
		if err = json.Unmarshal(response.RawData, &result); err != nil {
			return nil, NewError(err)
		}
		response.Data = result
	}

	// If we have errors in the response, return both the response as well
	// as an API error.
	if len(response.Errors) != 0 {
		return response, NewApiError(response.Errors[0].Code, response.Errors[0].Message)
	}
	return response, nil
}
899379
func (c *Client) SendRequest(method string, params interface{}, conn net.Conn) (interface{}, error) {
	request := Request{Method: method, Params: params}
	b, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}
	b = append(b, '\n')
	_, err = conn.Write(b)
	if err != nil {
		return nil, err
	}
	reader := bufio.NewReader(conn)
	b2, err := reader.ReadBytes('\n')
	if err != nil {
		return nil, err
	}
	var response Response
	err = json.Unmarshal(b2, &response)
	if err != nil {
		return nil, err
	}
	if response.Error != nil {
		return nil, fmt.Errorf("%s", response.Error.Message)
	}

	if response.Result == nil {
		return nil, fmt.Errorf("No valid result returned")
	}

	return *response.Result, nil
}
1318295
func (client *Client) run(req *request, resp interface{}) (*http.Response, error) {
	if client.debug {
		log.Printf("Running OSS request: %#v", req)
	}

	hreq, err := client.setupHttpRequest(req)
	if err != nil {
		return nil, err
	}

	c := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (c net.Conn, err error) {
				if client.ConnectTimeout > 0 {
					c, err = net.DialTimeout(netw, addr, client.ConnectTimeout)
				} else {
					c, err = net.Dial(netw, addr)
				}
				if err != nil {
					return
				}
				return
			},
			Proxy: http.ProxyFromEnvironment,
		},
		Timeout: req.timeout,
	}

	return client.doHttpRequest(c, hreq, resp)
}
465836
func (c *Client) Run(run params.RunParams) ([]params.ActionResult, error) {
	var results params.ActionResults
	err := c.facade.FacadeCall("Run", run, &results)
	return results.Results, err
}