public async Task Invoke(HttpContext context) { var qosProvider = _qosProviderHouse.Get(DownstreamRoute.ReRoute); if (qosProvider.IsError) { _logger.LogDebug("IQosProviderHouse returned an error, setting pipeline error"); SetPipelineError(qosProvider.Errors); return; } var buildResult = await _requestCreator.Build( DownstreamRequest, DownstreamRoute.ReRoute.IsQos, qosProvider.Data, DownstreamRoute.ReRoute.HttpHandlerOptions.UseCookieContainer, DownstreamRoute.ReRoute.HttpHandlerOptions.AllowAutoRedirect, DownstreamRoute.ReRoute.ReRouteKey, DownstreamRoute.ReRoute.HttpHandlerOptions.UseTracing); if (buildResult.IsError) { _logger.LogDebug("IRequestCreator returned an error, setting pipeline error"); SetPipelineError(buildResult.Errors); return; } _logger.LogDebug("setting upstream request"); SetUpstreamRequestForThisRequest(buildResult.Data); await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling query string builder middleware"); if (DownstreamRoute.ReRoute.ClaimsToQueries.Any()) { _logger.LogDebug("this route has instructions to convert claims to queries"); var response = _addQueriesToRequest.SetQueriesOnContext(DownstreamRoute.ReRoute.ClaimsToQueries, context); if (response.IsError) { _logger.LogDebug("there was an error setting queries on context, setting pipeline error"); SetPipelineError(response.Errors); return; } } _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling request builder middleware"); var buildResult = await _requestCreator .Build(context.Request.Method, DownstreamUrl, context.Request.Body, context.Request.Headers, context.Request.Cookies, context.Request.QueryString, context.Request.ContentType, new RequestId.RequestId(DownstreamRoute?.ReRoute?.RequestIdKey, context.TraceIdentifier)); if (buildResult.IsError) { _logger.LogDebug("IRequestCreator returned an error, setting pipeline error"); SetPipelineError(buildResult.Errors); return; } _logger.LogDebug("setting upstream request"); SetUpstreamRequestForThisRequest(buildResult.Data); _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started error responder middleware"); await _next.Invoke(context); _logger.LogDebug("calling next middleware"); if (PipelineError) { _logger.LogDebug("there is a pipeline error, getting errors"); var errors = PipelineErrors; _logger.LogDebug("received errors setting error response"); SetErrorResponse(context, errors); } else { _logger.LogDebug("no pipeline error, setting response"); await _responder.SetResponseOnHttpContext(context, HttpResponseMessage); } }
private IClusterClient ConnectClient(string serviceName, IClusterClient client) { int attempt = 0; while (true) { try { client.Connect().Wait(); _logger.LogDebug($"Connection {serviceName} Sucess..."); return(client); } catch (Exception ex) { _logger.LogError($"Connection {serviceName} Faile...", ex); attempt++; if (attempt <= this._options.InitializeAttemptsBeforeFailing) { _logger.LogDebug($"Attempt {attempt} of " + this._options.InitializeAttemptsBeforeFailing + " failed to initialize the Orleans client."); Task.Delay(TimeSpan.FromSeconds(4)).Wait(); continue; } throw new OrleansConnectionFailedException($"Connection {serviceName} Faile..."); } } }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started claims middleware"); if (DownstreamRoute.ReRoute.ClaimsToClaims.Any()) { _logger.LogDebug("this route has instructions to convert claims to other claims"); var result = _addClaimsToRequest.SetClaimsOnContext(DownstreamRoute.ReRoute.ClaimsToClaims, context); if (result.IsError) { _logger.LogDebug("error converting claims to other claims, setting pipeline error"); SetPipelineError(result.Errors); return; } } _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(DownstreamContext context) { if (IsAuthenticatedRoute(context.DownstreamReRoute)) { _logger.LogDebug($"{context.HttpContext.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated"); var result = await context.HttpContext.AuthenticateAsync(context.DownstreamReRoute.AuthenticationOptions.AuthenticationProviderKey); context.HttpContext.User = result.Principal; if (context.HttpContext.User.Identity.IsAuthenticated) { _logger.LogDebug($"Client has been authenticated for {context.HttpContext.Request.Path}"); await _next.Invoke(context); } else { var error = new List <Error> { new UnauthenticatedError( $"Request for authenticated route {context.HttpContext.Request.Path} by {context.HttpContext.User.Identity.Name} was unauthenticated") }; _logger.LogError($"Client has NOT been authenticated for {context.HttpContext.Request.Path} and pipeline error set. {error.ToErrorString()}"); SetPipelineError(context, error); } } else { _logger.LogTrace($"No authentication needed for {context.HttpContext.Request.Path}"); await _next.Invoke(context); } }
public PollyQoSProvider(ReRoute reRoute, IOcelotLoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger <PollyQoSProvider>(); _timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(reRoute.QosOptionsOptions.TimeoutValue), reRoute.QosOptionsOptions.TimeoutStrategy); _circuitBreakerPolicy = Policy .Handle <HttpRequestException>() .Or <TimeoutRejectedException>() .Or <TimeoutException>() .CircuitBreakerAsync( exceptionsAllowedBeforeBreaking: reRoute.QosOptionsOptions.ExceptionsAllowedBeforeBreaking, durationOfBreak: TimeSpan.FromMilliseconds(reRoute.QosOptionsOptions.DurationOfBreak), onBreak: (ex, breakDelay) => { _logger.LogError( ".Breaker logging: Breaking the circuit for " + breakDelay.TotalMilliseconds + "ms!", ex); }, onReset: () => { _logger.LogDebug(".Breaker logging: Call ok! Closed the circuit again."); }, onHalfOpen: () => { _logger.LogDebug(".Breaker logging: Half-open; next call is a trial."); } ); _circuitBreaker = new CircuitBreaker(_circuitBreakerPolicy, _timeoutPolicy); }
public async Task Invoke(DownstreamContext context) { var dsPath = _replacer .Replace(context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues); if (dsPath.IsError) { _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error"); SetPipelineError(context, dsPath.Errors); return; } UriBuilder uriBuilder; if (ServiceFabricRequest(context)) { uriBuilder = CreateServiceFabricUri(context, dsPath); } else { uriBuilder = new UriBuilder(context.DownstreamRequest.RequestUri) { Path = dsPath.Data.Value, Scheme = context.DownstreamReRoute.DownstreamScheme }; } context.DownstreamRequest.RequestUri = uriBuilder.Uri; _logger.LogDebug("downstream url is {downstreamUrl.Data.Value}", context.DownstreamRequest.RequestUri); await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { _logger.TraceMiddlewareEntry(); var upstreamUrlPath = context.Request.Path.ToString().SetLastCharacterAs('/'); _logger.LogDebug("upstream url path is {upstreamUrlPath}", upstreamUrlPath); var downstreamRoute = await _downstreamRouteFinder.FindDownstreamRoute(upstreamUrlPath, context.Request.Method); if (downstreamRoute.IsError) { _logger.LogError($"{MiddlwareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}"); SetPipelineError(downstreamRoute.Errors); _logger.TraceMiddlewareCompleted(); return; } _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamPathTemplate); SetDownstreamRouteForThisRequest(downstreamRoute.Data); _logger.TraceInvokeNext(); await _next.Invoke(context); _logger.TraceInvokeNextCompleted(); _logger.TraceMiddlewareCompleted(); }
public async Task Invoke(HttpContext context) { var upstreamUrlPath = context.Request.Path.ToString(); //todo make this getting config its own middleware one day? var configuration = await _configProvider.Get(); if (configuration.IsError) { _logger.LogError($"{MiddlewareName} setting pipeline errors. IOcelotConfigurationProvider returned {configuration.Errors.ToErrorString()}"); SetPipelineError(configuration.Errors); } SetServiceProviderConfigurationForThisRequest(configuration.Data.ServiceProviderConfiguration); _logger.LogDebug("upstream url path is {upstreamUrlPath}", upstreamUrlPath); var downstreamRoute = _downstreamRouteFinder.FindDownstreamRoute(upstreamUrlPath, context.Request.Method, configuration.Data); if (downstreamRoute.IsError) { _logger.LogError($"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}"); SetPipelineError(downstreamRoute.Errors); return; } _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamPathTemplate); SetDownstreamRouteForThisRequest(downstreamRoute.Data); await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { var dsPath = _replacer .Replace(DownstreamRoute.ReRoute.DownstreamPathTemplate, DownstreamRoute.TemplatePlaceholderNameAndValues); if (dsPath.IsError) { _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error"); SetPipelineError(dsPath.Errors); return; } var uriBuilder = new UriBuilder(DownstreamRequest.RequestUri) { Path = dsPath.Data.Value, Scheme = DownstreamRoute.ReRoute.DownstreamScheme }; DownstreamRequest.RequestUri = uriBuilder.Uri; _logger.LogDebug("downstream url is {downstreamUrl.Data.Value}", DownstreamRequest.RequestUri); await _next.Invoke(context); }
public async Task Invoke(DownstreamContext context) { var dsPath = _replacer .Replace(context.DownstreamReRoute.DownstreamPathTemplate, context.TemplatePlaceholderNameAndValues); if (dsPath.IsError) { _logger.LogDebug("IDownstreamPathPlaceholderReplacer returned an error, setting pipeline error"); SetPipelineError(context, dsPath.Errors); return; } context.DownstreamRequest.Scheme = context.DownstreamReRoute.DownstreamScheme; if (ServiceFabricRequest(context)) { var pathAndQuery = CreateServiceFabricUri(context, dsPath); context.DownstreamRequest.AbsolutePath = pathAndQuery.path; context.DownstreamRequest.Query = pathAndQuery.query; } else { context.DownstreamRequest.AbsolutePath = dsPath.Data.Value; } _logger.LogDebug("downstream url is {context.DownstreamRequest}", context.DownstreamRequest); await _next.Invoke(context); }
public async Task Invoke(DownstreamContext context) { var options = context.DownstreamReRoute.RateLimitOptions; // check if rate limiting is enabled if (!context.DownstreamReRoute.EnableEndpointEndpointRateLimiting) { _logger.LogDebug($"EndpointRateLimiting is not enabled for {context.DownstreamReRoute.DownstreamPathTemplate}"); await _next.Invoke(context); return; } // compute identity from request var identity = SetIdentity(context.HttpContext, options); // check white list if (IsWhitelisted(identity, options)) { _logger.LogDebug($"{context.DownstreamReRoute.DownstreamPathTemplate} is white listed from rate limiting"); await _next.Invoke(context); return; } var rule = options.RateLimitRule; if (rule.Limit > 0) { // increment counter var counter = _processor.ProcessRequest(identity, options); // check if limit is reached if (counter.TotalRequests > rule.Limit) { //compute retry after value var retryAfter = _processor.RetryAfterFrom(counter.Timestamp, rule); // log blocked request LogBlockedRequest(context.HttpContext, identity, counter, rule, context.DownstreamReRoute); var retrystring = retryAfter.ToString(System.Globalization.CultureInfo.InvariantCulture); // break execution await ReturnQuotaExceededResponse(context.HttpContext, options, retrystring); return; } } //set X-Rate-Limit headers for the longest period if (!options.DisableRateLimitHeaders) { var headers = _processor.GetRateLimitHeaders(context.HttpContext, identity, options); context.HttpContext.Response.OnStarting(SetRateLimitHeaders, state: headers); } await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { _logger.TraceMiddlewareEntry(); if (IsAuthenticatedRoute(DownstreamRoute.ReRoute)) { _logger.LogDebug($"{context.Request.Path} is an authenticated route. {MiddlwareName} checking if client is authenticated"); var authenticationHandler = _authHandlerFactory.Get(_app, DownstreamRoute.ReRoute.AuthenticationOptions); if (authenticationHandler.IsError) { _logger.LogError($"Error getting authentication handler for {context.Request.Path}. {authenticationHandler.Errors.ToErrorString()}"); SetPipelineError(authenticationHandler.Errors); _logger.TraceMiddlewareCompleted(); return; } await authenticationHandler.Data.Handler.Handle(context); if (context.User.Identity.IsAuthenticated) { _logger.LogDebug($"Client has been authenticated for {context.Request.Path}"); _logger.TraceInvokeNext(); await _next.Invoke(context); _logger.TraceInvokeNextCompleted(); _logger.TraceMiddlewareCompleted(); } else { var error = new List <Error> { new UnauthenticatedError( $"Request for authenticated route {context.Request.Path} by {context.User.Identity.Name} was unauthenticated") }; _logger.LogError($"Client has NOT been authenticated for {context.Request.Path} and pipeline error set. {error.ToErrorString()}"); SetPipelineError(error); _logger.TraceMiddlewareCompleted(); return; } } else { _logger.LogTrace($"No authentication needed for {context.Request.Path}"); _logger.TraceInvokeNext(); await _next.Invoke(context); _logger.TraceInvokeNextCompleted(); _logger.TraceMiddlewareCompleted(); } }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling RateLimit middleware"); var options = DownstreamRoute.ReRoute.RateLimitOptions; // check if rate limiting is enabled if (!DownstreamRoute.ReRoute.EnableEndpointRateLimiting) { await _next.Invoke(context); return; } // compute identity from request var identity = SetIdentity(context, options); // check white list if (IsWhitelisted(identity, options)) { await _next.Invoke(context); return; } var rule = options.RateLimitRule; if (rule.Limit > 0) { // increment counter var counter = _processor.ProcessRequest(identity, options); // check if limit is reached if (counter.TotalRequests > rule.Limit) { //compute retry after value var retryAfter = _processor.RetryAfterFrom(counter.Timestamp, rule); // log blocked request LogBlockedRequest(context, identity, counter, rule); // break execution await ReturnQuotaExceededResponse(context, options, retryAfter); return; } } //set X-Rate-Limit headers for the longest period if (!options.DisableRateLimitHeaders) { var headers = _processor.GetRateLimitHeaders(context, identity, options); context.Response.OnStarting(SetRateLimitHeaders, state: headers); } await _next.Invoke(context); }
public async Task <IActionResult> AppendEntries() { using (var reader = new StreamReader(HttpContext.Request.Body)) { var json = await reader.ReadToEndAsync(); var appendEntries = JsonConvert.DeserializeObject <AppendEntries>(json, _jsonSerialiserSettings); _logger.LogDebug($"{_baseSchemeUrlAndPort}/appendentries called, my state is {_node.State.GetType().FullName}"); var appendEntriesResponse = _node.Handle(appendEntries); return(new OkObjectResult(appendEntriesResponse)); } }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling request id middleware"); SetOcelotRequestId(context); _logger.LogDebug("set request id"); _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(DownstreamContext context) { var response = await _requester.GetResponseAsync(context); if (response.IsError) { _logger.LogDebug("IHttpRequester returned an error, setting pipeline error"); SetPipelineError(context, response.Errors); return; } _logger.LogDebug("setting http response message"); context.DownstreamResponse = response.Data; }
public async Task Invoke(HttpContext context) { var response = await _requester.GetResponse(Request); if (response.IsError) { _logger.LogDebug("IHttpRequester returned an error, setting pipeline error"); SetPipelineError(response.Errors); return; } _logger.LogDebug("setting http response message"); SetHttpResponseMessageThisRequest(response.Data); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling load balancing middleware"); var loadBalancer = _loadBalancerHouse.Get(DownstreamRoute.ReRoute.ReRouteKey); if (loadBalancer.IsError) { SetPipelineError(loadBalancer.Errors); return; } var hostAndPort = await loadBalancer.Data.Lease(); if (hostAndPort.IsError) { SetPipelineError(hostAndPort.Errors); return; } var uriBuilder = new UriBuilder(DownstreamRequest.RequestUri); uriBuilder.Host = hostAndPort.Data.DownstreamHost; if (hostAndPort.Data.DownstreamPort > 0) { uriBuilder.Port = hostAndPort.Data.DownstreamPort; } DownstreamRequest.RequestUri = uriBuilder.Uri; _logger.LogDebug("calling next middleware"); try { await _next.Invoke(context); loadBalancer.Data.Release(hostAndPort.Data); } catch (Exception) { loadBalancer.Data.Release(hostAndPort.Data); _logger.LogDebug("error calling next middleware, exception will be thrown to global handler"); throw; } _logger.LogDebug("succesfully called next middleware"); }
private string GetCacheKey(DownstreamContext request) { var cacheKey = $"{request.DownstreamRequest.Method}:{request.DownstreamRequest.OriginalString}"; _logger.LogDebug($"Cache key for request is {cacheKey}"); return(cacheKey); }
public async Task Invoke(DownstreamContext context) { var loadBalancer = await _loadBalancerHouse.Get(context.DownstreamReRoute, context.ServiceProviderConfiguration); if (loadBalancer.IsError) { _logger.LogDebug("there was an error retriving the loadbalancer, setting pipeline error"); SetPipelineError(context, loadBalancer.Errors); return; } var hostAndPort = await loadBalancer.Data.Lease(); if (hostAndPort.IsError) { _logger.LogDebug("there was an error leasing the loadbalancer, setting pipeline error"); SetPipelineError(context, hostAndPort.Errors); return; } var uriBuilder = new UriBuilder(context.DownstreamRequest.RequestUri); uriBuilder.Host = hostAndPort.Data.DownstreamHost; if (hostAndPort.Data.DownstreamPort > 0) { uriBuilder.Port = hostAndPort.Data.DownstreamPort; } context.DownstreamRequest.RequestUri = uriBuilder.Uri; try { await _next.Invoke(context); } catch (Exception) { _logger.LogDebug("Exception calling next middleware, exception will be thrown to global handler"); throw; } finally { loadBalancer.Data.Release(hostAndPort.Data); } }
public async Task Invoke(DownstreamContext context) { if (context.DownstreamReRoute.ClaimsToClaims.Any()) { _logger.LogDebug("this route has instructions to convert claims to other claims"); var result = _addClaimsToRequest.SetClaimsOnContext(context.DownstreamReRoute.ClaimsToClaims, context.HttpContext); if (result.IsError) { _logger.LogDebug("error converting claims to other claims, setting pipeline error"); SetPipelineError(context, result.Errors); return; } } await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { if (DownstreamRoute.ReRoute.ClaimsToQueries.Any()) { _logger.LogDebug($"{DownstreamRoute.ReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to queries"); var response = _addQueriesToRequest.SetQueriesOnDownstreamRequest(DownstreamRoute.ReRoute.ClaimsToQueries, context.User.Claims, DownstreamRequest); if (response.IsError) { _logger.LogDebug("there was an error setting queries on context, setting pipeline error"); SetPipelineError(response.Errors); return; } } await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling request builder middleware"); var downstreamRequest = await _requestMapper.Map(context.Request); if (downstreamRequest.IsError) { SetPipelineError(downstreamRequest.Errors); return; } SetDownstreamRequest(downstreamRequest.Data); _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(DownstreamContext context) { if (context.DownstreamReRoute.ClaimsToHeaders.Any()) { _logger.LogDebug($"{ context.DownstreamReRoute.DownstreamPathTemplate.Value} has instructions to convert claims to headers"); var response = _addHeadersToRequest.SetHeadersOnDownstreamRequest(context.DownstreamReRoute.ClaimsToHeaders, context.HttpContext.User.Claims, context.DownstreamRequest); if (response.IsError) { _logger.LogDebug("Error setting headers on context, setting pipeline error"); SetPipelineError(context, response.Errors); return; } _logger.LogDebug("headers have been set on context"); } await _next.Invoke(context); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling headers builder middleware"); if (DownstreamRoute.ReRoute.ClaimsToHeaders.Any()) { _logger.LogDebug("this route has instructions to convert claims to headers"); var response = _addHeadersToRequest.SetHeadersOnDownstreamRequest(DownstreamRoute.ReRoute.ClaimsToHeaders, context.User.Claims, DownstreamRequest); if (response.IsError) { _logger.LogDebug("there was an error setting headers on context, setting pipeline error"); SetPipelineError(response.Errors); return; } _logger.LogDebug("headers have been set on context"); } _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
public async Task Invoke(HttpContext context) { _logger.LogDebug("started calling downstream route finder middleware"); var upstreamUrlPath = context.Request.Path.ToString().SetLastCharacterAs('/'); _logger.LogDebug("upstream url path is {upstreamUrlPath}", upstreamUrlPath); var downstreamRoute = _downstreamRouteFinder.FindDownstreamRoute(upstreamUrlPath, context.Request.Method); if (downstreamRoute.IsError) { _logger.LogDebug("IDownstreamRouteFinder returned an error, setting pipeline error"); SetPipelineError(downstreamRoute.Errors); return; } _logger.LogDebug("downstream template is {downstreamRoute.Data.ReRoute.DownstreamPath}", downstreamRoute.Data.ReRoute.DownstreamPathTemplate); SetDownstreamRouteForThisRequest(downstreamRoute.Data); _logger.LogDebug("calling next middleware"); await _next.Invoke(context); _logger.LogDebug("succesfully called next middleware"); }
private async Task Poll() { _logger.LogDebug("Started polling consul"); var fileConfig = await _repo.Get(); if(fileConfig.IsError) { _logger.LogDebug($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}"); return; } var asJson = ToJson(fileConfig.Data); if(!fileConfig.IsError && asJson != _previousAsJson) { await _setter.Set(fileConfig.Data); _previousAsJson = asJson; } _logger.LogDebug("Finished polling consul"); }