logger = lagertest.NewTestLogger("test")
			transport = &roundtripperfakes.FakeRoundTripper{}
		})

		Context("backend", func() {
			BeforeEach(func() {
				endpoint := &route.Endpoint{
					Tags: map[string]string{},
				}

				endpointIterator.NextReturns(endpoint)

				var after round_tripper.AfterRoundTrip
				servingBackend := true
				proxyRoundTripper = round_tripper.NewProxyRoundTripper(
					servingBackend, transport, endpointIterator, logger, after)
			})

			Context("when backend is unavailable", func() {
				BeforeEach(func() {
					transport.RoundTripStub = func(req *http.Request) (*http.Response, error) {
						return nil, dialError
					}
				})

				It("retries 3 times", func() {
					resp.HeaderReturns(make(http.Header))
					_, err := proxyRoundTripper.RoundTrip(req)
					Expect(err).To(HaveOccurred())
					Expect(endpointIterator.NextCallCount()).To(Equal(3))
				})
Beispiel #2
0
func (p *proxy) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
	proxyWriter := responseWriter.(utils.ProxyResponseWriter)

	alr := proxyWriter.Context().Value("AccessLogRecord")
	if alr == nil {
		p.logger.Error("AccessLogRecord not set on context", errors.New("failed-to-access-LogRecord"))
	}
	accessLog := alr.(*schema.AccessLogRecord)

	handler := handler.NewRequestHandler(request, proxyWriter, p.reporter, accessLog, p.logger)

	if !isProtocolSupported(request) {
		handler.HandleUnsupportedProtocol()
		return
	}

	routePool := p.lookup(request)
	if routePool == nil {
		handler.HandleMissingRoute()
		return
	}

	stickyEndpointId := p.getStickySession(request)
	iter := &wrappedIterator{
		nested: routePool.Endpoints(p.defaultLoadBalance, stickyEndpointId),

		afterNext: func(endpoint *route.Endpoint) {
			if endpoint != nil {
				accessLog.RouteEndpoint = endpoint
				p.reporter.CaptureRoutingRequest(endpoint, request)
			}
		},
	}

	if isTcpUpgrade(request) {
		handler.HandleTcpRequest(iter)
		return
	}

	if isWebSocketUpgrade(request) {
		handler.HandleWebSocketRequest(iter)
		return
	}

	backend := true

	routeServiceUrl := routePool.RouteServiceUrl()
	// Attempted to use a route service when it is not supported
	if routeServiceUrl != "" && !p.routeServiceConfig.RouteServiceEnabled() {
		handler.HandleUnsupportedRouteService()
		return
	}

	var routeServiceArgs routeservice.RouteServiceRequest
	if routeServiceUrl != "" {
		rsSignature := request.Header.Get(routeservice.RouteServiceSignature)

		var recommendedScheme string

		if p.routeServiceRecommendHttps {
			recommendedScheme = "https"
		} else {
			recommendedScheme = "http"
		}

		forwardedUrlRaw := recommendedScheme + "://" + hostWithoutPort(request) + request.RequestURI
		if hasBeenToRouteService(routeServiceUrl, rsSignature) {
			// A request from a route service destined for a backend instances
			routeServiceArgs.URLString = routeServiceUrl
			err := p.routeServiceConfig.ValidateSignature(&request.Header, forwardedUrlRaw)
			if err != nil {
				handler.HandleBadSignature(err)
				return
			}
		} else {
			var err error
			// should not hardcode http, will be addressed by #100982038
			routeServiceArgs, err = p.routeServiceConfig.Request(routeServiceUrl, forwardedUrlRaw)
			backend = false
			if err != nil {
				handler.HandleRouteServiceFailure(err)
				return
			}
		}
	}

	after := func(rsp *http.Response, endpoint *route.Endpoint, err error) {
		if endpoint == nil {
			handler.HandleBadGateway(err, request)
			return
		}

		accessLog.FirstByteAt = time.Now()
		if rsp != nil {
			accessLog.StatusCode = rsp.StatusCode
		}

		if p.traceKey != "" && endpoint != nil && request.Header.Get(router_http.VcapTraceHeader) == p.traceKey {
			router_http.SetTraceHeaders(responseWriter, p.ip, endpoint.CanonicalAddr())
		}

		latency := time.Since(accessLog.StartedAt)

		if backend {
			p.reporter.CaptureRoutingResponse(endpoint, rsp, accessLog.StartedAt, latency)
		} else {
			p.reporter.CaptureRouteServiceResponse(endpoint, rsp, accessLog.StartedAt, latency)
		}

		if err != nil {
			handler.HandleBadGateway(err, request)
			return
		}

		if endpoint.PrivateInstanceId != "" {
			setupStickySession(responseWriter, rsp, endpoint, stickyEndpointId, p.secureCookies, routePool.ContextPath())
		}

		// if Content-Type not in response, nil out to suppress Go's auto-detect
		if _, ok := rsp.Header["Content-Type"]; !ok {
			responseWriter.Header()["Content-Type"] = nil
		}
	}

	roundTripper := round_tripper.NewProxyRoundTripper(backend,
		dropsonde.InstrumentedRoundTripper(p.transport), iter, handler.Logger(), after)

	newReverseProxy(roundTripper, request, routeServiceArgs, p.routeServiceConfig, p.forceForwardedProtoHttps).ServeHTTP(proxyWriter, request)
}