// sendRefused creates and sends a REFUSED response for request to w
// The returned error is logged with scopedLog and is returned for convenience
508201
func (p *DNSProxy) sendRefused(scopedLog *logrus.Entry, w dns.ResponseWriter, request *dns.Msg) (err error) {
	refused := new(dns.Msg)
	refused.SetRcode(request, p.rejectReply)

	if err = w.WriteMsg(refused); err != nil {
		scopedLog.WithError(err).Error("Cannot send REFUSED response")
		err = fmt.Errorf("cannot send REFUSED response: %s", err)
	}
	return err
}
882963
func (c *RPCClient) send(header *requestHeader, obj interface{}) error {
	c.writeLock.Lock()
	defer c.writeLock.Unlock()

	if c.shutdown {
		return clientClosed
	}

	// Setup an IO deadline, this way we won't wait indefinitely
	// if the client has hung.
	if err := c.conn.SetWriteDeadline(time.Now().Add(c.timeout)); err != nil {
		return err
	}

	if err := c.enc.Encode(header); err != nil {
		return err
	}

	if obj != nil {
		if err := c.enc.Encode(obj); err != nil {
			return err
		}
	}

	if err := c.writer.Flush(); err != nil {
		return err
	}

	return nil
}
924156
func (qs *queryResponseStream) sendResponse(from string, payload []byte) error {
	header := responseHeader{
		Seq:   qs.seq,
		Error: "",
	}
	rec := queryRecord{
		Type:    queryRecordResponse,
		From:    from,
		Payload: payload,
	}
	return qs.client.Send(&header, &rec)
}
1028201
func (f SenderFunc) Send(ctx context.Context, r Request) (mesos.Response, error) {
	return f(ctx, r)
}
970065
func SendPayload(reqCtx reqContext.Context, payload *common.Payload, orderers []fab.Orderer) (*common.Block, error) {
	if len(orderers) == 0 {
		return nil, errors.New("orderers not set")
	}

	ctx, ok := context.RequestClientContext(reqCtx)
	if !ok {
		return nil, errors.New("failed get client context from reqContext for signPayload")
	}
	envelope, err := signPayload(ctx, payload)
	if err != nil {
		return nil, err
	}

	// Copy aside the ordering service endpoints
	randOrderers := []fab.Orderer{}
	randOrderers = append(randOrderers, orderers...)

	// Iterate them in a random order and try broadcasting 1 by 1
	var errResp error
	for _, i := range rand.Perm(len(randOrderers)) {
		resp, err := sendEnvelope(reqCtx, envelope, randOrderers[i])
		if err != nil {
			errResp = err
		} else {
			return resp, nil
		}
	}
	return nil, errResp
}
629628
func (c *ResponseClient) SendResponse(req Request, response Response) error {
	raw, err := json.Marshal(response)
	if err != nil {
		return err
	}

	r, err := http.NewRequest("PUT", req.ResponseURL, bytes.NewReader(raw))
	if err != nil {
		return err
	}

	resp, err := c.client.Do(r)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if code := resp.StatusCode; code/100 != 2 {
		return fmt.Errorf("unexpected response from pre-signed url: %v: %v", code, string(body))
	}

	return nil
}
1242593
func (d *DNSProvider) sendRequest(method, resource string, payload interface{}, queryArgs map[string]string) (*http.Response, error) {
	url := fmt.Sprintf("%s/Services/REST/v1/%s", d.config.BaseURL, resource)

	body, err := json.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}

	req, err := http.NewRequest(method, url, bytes.NewReader(body))
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")
	if len(d.token) > 0 {
		req.Header.Set("Authorization", d.token)
	}

	// Add all query parameters
	q := req.URL.Query()
	for argName, argVal := range queryArgs {
		q.Add(argName, argVal)
	}
	req.URL.RawQuery = q.Encode()
	resp, err := d.config.HTTPClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("bluecat: %v", err)
	}

	if resp.StatusCode >= 400 {
		errBytes, _ := ioutil.ReadAll(resp.Body)
		errResp := string(errBytes)
		return nil, fmt.Errorf("bluecat: request failed with HTTP status code %d\n Full message: %s",
			resp.StatusCode, errResp)
	}

	return resp, nil
}
420715
func (oc *openShiftAPIClient) sendResource(path string, method string, reqBody interface{}) (map[string]interface{}, error) {
	url, err := oc.config.GetAPIURL()
	if err != nil {
		return nil, err
	}
	fullURL := strings.TrimSuffix(*url, "/") + path

	marshalled, err := json.Marshal(reqBody)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not marshal %s request", method)
		return nil, errs.WithStack(err)
	}

	req, err := http.NewRequest(method, fullURL, bytes.NewBuffer(marshalled))
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not create %s request", method)
		return nil, errs.WithStack(err)
	}

	token, err := oc.config.GetAPIToken()
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Bearer "+*token)

	resp, err := oc.httpClient.Do(req)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not perform %s request", method)
		return nil, errs.WithStack(err)
	}
	defer resp.Body.Close()

	buf := new(bytes.Buffer)
	_, err = buf.ReadFrom(resp.Body)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":          err,
			"url":          fullURL,
			"request_body": reqBody,
		}, "could not read response from %s request", method)
		return nil, errs.WithStack(err)
	}
	respBody := buf.Bytes()

	status := resp.StatusCode
	if status < http.StatusOK || status > http.StatusPartialContent {
		log.Error(nil, map[string]interface{}{
			"url":           fullURL,
			"request_body":  reqBody,
			"response_body": buf,
			"http_status":   status,
		}, "failed to %s request due to HTTP error", method)

		// If response contains a Kubernetes Status object, create a StatusError
		err = parseErrorFromStatus(respBody)
		if err != nil {
			return nil, convertError(errs.WithStack(err), "failed to %s url %s due to status code %d", method, fullURL, status)
		}
		return nil, errs.Errorf("failed to %s url %s: status code %d", method, fullURL, status)
	}

	var respJSON map[string]interface{}
	err = json.Unmarshal(respBody, &respJSON)
	if err != nil {
		log.Error(nil, map[string]interface{}{
			"err":           err,
			"url":           fullURL,
			"response_body": buf,
			"http_status":   status,
		}, "error unmarshalling JSON response")
		return nil, errs.WithStack(err)
	}
	return respJSON, nil
}
1100930
func (c *Client) Send(req *gomemcached.MCRequest) (rv *gomemcached.MCResponse, err error) {
	_, err = transmitRequest(c.conn, req)
	if err != nil {
		c.healthy = false
		return
	}
	resp, _, err := getResponse(c.conn, c.hdrBuf)
	c.healthy = !gomemcached.IsFatal(err)
	return resp, err
}
426878
func (c *Client) sendRequest(req request) (*jh.ResponseData, error) {
	request := jh.RequestData{
		ReqValue:   req.reqValue,
		ReqHeaders: req.reqHeader,
		ReqReader:  req.reqReader,
		ReqLength:  req.reqLength,
	}
	if req.expectedStatus == 0 {
		req.expectedStatus = http.StatusOK
	}
	respData := jh.ResponseData{
		RespValue:      req.resp,
		RespHeaders:    req.respHeader,
		ExpectedStatus: []int{req.expectedStatus},
	}
	err := c.client.SendRequest(req.method, req.url, "", &request, &respData)
	return &respData, err
}
277064
func (s *MockDeliverServer) DeliverFiltered(srv pb.Deliver_DeliverFilteredServer) error {
	if s.status != cb.Status_UNKNOWN {
		err1 := srv.Send(&pb.DeliverResponse{
			Type: &pb.DeliverResponse_Status{
				Status: s.status,
			},
		})
		return errors.Errorf("returning error status: %s %s", s.status, err1)
	}
	disconnect := make(chan bool)

	go s.handleFilteredEvents(srv, disconnect)
	for {
		envelope, err := srv.Recv()
		if err == io.EOF || envelope == nil {
			disconnect <- true
			break
		}

		err = s.disconnectErr()
		if err != nil {
			disconnect <- true
			return err
		}

		err1 := srv.Send(&pb.DeliverResponse{
			Type: &pb.DeliverResponse_FilteredBlock{
				FilteredBlock: &pb.FilteredBlock{},
			},
		})
		if err1 != nil {
			return err1
		}
		if err == io.EOF {
			test.Logf("*** mockdelserver err is io.EOF or envelope == nil, disconnecting from DeliverFiltered..")
			disconnect <- true
			break
		}
	}
	return nil
}
291983
func (e *endpoint) sendRaw(data buffer.VectorisedView, flags byte, seq, ack seqnum.Value, rcvWnd seqnum.Size) *tcpip.Error {
	var sackBlocks []header.SACKBlock
	if e.state == stateConnected && e.rcv.pendingBufSize > 0 && (flags&header.TCPFlagAck != 0) {
		sackBlocks = e.sack.Blocks[:e.sack.NumBlocks]
	}
	options := e.makeOptions(sackBlocks)
	err := sendTCP(&e.route, e.id, data, e.route.DefaultTTL(), flags, seq, ack, rcvWnd, options, e.gso)
	putOptions(options)
	return err
}
872022
func (api *Client) SendAuthRevokeContext(ctx context.Context, token string) (*AuthRevokeResponse, error) {
	if token == "" {
		token = api.token
	}
	values := url.Values{
		"token": {token},
	}

	return api.authRequest(ctx, "auth.revoke", values)
}
1075598
func (ds *streamBackend) SendSync(ctx context.Context, span *ssf.SSFSpan) error {
	if ds.conn == nil {
		if err := connect(ctx, ds); err != nil {
			return err
		}
	}
	_, err := protocol.WriteSSF(ds.output, span)
	if err != nil {
		if protocol.IsFramingError(err) {
			_ = ds.conn.Close()
			ds.conn = nil
		}
	}
	return err
}
407880
func (writer *messageWriter) SendRecord(payload []byte) error {
	select {
	case writer.payloadCh <- payload:
		return nil
	case <-writer.doneCh:
		return fmt.Errorf("messageWriter is done")
	}
}
430050
func sendResponse(w http.ResponseWriter, response interface{}, status int) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	marshalledResponse, err := json.Marshal(response)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(fmt.Sprintf("Failed to marshal response: %v %v", response, err)))
		return
	}
	w.WriteHeader(status)
	w.Write(marshalledResponse)
}
375730
func (c *rpcClient) SendRequest(ctx context.Context, addr string, req *tikvrpc.Request, timeout time.Duration) (*tikvrpc.Response, error) {
	start := time.Now()
	reqType := req.Type.String()
	storeID := strconv.FormatUint(req.Context.GetPeer().GetStoreId(), 10)
	defer func() {
		metrics.TiKVSendReqHistogram.WithLabelValues(reqType, storeID).Observe(time.Since(start).Seconds())
	}()

	connArray, err := c.getConnArray(addr)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if config.GetGlobalConfig().TiKVClient.MaxBatchSize > 0 {
		if batchReq := req.ToBatchCommandsRequest(); batchReq != nil {
			return sendBatchRequest(ctx, addr, connArray, batchReq, timeout)
		}
	}

	if req.IsDebugReq() {
		client := debugpb.NewDebugClient(connArray.Get())
		ctx1, cancel := context.WithTimeout(ctx, timeout)
		defer cancel()
		return tikvrpc.CallDebugRPC(ctx1, client, req)
	}

	client := tikvpb.NewTikvClient(connArray.Get())

	if req.Type != tikvrpc.CmdCopStream {
		ctx1, cancel := context.WithTimeout(ctx, timeout)
		defer cancel()
		return tikvrpc.CallRPC(ctx1, client, req)
	}

	// Coprocessor streaming request.
	// Use context to support timeout for grpc streaming client.
	ctx1, cancel := context.WithCancel(ctx)
	defer cancel()
	resp, err := tikvrpc.CallRPC(ctx1, client, req)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Put the lease object to the timeout channel, so it would be checked periodically.
	copStream := resp.CopStream
	copStream.Timeout = timeout
	copStream.Lease.Cancel = cancel
	connArray.streamTimeout <- &copStream.Lease

	// Read the first streaming response to get CopStreamResponse.
	// This can make error handling much easier, because SendReq() retry on
	// region error automatically.
	var first *coprocessor.Response
	first, err = copStream.Recv()
	if err != nil {
		if errors.Cause(err) != io.EOF {
			return nil, errors.Trace(err)
		}
		logutil.Logger(context.Background()).Debug("copstream returns nothing for the request.")
	}
	copStream.Response = first
	return resp, nil
}