// HandleRequest implements rpc.Recorder.
495480
func (cr *combinedRecorder) HandleRequest(hdr *rpc.Header, body interface{}) error {
	cr.observer.ServerRequest(hdr, body)
	if cr.recorder == nil {
		return nil
	}
	var args string
	if cr.captureArgs {
		jsonArgs, err := json.Marshal(body)
		if err != nil {
			return errors.Trace(err)
		}
		args = string(jsonArgs)
	}
	return errors.Trace(cr.recorder.AddRequest(auditlog.RequestArgs{
		RequestID: hdr.RequestId,
		Facade:    hdr.Request.Type,
		Method:    hdr.Request.Action,
		Version:   hdr.Request.Version,
		Args:      args,
	}))
}
1146430
func LogRequest(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var start time.Time
		if zerolog.GlobalLevel() <= zerolog.DebugLevel {
			start = time.Now()
		}
		h.ServeHTTP(w, r)
		if zerolog.GlobalLevel() <= zerolog.DebugLevel {
			addr := r.Header.Get("X-Real-IP")
			if addr == "" {
				addr = r.Header.Get("X-Forwarded-For")
				if addr == "" {
					addr = r.RemoteAddr
				}
			}
			log.Debug().Str("method", r.Method).Str("path", r.URL.Path).Str("addr", addr).Dur("duration", time.Since(start)).Msgf("http request")
		}
		return
	})
}
284087
func (i *AgentIPC) handleRequest(client *IPCClient, reqHeader *requestHeader) error {
	// Look for a command field
	command := reqHeader.Command
	seq := reqHeader.Seq

	// Ensure the handshake is performed before other commands
	if command != handshakeCommand && client.version == 0 {
		respHeader := responseHeader{Seq: seq, Error: handshakeRequired}
		client.Send(&respHeader, nil)
		return fmt.Errorf(handshakeRequired)
	}
	metrics.IncrCounter([]string{"agent", "ipc", "command"}, 1)

	// Ensure the client has authenticated after the handshake if necessary
	if i.authKey != "" && !client.didAuth && command != authCommand && command != handshakeCommand {
		i.logger.Printf("[WARN] agent.ipc: Client sending commands before auth")
		respHeader := responseHeader{Seq: seq, Error: authRequired}
		client.Send(&respHeader, nil)
		return nil
	}

	// Dispatch command specific handlers
	switch command {
	case handshakeCommand:
		return i.handleHandshake(client, seq)

	case authCommand:
		return i.handleAuth(client, seq)

	case eventCommand:
		return i.handleEvent(client, seq)

	case membersCommand, membersFilteredCommand:
		return i.handleMembers(client, command, seq)

	case streamCommand:
		return i.handleStream(client, seq)

	case monitorCommand:
		return i.handleMonitor(client, seq)

	case stopCommand:
		return i.handleStop(client, seq)

	case forceLeaveCommand:
		return i.handleForceLeave(client, seq)

	case joinCommand:
		return i.handleJoin(client, seq)

	case leaveCommand:
		return i.handleLeave(client, seq)

	case installKeyCommand:
		return i.handleInstallKey(client, seq)

	case useKeyCommand:
		return i.handleUseKey(client, seq)

	case removeKeyCommand:
		return i.handleRemoveKey(client, seq)

	case listKeysCommand:
		return i.handleListKeys(client, seq)

	case tagsCommand:
		return i.handleTags(client, seq)

	case queryCommand:
		return i.handleQuery(client, seq)

	case respondCommand:
		return i.handleRespond(client, seq)

	case statsCommand:
		return i.handleStats(client, seq)

	case getCoordinateCommand:
		return i.handleGetCoordinate(client, seq)

	default:
		respHeader := responseHeader{Seq: seq, Error: unsupportedCommand}
		client.Send(&respHeader, nil)
		return fmt.Errorf("command '%s' not recognized", command)
	}
}
524084
func (s *Server) handleRequest(req *Request, conn conn) error {
	ctx := context.Background()

	// Resolve the address if we have a FQDN
	dest := req.DestAddr
	if dest.FQDN != "" {
		ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
		if err != nil {
			if err := sendReply(conn, hostUnreachable, nil); err != nil {
				return fmt.Errorf("Failed to send reply: %v", err)
			}
			return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err)
		}
		ctx = ctx_
		dest.IP = addr
	}

	// Apply any address rewrites
	req.realDestAddr = req.DestAddr
	if s.config.Rewriter != nil {
		ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
	}

	// Switch on the command
	switch req.Command {
	case ConnectCommand:
		return s.handleConnect(ctx, conn, req)
	case BindCommand:
		return s.handleBind(ctx, conn, req)
	case AssociateCommand:
		return s.handleAssociate(ctx, conn, req)
	default:
		if err := sendReply(conn, commandNotSupported, nil); err != nil {
			return fmt.Errorf("Failed to send reply: %v", err)
		}
		return fmt.Errorf("Unsupported command: %v", req.Command)
	}
}
160625
func (p *Prometheus) HandlerFunc() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.URL.String() == p.MetricsPath {
			c.Next()
			return
		}

		start := time.Now()
		reqSz := computeApproximateRequestSize(c.Request)

		c.Next()

		status := strconv.Itoa(c.Writer.Status())
		elapsed := float64(time.Since(start)) / float64(time.Second)
		resSz := float64(c.Writer.Size())

		p.reqDur.Observe(elapsed)
		url := p.ReqCntURLLabelMappingFn(c)
		// jlambert Oct 2018 - sidecar specific mod
		if len(p.URLLabelFromContext) > 0 {
			u, found := c.Get(p.URLLabelFromContext)
			if !found {
				u = "unknown"
			}
			url = u.(string)
		}
		p.reqCnt.WithLabelValues(status, c.Request.Method, c.HandlerName(), c.Request.Host, url).Inc()
		p.reqSz.Observe(float64(reqSz))
		p.resSz.Observe(resSz)
	}
}
1312692
func (rs *RequestServer) nextRequest(r *Request) string {
	rs.openRequestLock.Lock()
	defer rs.openRequestLock.Unlock()
	rs.handleCount++
	handle := strconv.Itoa(rs.handleCount)
	r.handle = handle
	rs.openRequests[handle] = r
	return handle
}
1059654
func DecodeRequest(r *http.Request, v interface{}, ignoreEOF bool) error {
	if err := json.NewDecoder(r.Body).Decode(v); err != nil {
		if err == io.EOF && ignoreEOF {
			return nil
		}
		return fmt.Errorf("error decoding request body: %v", err)
	}
	return nil
}
235780
func (c *Core) HandleRequest(httpCtx context.Context, req *logical.Request) (resp *logical.Response, err error) {
	return c.switchedLockHandleRequest(httpCtx, req, true)
}
89076
func HttpRequestHandler(requestHeader RequestHeader, requestBody interface{}, responseDTO interface{}) (*http.Response, apihelper.ApiErrors) {
	req, err := http.NewRequest(requestHeader.Method, requestHeader.URL, encodeRequestBody(requestBody))
	req.Header.Set("Content-Type", requestHeader.ContentType)
	req.Header.Set("Authorization", requestHeader.Authorization)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}

	// read response
	body, _ := ioutil.ReadAll(resp.Body)

	var apiErrors apihelper.ApiErrors
	json.Unmarshal(body, &responseDTO)
	json.Unmarshal(body, &apiErrors)

	if len(apiErrors.Errors) > 0 {
		pretty.Println(apiErrors.Errors)
	}

	return resp, apiErrors
}
1230761
func (a *auditLogFile) AddRequest(m Request) error {
	return errors.Trace(a.addRecord(Record{Request: &m}))

}
21785
func (c *RPCClient) handleSeq(seq uint64, handler seqHandler) {
	c.dispatchLock.Lock()
	defer c.dispatchLock.Unlock()
	c.dispatch[seq] = handler
}
1069112
func (m *Mux) UseRequest(fn c.HandlerFunc) *Mux {
	m.Middleware.UseRequest(fn)
	return m
}
44085
func makeRequest(client *http.Client, req *http.Request) {
	// Make the request
	resp, err := client.Do(req)
	if err == nil {
		defer resp.Body.Close()
		resp.Close = true
	} else {
		LoggingClient.Error(err.Error())
	}
}
200958
func handleRequestForwarding(core *vault.Core, handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// If we are a performance standby we can handle the request.
		if core.PerfStandby() {
			ns, err := namespace.FromContext(r.Context())
			if err != nil {
				respondError(w, http.StatusBadRequest, err)
				return
			}
			path := ns.TrimmedPath(r.URL.Path[len("/v1/"):])
			switch {
			case !perfStandbyAlwaysForwardPaths.HasPath(path):
				handler.ServeHTTP(w, r)
				return
			case strings.HasPrefix(path, "auth/token/create/"):
				isBatch, err := core.IsBatchTokenCreationRequest(r.Context(), path)
				if err == nil && isBatch {
					handler.ServeHTTP(w, r)
					return
				}
			}
		}

		// Note: in an HA setup, this call will also ensure that connections to
		// the leader are set up, as that happens once the advertised cluster
		// values are read during this function
		isLeader, leaderAddr, _, err := core.Leader()
		if err != nil {
			if err == vault.ErrHANotEnabled {
				// Standalone node, serve request normally
				handler.ServeHTTP(w, r)
				return
			}
			// Some internal error occurred
			respondError(w, http.StatusInternalServerError, err)
			return
		}
		if isLeader {
			// No forwarding needed, we're leader
			handler.ServeHTTP(w, r)
			return
		}
		if leaderAddr == "" {
			respondError(w, http.StatusInternalServerError, fmt.Errorf("local node not active but active cluster node not found"))
			return
		}

		forwardRequest(core, w, r)
		return
	})
}
1247899
func (h *HandlerShared) handleFileSystemRequest(ctx context.Context, req *jsonrpc2.Request) (lsp.DocumentURI, bool, error) {
	span := opentracing.SpanFromContext(ctx)
	h.Mu.Lock()
	overlay := h.overlay
	h.Mu.Unlock()

	do := func(uri lsp.DocumentURI, op func() error) (lsp.DocumentURI, bool, error) {
		span.SetTag("uri", uri)
		before, beforeErr := h.readFile(ctx, uri)
		if beforeErr != nil && !os.IsNotExist(beforeErr) {
			// There is no op that could succeed in this case. (Most
			// commonly occurs when uri refers to a dir, not a file.)
			return uri, false, beforeErr
		}
		err := op()
		after, afterErr := h.readFile(ctx, uri)
		if os.IsNotExist(beforeErr) && os.IsNotExist(afterErr) {
			// File did not exist before or after so nothing has changed.
			return uri, false, err
		} else if afterErr != nil || beforeErr != nil {
			// If an error prevented us from reading the file
			// before or after then we assume the file changed to
			// be conservative.
			return uri, true, err
		}
		return uri, !bytes.Equal(before, after), err
	}

	switch req.Method {
	case "textDocument/didOpen":
		var params lsp.DidOpenTextDocumentParams
		if err := json.Unmarshal(*req.Params, &params); err != nil {
			return "", false, err
		}
		return do(params.TextDocument.URI, func() error {
			overlay.didOpen(&params)
			return nil
		})

	case "textDocument/didChange":
		var params lsp.DidChangeTextDocumentParams
		if err := json.Unmarshal(*req.Params, &params); err != nil {
			return "", false, err
		}
		return do(params.TextDocument.URI, func() error {
			return overlay.didChange(&params)
		})

	case "textDocument/didClose":
		var params lsp.DidCloseTextDocumentParams
		if err := json.Unmarshal(*req.Params, &params); err != nil {
			return "", false, err
		}
		return do(params.TextDocument.URI, func() error {
			overlay.didClose(&params)
			return nil
		})

	case "textDocument/didSave":
		var params lsp.DidSaveTextDocumentParams
		if err := json.Unmarshal(*req.Params, &params); err != nil {
			return "", false, err
		}
		// no-op
		return params.TextDocument.URI, false, nil

	default:
		panic("unexpected file system request method: " + req.Method)
	}
}
803687
func (k *Kite) handleLog(r *Request) (interface{}, error) {
	msg, err := r.Args.One().String()
	if err != nil {
		return nil, err
	}

	k.Log.Info("%s: %s", r.Client.Name, msg)

	return nil, nil
}
695801
func (s *Server) HandleRequestStream(ctx context.Context, stream Stream, defaultTypeURL string) error {
	// increment stream count
	streamID := atomic.AddUint64(&s.lastStreamID, 1)

	streamLog := log.WithField(logfields.XDSStreamID, streamID)

	reqCh := make(chan *envoy_api_v2.DiscoveryRequest)

	stopRecv := make(chan struct{})
	defer close(stopRecv)

	go func() {
		defer close(reqCh)
		for {
			req, err := stream.Recv()
			if err != nil {
				if err == io.EOF {
					streamLog.Debug("xDS stream closed")
				} else {
					streamLog.WithError(err).Error("error while receiving request from xDS stream")
				}
				return
			}
			if req == nil {
				streamLog.Error("received nil request from xDS stream; stopping xDS stream handling")
				return
			}
			if req.GetTypeUrl() == "" {
				req.TypeUrl = defaultTypeURL
			}
			streamLog.WithFields(getXDSRequestFields(req)).Debug("received request from xDS stream")
			select {
			case <-stopRecv:
				streamLog.Debug("stopping xDS stream handling")
				return
			case reqCh <- req:
			}
		}
	}()

	return s.processRequestStream(ctx, streamLog, stream, reqCh, defaultTypeURL)
}