private ReRoute SetUpAggregateReRoute(List <ReRoute> reRoutes, FileAggregateReRoute aggregateReRoute, FileGlobalConfiguration globalConfiguration) { var applicableReRoutes = reRoutes .SelectMany(x => x.DownstreamReRoute) .Where(r => aggregateReRoute.ReRouteKeys.Contains(r.Key)) .ToList(); if (applicableReRoutes.Count != aggregateReRoute.ReRouteKeys.Count) { //todo - log or throw or return error whatever? } //make another re route out of these var upstreamTemplatePattern = _upstreamTemplatePatternCreator.Create(aggregateReRoute); var reRoute = new ReRouteBuilder() .WithUpstreamPathTemplate(aggregateReRoute.UpstreamPathTemplate) .WithUpstreamHttpMethod(aggregateReRoute.UpstreamHttpMethod) .WithUpstreamTemplatePattern(upstreamTemplatePattern) .WithDownstreamReRoutes(applicableReRoutes) .WithUpstreamHost(aggregateReRoute.UpstreamHost) .WithAggregator(aggregateReRoute.Aggregator) .Build(); return(reRoute); }
/// <summary> /// 从数据库中获取配置信息 /// </summary> /// <returns></returns> public async Task <Response <FileConfiguration> > Get() { #region 提取配置信息 var file = new FileConfiguration(); //提取默认启用的路由配置信息 string glbsql = "select * from GlobalConfiguration where IsDefault=1 and InfoStatus=1"; //提取全局配置信息 using (var connection = new SqlConnection(_option.DbConnectionStrings)) { var result = await connection.QueryFirstOrDefaultAsync <GlobalConfiguration>(glbsql); if (result != null) { var glb = new FileGlobalConfiguration(); //赋值全局信息 glb.BaseUrl = result.BaseUrl; glb.DownstreamScheme = result.DownstreamScheme; glb.RequestIdKey = result.RequestIdKey; if (!result.HttpHandlerOptions.IsNullOrEmpty()) { glb.HttpHandlerOptions = result.HttpHandlerOptions.ToObject <FileHttpHandlerOptions>(); } if (!result.LoadBalancerOptions.IsNullOrEmpty()) { glb.LoadBalancerOptions = result.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!result.QoSOptions.IsNullOrEmpty()) { glb.QoSOptions = result.QoSOptions.ToObject <FileQoSOptions>(); } if (!result.ServiceDiscoveryProvider.IsNullOrEmpty()) { glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider.ToObject <FileServiceDiscoveryProvider>(); } file.GlobalConfiguration = glb; //提取所有路由信息 string routesql = "select T2.* from ConfigReRoutes T1 inner join ReRoute T2 on T1.ReRouteId=T2.ReRouteId where KeyId=@KeyId and InfoStatus=1"; var routeresult = (await connection.QueryAsync <ReRoute>(routesql, new { result.KeyId }))?.AsList(); if (routeresult != null && routeresult.Count > 0) { var reroutelist = new List <FileReRoute>(); foreach (var model in routeresult) { var m = new FileReRoute(); if (!model.AuthenticationOptions.IsNullOrEmpty()) { m.AuthenticationOptions = model.AuthenticationOptions.ToObject <FileAuthenticationOptions>(); } if (!model.CacheOptions.IsNullOrEmpty()) { m.FileCacheOptions = model.CacheOptions.ToObject <FileCacheOptions>(); } if (!model.DelegatingHandlers.IsNullOrEmpty()) { m.DelegatingHandlers = model.DelegatingHandlers.ToObject <List <string> >(); } if (!model.LoadBalancerOptions.IsNullOrEmpty()) { m.LoadBalancerOptions = model.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!model.QoSOptions.IsNullOrEmpty()) { m.QoSOptions = model.QoSOptions.ToObject <FileQoSOptions>(); } if (!model.DownstreamHostAndPorts.IsNullOrEmpty()) { m.DownstreamHostAndPorts = model.DownstreamHostAndPorts.ToObject <List <FileHostAndPort> >(); } //开始赋值 m.DownstreamPathTemplate = model.DownstreamPathTemplate; m.DownstreamScheme = model.DownstreamScheme; m.Key = model.RequestIdKey; m.Priority = model.Priority ?? 0; m.RequestIdKey = model.RequestIdKey; m.ServiceName = model.ServiceName; m.UpstreamHost = model.UpstreamHost; m.UpstreamHttpMethod = model.UpstreamHttpMethod?.ToObject <List <string> >(); m.UpstreamPathTemplate = model.UpstreamPathTemplate; reroutelist.Add(m); } file.ReRoutes = reroutelist; } } else { throw new Exception("未监测到任何可用的配置信息"); } } #endregion if (file.ReRoutes == null || file.ReRoutes.Count == 0) { return(new OkResponse <FileConfiguration>(null)); } return(new OkResponse <FileConfiguration>(file)); }
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration fileGlobalConfig) { _globalConfig = fileGlobalConfig; }
public Task <Response <FileConfiguration> > Get() { var fileConfiguration = new FileConfiguration(); var configModel = _userDatabaseContext.OcelotConfigs .Where(x => x.IsEnable == true) .Include(x => x.GlobalConfiguration).FirstOrDefault(); if (configModel != null) { //全局配置 var guid = configModel.Id; //var routes = _userDatabaseContext.Routes.Where(x => x.OcelotConfigGuid == guid) // .Include(x => x.LoadBalancerOption) // .Include(x => x.DownstreamPathTemplate) // .Include(x => x.AuthenticationOptions).ToList(); var routes = _userDatabaseContext.Routes.Where(x => x.OcelotConfigGuid == guid).ToList(); configModel.Routes = routes; var fileGlobalConfiguration = new FileGlobalConfiguration(); fileGlobalConfiguration.BaseUrl = configModel.GlobalConfiguration.BaseUrl; fileConfiguration.GlobalConfiguration = fileGlobalConfiguration; var routelist = new List <FileRoute>(); foreach (var item in routes) { item.LoadBalancerOption = _userDatabaseContext.LoadBalancerOptions.FirstOrDefault(x => x.RoutesGuid == item.Id); item.AuthenticationOptions = _userDatabaseContext.AuthenticationOptions.FirstOrDefault(x => x.RoutesGuid == item.Id); item.DownstreamHostAndPorts = _userDatabaseContext.DownstreamHostAndPorts.Where(x => x.RoutesGuid == item.Id).ToList(); var m = new FileRoute(); m.DownstreamPathTemplate = item.DownstreamPathTemplate; m.DownstreamScheme = item.DownstreamScheme; m.UpstreamPathTemplate = item.UpstreamPathTemplate; m.UpstreamHttpMethod.AddRange(item.UpstreamHttpMethods.Select(x => x.Method)); m.RouteIsCaseSensitive = item.RouteIsCaseSensitive; m.LoadBalancerOptions = new FileLoadBalancerOptions { Type = item.LoadBalancerOption.Type }; m.AuthenticationOptions = new FileAuthenticationOptions { AuthenticationProviderKey = item.AuthenticationOptions.AuthenticationProviderKey, AllowedScopes = new List <string> { } }; var list = new List <FileHostAndPort>(); foreach (var hostItem in item.DownstreamHostAndPorts) { list.Add(new FileHostAndPort { Host = hostItem.Host, Port = hostItem.Port }); } m.DownstreamHostAndPorts = list; routelist.Add(m); } fileConfiguration.Routes = routelist; } else { throw new Exception("未监测到任何可用的配置信息"); } if (fileConfiguration.Routes == null || fileConfiguration.Routes.Count == 0) { return(Task.FromResult <Response <FileConfiguration> >(new OkResponse <FileConfiguration>(null))); } return(Task.FromResult <Response <FileConfiguration> >(new OkResponse <FileConfiguration>(fileConfiguration))); }
public async Task <FileConfiguration> GetFileConfiguration(string name) { var file = new FileConfiguration(); // 提取全局配置信息 var globalResult = await _ocelotGlobalConfigurationRepository.FindByNameAsync(name); if (globalResult != null) { var fileGlobalConfig = new FileGlobalConfiguration { BaseUrl = globalResult.BaseUrl, DownstreamScheme = globalResult.DownstreamScheme, RequestIdKey = globalResult.RequestIdKey }; if (globalResult.HttpHandlerOption != null) { var httpHandlerOption = globalResult.HttpHandlerOption; fileGlobalConfig.HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = httpHandlerOption.AllowAutoRedirect, UseCookieContainer = httpHandlerOption.UseCookieContainer, UseProxy = httpHandlerOption.UseProxy, UseTracing = httpHandlerOption.UseTracing, MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer }; } if (globalResult.LoadBalancerOption != null) { var loadBalancerOption = globalResult.LoadBalancerOption; fileGlobalConfig.LoadBalancerOptions = new FileLoadBalancerOptions { Expiry = loadBalancerOption.Expiry, Key = loadBalancerOption.Key, Type = loadBalancerOption.Type }; } if (globalResult.QoSOption != null) { var qoSOption = globalResult.QoSOption; fileGlobalConfig.QoSOptions = new FileQoSOptions { ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking, DurationOfBreak = qoSOption.DurationOfBreak, TimeoutValue = qoSOption.TimeoutValue }; } if (globalResult.ServiceDiscoveryProvider != null) { var serviceDiscoveryProvider = globalResult.ServiceDiscoveryProvider; fileGlobalConfig.ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { ConfigurationKey = serviceDiscoveryProvider.ConfigurationKey, Host = serviceDiscoveryProvider.Host, Namespace = serviceDiscoveryProvider.Namespace, PollingInterval = serviceDiscoveryProvider.PollingInterval, Port = serviceDiscoveryProvider.Port, Token = serviceDiscoveryProvider.Token, Type = serviceDiscoveryProvider.Type }; } if (globalResult.RateLimitOption != null) { var rateLimitOption = globalResult.RateLimitOption; fileGlobalConfig.RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = rateLimitOption.ClientIdHeader, DisableRateLimitHeaders = rateLimitOption.DisableRateLimitHeaders, HttpStatusCode = rateLimitOption.HttpStatusCode, QuotaExceededMessage = rateLimitOption.QuotaExceededMessage, RateLimitCounterPrefix = rateLimitOption.RateLimitCounterPrefix }; } file.GlobalConfiguration = fileGlobalConfig; //TODO: Optimize code structure if (globalResult?.Routes?.Count > 0) { _logger.LogInformation($"Route Count:{ globalResult?.Routes?.Count }"); //提取路由信息 var Routes = globalResult.Routes.OrderBy(c => c.Sort); List <FileRoute> fileRoutes = new List <FileRoute>(); foreach (var route in Routes) { _logger.LogInformation($"Loading Route: {route.Name}"); var r = new FileRoute { Key = route.Key, Priority = route.Priority, ServiceName = route.ServiceName, Timeout = route.Timeout, DownstreamPathTemplate = route.DownstreamPathTemplate, DownstreamScheme = route.DownstreamScheme, UpstreamHost = route.UpstreamHost, DangerousAcceptAnyServerCertificateValidator = route.DangerousAcceptAnyServerCertificateValidator, DownstreamHttpMethod = route.DownstreamHttpMethod, RequestIdKey = route.RequestIdKey, UpstreamPathTemplate = route.UpstreamPathTemplate, ServiceNamespace = route.ServiceNamespace, RouteIsCaseSensitive = route.RouteIsCaseSensitive, AddClaimsToRequest = route.AddClaimsToRequests, AddHeadersToRequest = route.AddHeadersToRequests, AddQueriesToRequest = route.AddQueriesToRequests, ChangeDownstreamPathTemplate = route.ChangeDownstreamPathTemplates, DownstreamHeaderTransform = route.DownstreamHeaderTransforms, RouteClaimsRequirement = route.RouteClaimsRequirements, UpstreamHeaderTransform = route.UpstreamHeaderTransforms, // AuthenticationOptions = null, // DelegatingHandlers = null, // DownstreamHostAndPorts = null, // FileCacheOptions = null, // HttpHandlerOptions = null, // LoadBalancerOptions = null, // QoSOptions = null, // RateLimitOptions = null, // SecurityOptions = null, // UpstreamHttpMethod = null }; if (route.AuthenticationOption != null) { var authenticationOption = route.AuthenticationOption; r.AuthenticationOptions = new FileAuthenticationOptions { AuthenticationProviderKey = authenticationOption.AuthenticationProviderKey, AllowedScopes = authenticationOption.AllowedScopes.Select(c => c.Scope).ToList() }; } if (route.DelegatingHandlers != null && route.DelegatingHandlers.Count > 0) { r.DelegatingHandlers = route.DelegatingHandlers.Select(c => c.Delegating).ToList(); } if (route.DownstreamHostAndPorts != null && route.DownstreamHostAndPorts.Count > 0) { var downstreamHostAndPorts = new List <FileHostAndPort>(); foreach (var host in route.DownstreamHostAndPorts) { downstreamHostAndPorts.Add(new FileHostAndPort { Host = host.Host, Port = host.Port }); } r.DownstreamHostAndPorts = downstreamHostAndPorts; } if (route.CacheOption != null) { var cacheOption = route.CacheOption; r.FileCacheOptions = new FileCacheOptions { TtlSeconds = cacheOption.TtlSeconds, Region = cacheOption.Region }; } if (route.HttpHandlerOption != null) { var httpHandlerOption = route.HttpHandlerOption; r.HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = httpHandlerOption.AllowAutoRedirect, UseCookieContainer = httpHandlerOption.UseCookieContainer, UseProxy = httpHandlerOption.UseProxy, UseTracing = httpHandlerOption.UseTracing, MaxConnectionsPerServer = httpHandlerOption.MaxConnectionsPerServer }; } if (route.LoadBalancerOption != null) { var loadBalancerOptions = route.LoadBalancerOption; r.LoadBalancerOptions = new FileLoadBalancerOptions { Expiry = loadBalancerOptions.Expiry, Key = loadBalancerOptions.Key, Type = loadBalancerOptions.Type }; } if (route.QoSOption != null) { var qoSOption = route.QoSOption; r.QoSOptions = new FileQoSOptions { ExceptionsAllowedBeforeBreaking = qoSOption.ExceptionsAllowedBeforeBreaking, DurationOfBreak = qoSOption.DurationOfBreak, TimeoutValue = qoSOption.TimeoutValue }; } if (route.RateLimitOption != null) { var rateLimitOption = route.RateLimitOption; r.RateLimitOptions = new FileRateLimitRule { ClientWhitelist = rateLimitOption.ClientWhitelist.Select(c => c.Whitelist).ToList(), EnableRateLimiting = rateLimitOption.EnableRateLimiting, Limit = rateLimitOption.Limit, Period = rateLimitOption.Period, PeriodTimespan = rateLimitOption.PeriodTimespan }; } if (route.SecurityOption != null) { var securityOption = route.SecurityOption; r.SecurityOptions = new FileSecurityOptions { IPAllowedList = securityOption.IPAllowedList.Select(c => c.IP).ToList(), IPBlockedList = securityOption.IPBlockedList.Select(c => c.IP).ToList() }; } if (route.UpstreamHttpMethods != null) { r.UpstreamHttpMethod = route.UpstreamHttpMethods.Select(c => c.Method).ToList(); } r.UpstreamPathTemplate = route.UpstreamPathTemplate; file.Routes.Add(r); } } else { _logger.LogWarning($"Not Found Route"); } } else { throw new Exception(string.Format("Not found '{0}' gateway name config", name)); } return(file); }
private async Task <ReRoute> SetUpReRoute(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { var fileReRouteOptions = _fileReRouteOptionsCreator.Create(fileReRoute); var requestIdKey = _requestIdKeyCreator.Create(fileReRoute, globalConfiguration); var reRouteKey = CreateReRouteKey(fileReRoute); var upstreamTemplatePattern = _upstreamTemplatePatternCreator.Create(fileReRoute); var serviceProviderConfiguration = _serviceProviderConfigCreator.Create(fileReRoute, globalConfiguration); var authOptionsForRoute = _authOptionsCreator.Create(fileReRoute); var claimsToHeaders = _claimsToThingCreator.Create(fileReRoute.AddHeadersToRequest); var claimsToClaims = _claimsToThingCreator.Create(fileReRoute.AddClaimsToRequest); var claimsToQueries = _claimsToThingCreator.Create(fileReRoute.AddQueriesToRequest); var qosOptions = _qosOptionsCreator.Create(fileReRoute); var rateLimitOption = _rateLimitOptionsCreator.Create(fileReRoute, globalConfiguration, fileReRouteOptions.EnableRateLimiting); var region = _regionCreator.Create(fileReRoute); var httpHandlerOptions = _httpHandlerOptionsCreator.Create(fileReRoute); var reRoute = new ReRouteBuilder() .WithDownstreamPathTemplate(fileReRoute.DownstreamPathTemplate) .WithUpstreamPathTemplate(fileReRoute.UpstreamPathTemplate) .WithUpstreamHttpMethod(fileReRoute.UpstreamHttpMethod) .WithUpstreamTemplatePattern(upstreamTemplatePattern) .WithIsAuthenticated(fileReRouteOptions.IsAuthenticated) .WithAuthenticationOptions(authOptionsForRoute) .WithClaimsToHeaders(claimsToHeaders) .WithClaimsToClaims(claimsToClaims) .WithRouteClaimsRequirement(fileReRoute.RouteClaimsRequirement) .WithIsAuthorised(fileReRouteOptions.IsAuthorised) .WithClaimsToQueries(claimsToQueries) .WithRequestIdKey(requestIdKey) .WithIsCached(fileReRouteOptions.IsCached) .WithCacheOptions(new CacheOptions(fileReRoute.FileCacheOptions.TtlSeconds, region)) .WithDownstreamScheme(fileReRoute.DownstreamScheme) .WithLoadBalancer(fileReRoute.LoadBalancer) .WithDownstreamHost(fileReRoute.DownstreamHost) .WithDownstreamPort(fileReRoute.DownstreamPort) .WithLoadBalancerKey(reRouteKey) .WithServiceProviderConfiguraion(serviceProviderConfiguration) .WithIsQos(fileReRouteOptions.IsQos) .WithQosOptions(qosOptions) .WithEnableRateLimiting(fileReRouteOptions.EnableRateLimiting) .WithRateLimitOptions(rateLimitOption) .WithHttpHandlerOptions(httpHandlerOptions) .Build(); await SetupLoadBalancer(reRoute); SetupQosProvider(reRoute); return(reRoute); }
public async Task <Response <FileConfiguration> > Get() { using (var scope = _serviceProvider.CreateScope()) { var _configDbRepository = scope.ServiceProvider.GetRequiredService <IDbRepository <ConfigurationInfo> >(); var _routeDbRepository = scope.ServiceProvider.GetRequiredService <IDbRepository <ReRouteInfo> >(); var st = DateTime.Now; var fileConfig = new FileConfiguration(); var configInfo = await _configDbRepository.GetFirstAsync(it => it.GatewayKey == _apiGatewayKey); if (configInfo != null) { // config var fgc = new FileGlobalConfiguration { BaseUrl = configInfo.BaseUrl, DownstreamScheme = configInfo.DownstreamScheme, RequestIdKey = configInfo.RequestIdKey, }; if (!string.IsNullOrWhiteSpace(configInfo.HttpHandlerOptions)) { fgc.HttpHandlerOptions = ToObject <FileHttpHandlerOptions>(configInfo.HttpHandlerOptions); } if (!string.IsNullOrWhiteSpace(configInfo.LoadBalancerOptions)) { fgc.LoadBalancerOptions = ToObject <FileLoadBalancerOptions>(configInfo.LoadBalancerOptions); } if (!string.IsNullOrWhiteSpace(configInfo.QoSOptions)) { fgc.QoSOptions = ToObject <FileQoSOptions>(configInfo.QoSOptions); } if (!string.IsNullOrWhiteSpace(configInfo.RateLimitOptions)) { fgc.RateLimitOptions = ToObject <FileRateLimitOptions>(configInfo.RateLimitOptions); } if (!string.IsNullOrWhiteSpace(configInfo.ServiceDiscoveryProvider)) { fgc.ServiceDiscoveryProvider = ToObject <FileServiceDiscoveryProvider>(configInfo.ServiceDiscoveryProvider); } fileConfig.GlobalConfiguration = fgc; // reroutes var reRouteResult = await _routeDbRepository.GetListAsync(it => it.GatewayId == configInfo.GatewayId && it.State == 1); if (reRouteResult.Count > 0) { var reroutelist = new List <FileReRoute>(); foreach (var model in reRouteResult) { var m = new FileReRoute() { UpstreamHost = model.UpstreamHost, UpstreamPathTemplate = model.UpstreamPathTemplate, DownstreamPathTemplate = model.DownstreamPathTemplate, DownstreamScheme = model.DownstreamScheme, ServiceName = model.ServiceName, Priority = model.Priority, RequestIdKey = model.RequestIdKey, Key = model.Key, Timeout = model.Timeout, }; if (!string.IsNullOrWhiteSpace(model.UpstreamHttpMethod)) { m.UpstreamHttpMethod = ToObject <List <string> >(model.UpstreamHttpMethod); } if (!string.IsNullOrWhiteSpace(model.DownstreamHostAndPorts)) { m.DownstreamHostAndPorts = ToObject <List <FileHostAndPort> >(model.DownstreamHostAndPorts); } if (!string.IsNullOrWhiteSpace(model.SecurityOptions)) { m.SecurityOptions = ToObject <FileSecurityOptions>(model.SecurityOptions); } if (!string.IsNullOrWhiteSpace(model.CacheOptions)) { m.FileCacheOptions = ToObject <FileCacheOptions>(model.CacheOptions); } if (!string.IsNullOrWhiteSpace(model.HttpHandlerOptions)) { m.HttpHandlerOptions = ToObject <FileHttpHandlerOptions>(model.HttpHandlerOptions); } if (!string.IsNullOrWhiteSpace(model.AuthenticationOptions)) { m.AuthenticationOptions = ToObject <FileAuthenticationOptions>(model.AuthenticationOptions); } if (!string.IsNullOrWhiteSpace(model.RateLimitOptions)) { m.RateLimitOptions = ToObject <FileRateLimitRule>(model.RateLimitOptions); } if (!string.IsNullOrWhiteSpace(model.LoadBalancerOptions)) { m.LoadBalancerOptions = ToObject <FileLoadBalancerOptions>(model.LoadBalancerOptions); } if (!string.IsNullOrWhiteSpace(model.QoSOptions)) { m.QoSOptions = ToObject <FileQoSOptions>(model.QoSOptions); } if (!string.IsNullOrWhiteSpace(model.DelegatingHandlers)) { m.DelegatingHandlers = ToObject <List <string> >(model.DelegatingHandlers); } reroutelist.Add(m); } fileConfig.ReRoutes = reroutelist; } } // Console.WriteLine((DateTime.Now - st).TotalMilliseconds); return(new OkResponse <FileConfiguration>(fileConfig)); } }
/// <summary> /// 提取配置信息 /// </summary> /// <returns></returns> public async Task <Response <FileConfiguration> > Get() { var config = _cache.Get(_option.CachePrefix + "FileConfiguration", ""); if (config != null) { return(new OkResponse <FileConfiguration>(config)); } #region 提取配置信息 var file = new FileConfiguration(); string glbsql = "select top 1 * from OcelotGlobalConfiguration where IsDefault=1"; //提取全局配置信息 using (var connection = new SqlConnection(_option.DbConnectionStrings)) { var result = await connection.QueryFirstOrDefaultAsync <OcelotGlobalConfiguration>(glbsql); if (result != null) { var glb = new FileGlobalConfiguration(); glb.BaseUrl = result.BaseUrl; glb.DownstreamScheme = result.DownstreamScheme; glb.RequestIdKey = result.RequestIdKey; if (!String.IsNullOrEmpty(result.HttpHandlerOptions)) { glb.HttpHandlerOptions = result.HttpHandlerOptions.ToObject <FileHttpHandlerOptions>(); } if (!String.IsNullOrEmpty(result.LoadBalancerOptions)) { glb.LoadBalancerOptions = result.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!String.IsNullOrEmpty(result.QoSOptions)) { glb.QoSOptions = result.QoSOptions.ToObject <FileQoSOptions>(); } if (!String.IsNullOrEmpty(result.ServiceDiscoveryProvider)) { glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider.ToObject <FileServiceDiscoveryProvider>(); } file.GlobalConfiguration = glb; //提取路由信息 string routesql = "select * from OcelotReRoutes where OcelotGlobalConfigurationId=@OcelotGlobalConfigurationId and IsStatus=1"; var routeresult = (await connection.QueryAsync <OcelotReRoutes>(routesql, new { OcelotGlobalConfigurationId = result.Id })).AsList(); if (routeresult != null && routeresult.Count > 0) { var reroutelist = new List <FileReRoute>(); foreach (var model in routeresult) { var m = new FileReRoute(); if (!String.IsNullOrEmpty(model.AuthenticationOptions)) { m.AuthenticationOptions = model.AuthenticationOptions.ToObject <FileAuthenticationOptions>(); } if (!String.IsNullOrEmpty(model.CacheOptions)) { m.FileCacheOptions = model.CacheOptions.ToObject <FileCacheOptions>(); } if (!String.IsNullOrEmpty(model.DelegatingHandlers)) { m.DelegatingHandlers = model.DelegatingHandlers.ToObject <List <string> >(); } if (!String.IsNullOrEmpty(model.LoadBalancerOptions)) { m.LoadBalancerOptions = model.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!String.IsNullOrEmpty(model.QoSOptions)) { m.QoSOptions = model.QoSOptions.ToObject <FileQoSOptions>(); } if (!String.IsNullOrEmpty(model.DownstreamHostAndPorts)) { m.DownstreamHostAndPorts = model.DownstreamHostAndPorts.ToObject <List <FileHostAndPort> >(); } //开始赋值 m.DownstreamPathTemplate = model.DownstreamPathTemplate; m.DownstreamScheme = model.DownstreamScheme; m.Key = model.Key; m.Priority = model.Priority ?? 0; m.RequestIdKey = model.RequestIdKey; m.ServiceName = model.ServiceName; m.Timeout = model.Timeout ?? 0; m.UpstreamHost = model.UpstreamHost; if (!String.IsNullOrEmpty(model.UpstreamHttpMethod)) { m.UpstreamHttpMethod = model.UpstreamHttpMethod.ToObject <List <string> >(); } m.UpstreamPathTemplate = model.UpstreamPathTemplate; reroutelist.Add(m); } file.ReRoutes = reroutelist; } } else { throw new Exception("未监测到配置信息"); } } #endregion if (file.ReRoutes == null || file.ReRoutes.Count == 0) { return(new OkResponse <FileConfiguration>(null)); } return(new OkResponse <FileConfiguration>(file)); }
public async Task <Response <FileConfiguration> > Get() { var _gatewayDbContext = _serviceProvider.CreateScope().ServiceProvider.GetRequiredService <GatewayDbContext>(); var dbGlobalConfig = _gatewayDbContext.GlobalConfiguration.Where(x => x.Enable).FirstOrDefault(); if (dbGlobalConfig == null) { throw new Exception("未监测到任何可用的配置信息"); } if (string.IsNullOrEmpty(dbGlobalConfig.BaseUrl)) { throw new Exception("BaseUrl不可为空"); } // Globalconfig var fileConfiguration = new FileConfiguration(); var fileGlobalConfiguration = new FileGlobalConfiguration(); fileGlobalConfiguration.BaseUrl = dbGlobalConfig.BaseUrl; fileGlobalConfiguration.DownstreamScheme = dbGlobalConfig.DownstreamScheme; fileGlobalConfiguration.RequestIdKey = dbGlobalConfig.RequestIdKey; fileGlobalConfiguration.DownstreamHttpVersion = dbGlobalConfig.DownstreamHttpVersion; if (!string.IsNullOrEmpty(dbGlobalConfig.HttpHandlerOptions)) { fileGlobalConfiguration.HttpHandlerOptions = JsonConvert.DeserializeObject <FileHttpHandlerOptions>(dbGlobalConfig.HttpHandlerOptions); } if (!string.IsNullOrEmpty(dbGlobalConfig.LoadBalancerOptions)) { fileGlobalConfiguration.LoadBalancerOptions = JsonConvert.DeserializeObject <FileLoadBalancerOptions>(dbGlobalConfig.LoadBalancerOptions); } if (!string.IsNullOrEmpty(dbGlobalConfig.QoSOptions)) { fileGlobalConfiguration.QoSOptions = JsonConvert.DeserializeObject <FileQoSOptions>(dbGlobalConfig.QoSOptions); } if (!string.IsNullOrEmpty(dbGlobalConfig.ServiceDiscoveryProvider)) { fileGlobalConfiguration.ServiceDiscoveryProvider = JsonConvert.DeserializeObject <FileServiceDiscoveryProvider>(dbGlobalConfig.ServiceDiscoveryProvider); } if (!string.IsNullOrEmpty(dbGlobalConfig.RateLimitOptions)) { fileGlobalConfiguration.RateLimitOptions = JsonConvert.DeserializeObject <FileRateLimitOptions>(dbGlobalConfig.RateLimitOptions); } fileConfiguration.GlobalConfiguration = fileGlobalConfiguration; var routeresult = dbGlobalConfig.ReRoutes; if (routeresult == null || routeresult.Count <= 0) { return(await Task.FromResult(new OkResponse <FileConfiguration>(null))); } // Reroutes var reroutelist = new List <FileReRoute>(); foreach (var model in routeresult) { var fileReroute = new FileReRoute(); if (!string.IsNullOrEmpty(model.AuthenticationOptions)) { fileReroute.AuthenticationOptions = JsonConvert.DeserializeObject <FileAuthenticationOptions>(model.AuthenticationOptions); } if (!string.IsNullOrEmpty(model.FileCacheOptions)) { fileReroute.FileCacheOptions = JsonConvert.DeserializeObject <FileCacheOptions>(model.FileCacheOptions); } if (!string.IsNullOrEmpty(model.DelegatingHandlers)) { fileReroute.DelegatingHandlers = JsonConvert.DeserializeObject <List <string> >(model.DelegatingHandlers); } if (!string.IsNullOrEmpty(model.LoadBalancerOptions)) { fileReroute.LoadBalancerOptions = JsonConvert.DeserializeObject <FileLoadBalancerOptions>(model.LoadBalancerOptions); } if (!string.IsNullOrEmpty(model.QoSOptions)) { fileReroute.QoSOptions = JsonConvert.DeserializeObject <FileQoSOptions>(model.QoSOptions); } if (!string.IsNullOrEmpty(model.DownstreamHostAndPorts)) { fileReroute.DownstreamHostAndPorts = JsonConvert.DeserializeObject <List <FileHostAndPort> >(model.DownstreamHostAndPorts); } if (!string.IsNullOrEmpty(model.HttpHandlerOptions)) { fileReroute.HttpHandlerOptions = JsonConvert.DeserializeObject <FileHttpHandlerOptions>(model.HttpHandlerOptions); } if (!string.IsNullOrEmpty(model.RateLimitOptions)) { fileReroute.RateLimitOptions = JsonConvert.DeserializeObject <FileRateLimitRule>(model.RateLimitOptions); } fileReroute.DownstreamPathTemplate = model.DownstreamPathTemplate; fileReroute.DownstreamScheme = model.DownstreamScheme; fileReroute.Key = model.Key ?? ""; fileReroute.Priority = model.Priority; fileReroute.RequestIdKey = model.RequestIdKey ?? ""; fileReroute.ServiceName = model.ServiceName ?? ""; fileReroute.UpstreamHost = model.UpstreamHost ?? ""; fileReroute.UpstreamHttpMethod = JsonConvert.DeserializeObject <List <string> >(model.UpstreamHttpMethod); fileReroute.UpstreamPathTemplate = model.UpstreamPathTemplate; fileReroute.DownstreamHttpVersion = model.DownstreamHttpVersion; reroutelist.Add(fileReroute); } fileConfiguration.ReRoutes = reroutelist; // Aggregates var dbAggregates = _gatewayDbContext.Aggregates.Where(x => x.Enable); foreach (var aggregate in dbAggregates) { var fileAggregate = new FileAggregateReRoute(); if (!string.IsNullOrEmpty(aggregate.ReRouteKeys)) { fileAggregate.ReRouteKeys = JsonConvert.DeserializeObject <List <string> >(aggregate.ReRouteKeys); } if (!string.IsNullOrEmpty(aggregate.ReRouteKeysConfig)) { fileAggregate.ReRouteKeysConfig = JsonConvert.DeserializeObject <List <AggregateReRouteConfig> >(aggregate.ReRouteKeysConfig); } fileAggregate.UpstreamPathTemplate = aggregate.UpstreamPathTemplate; fileAggregate.UpstreamHost = aggregate.UpstreamHost; fileAggregate.ReRouteIsCaseSensitive = aggregate.ReRouteIsCaseSensitive; fileAggregate.Aggregator = aggregate.Aggregator; fileAggregate.Priority = aggregate.Priority; fileConfiguration.Aggregates.Add(fileAggregate); } if (fileConfiguration.ReRoutes == null || fileConfiguration.ReRoutes.Count <= 0) { return(await Task.FromResult(new OkResponse <FileConfiguration>(null))); } return(await Task.FromResult(new OkResponse <FileConfiguration>(fileConfiguration))); }
private ServiceProviderConfiguraion BuildServiceProviderConfiguration(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { var useServiceDiscovery = !string.IsNullOrEmpty(fileReRoute.ServiceName) && !string.IsNullOrEmpty(globalConfiguration?.ServiceDiscoveryProvider?.Provider); var serviceProviderPort = globalConfiguration?.ServiceDiscoveryProvider?.Port ?? 0; return(new ServiceProviderConfiguraionBuilder() .WithServiceName(fileReRoute.ServiceName) .WithDownstreamHost(fileReRoute.DownstreamHost) .WithDownstreamPort(fileReRoute.DownstreamPort) .WithUseServiceDiscovery(useServiceDiscovery) .WithServiceDiscoveryProvider(globalConfiguration?.ServiceDiscoveryProvider?.Provider) .WithServiceDiscoveryProviderHost(globalConfiguration?.ServiceDiscoveryProvider?.Host) .WithServiceDiscoveryProviderPort(serviceProviderPort) .Build()); }
private async Task <ReRoute> SetUpReRoute(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { var isAuthenticated = IsAuthenticated(fileReRoute); var isAuthorised = IsAuthorised(fileReRoute); var isCached = IsCached(fileReRoute); var requestIdKey = BuildRequestId(fileReRoute, globalConfiguration); var reRouteKey = BuildReRouteKey(fileReRoute); var upstreamTemplatePattern = BuildUpstreamTemplatePattern(fileReRoute); var isQos = IsQoS(fileReRoute); var serviceProviderConfiguration = BuildServiceProviderConfiguration(fileReRoute, globalConfiguration); var authOptionsForRoute = BuildAuthenticationOptions(fileReRoute); var claimsToHeaders = BuildAddThingsToRequest(fileReRoute.AddHeadersToRequest); var claimsToClaims = BuildAddThingsToRequest(fileReRoute.AddClaimsToRequest); var claimsToQueries = BuildAddThingsToRequest(fileReRoute.AddQueriesToRequest); var qosOptions = BuildQoSOptions(fileReRoute); var enableRateLimiting = IsEnableRateLimiting(fileReRoute); var rateLimitOption = BuildRateLimitOptions(fileReRoute, globalConfiguration, enableRateLimiting); var reRoute = new ReRouteBuilder() .WithDownstreamPathTemplate(fileReRoute.DownstreamPathTemplate) .WithUpstreamPathTemplate(fileReRoute.UpstreamPathTemplate) .WithUpstreamHttpMethod(fileReRoute.UpstreamHttpMethod) .WithUpstreamTemplatePattern(upstreamTemplatePattern) .WithIsAuthenticated(isAuthenticated) .WithAuthenticationOptions(authOptionsForRoute) .WithClaimsToHeaders(claimsToHeaders) .WithClaimsToClaims(claimsToClaims) .WithRouteClaimsRequirement(fileReRoute.RouteClaimsRequirement) .WithIsAuthorised(isAuthorised) .WithClaimsToQueries(claimsToQueries) .WithRequestIdKey(requestIdKey) .WithIsCached(isCached) .WithCacheOptions(new CacheOptions(fileReRoute.FileCacheOptions.TtlSeconds)) .WithDownstreamScheme(fileReRoute.DownstreamScheme) .WithLoadBalancer(fileReRoute.LoadBalancer) .WithDownstreamHost(fileReRoute.DownstreamHost) .WithDownstreamPort(fileReRoute.DownstreamPort) .WithLoadBalancerKey(reRouteKey) .WithServiceProviderConfiguraion(serviceProviderConfiguration) .WithIsQos(isQos) .WithQosOptions(qosOptions) .WithEnableRateLimiting(enableRateLimiting) .WithRateLimitOptions(rateLimitOption) .Build(); await SetupLoadBalancer(reRoute); SetupQosProvider(reRoute); return(reRoute); }
private static RateLimitOptions BuildRateLimitOptions(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration, bool enableRateLimiting) { RateLimitOptions rateLimitOption = null; if (enableRateLimiting) { rateLimitOption = new RateLimitOptions(enableRateLimiting, globalConfiguration.RateLimitOptions.ClientIdHeader, fileReRoute.RateLimitOptions.ClientWhitelist, globalConfiguration.RateLimitOptions.DisableRateLimitHeaders, globalConfiguration.RateLimitOptions.QuotaExceededMessage, globalConfiguration.RateLimitOptions.RateLimitCounterPrefix, new RateLimitRule(fileReRoute.RateLimitOptions.Period, TimeSpan.FromSeconds(fileReRoute.RateLimitOptions.PeriodTimespan), fileReRoute.RateLimitOptions.Limit) , globalConfiguration.RateLimitOptions.HttpStatusCode); } return(rateLimitOption); }
private async Task <ReRoute> SetUpReRoute(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { var globalRequestIdConfiguration = !string.IsNullOrEmpty(globalConfiguration?.RequestIdKey); var upstreamTemplate = BuildUpstreamTemplate(fileReRoute); var isAuthenticated = !string.IsNullOrEmpty(fileReRoute.AuthenticationOptions?.Provider); var isAuthorised = fileReRoute.RouteClaimsRequirement?.Count > 0; var isCached = fileReRoute.FileCacheOptions.TtlSeconds > 0; var requestIdKey = globalRequestIdConfiguration ? globalConfiguration.RequestIdKey : fileReRoute.RequestIdKey; var useServiceDiscovery = !string.IsNullOrEmpty(fileReRoute.ServiceName) && !string.IsNullOrEmpty(globalConfiguration?.ServiceDiscoveryProvider?.Provider); //note - not sure if this is the correct key, but this is probably the only unique key i can think of given my poor brain var loadBalancerKey = $"{fileReRoute.UpstreamTemplate}{fileReRoute.UpstreamHttpMethod}"; ReRoute reRoute; var serviceProviderPort = globalConfiguration?.ServiceDiscoveryProvider?.Port ?? 0; var serviceProviderConfiguration = new ServiceProviderConfiguraion(fileReRoute.ServiceName, fileReRoute.DownstreamHost, fileReRoute.DownstreamPort, useServiceDiscovery, globalConfiguration?.ServiceDiscoveryProvider?.Provider, globalConfiguration?.ServiceDiscoveryProvider?.Host, serviceProviderPort); if (isAuthenticated) { var authOptionsForRoute = new AuthenticationOptions(fileReRoute.AuthenticationOptions.Provider, fileReRoute.AuthenticationOptions.ProviderRootUrl, fileReRoute.AuthenticationOptions.ScopeName, fileReRoute.AuthenticationOptions.RequireHttps, fileReRoute.AuthenticationOptions.AdditionalScopes, fileReRoute.AuthenticationOptions.ScopeSecret); var claimsToHeaders = GetAddThingsToRequest(fileReRoute.AddHeadersToRequest); var claimsToClaims = GetAddThingsToRequest(fileReRoute.AddClaimsToRequest); var claimsToQueries = GetAddThingsToRequest(fileReRoute.AddQueriesToRequest); reRoute = new ReRoute(new DownstreamPathTemplate(fileReRoute.DownstreamPathTemplate), fileReRoute.UpstreamTemplate, fileReRoute.UpstreamHttpMethod, upstreamTemplate, isAuthenticated, authOptionsForRoute, claimsToHeaders, claimsToClaims, fileReRoute.RouteClaimsRequirement, isAuthorised, claimsToQueries, requestIdKey, isCached, new CacheOptions(fileReRoute.FileCacheOptions.TtlSeconds) , fileReRoute.DownstreamScheme, fileReRoute.LoadBalancer, fileReRoute.DownstreamHost, fileReRoute.DownstreamPort, loadBalancerKey, serviceProviderConfiguration); } else { reRoute = new ReRoute(new DownstreamPathTemplate(fileReRoute.DownstreamPathTemplate), fileReRoute.UpstreamTemplate, fileReRoute.UpstreamHttpMethod, upstreamTemplate, isAuthenticated, null, new List <ClaimToThing>(), new List <ClaimToThing>(), fileReRoute.RouteClaimsRequirement, isAuthorised, new List <ClaimToThing>(), requestIdKey, isCached, new CacheOptions(fileReRoute.FileCacheOptions.TtlSeconds), fileReRoute.DownstreamScheme, fileReRoute.LoadBalancer, fileReRoute.DownstreamHost, fileReRoute.DownstreamPort, loadBalancerKey, serviceProviderConfiguration); } var loadBalancer = await _loadBalanceFactory.Get(reRoute); _loadBalancerHouse.Add(reRoute.LoadBalancerKey, loadBalancer); return(reRoute); }
public async Task <Response <FileConfiguration> > Get() { var file = new FileConfiguration(); using (var connection = new MySqlConnection(_configuration.ConnectString)) { var result = await connection.QueryFirstOrDefaultAsync <OcelotGlobalConfiguration>(_gloableSql); if (result != null) { // get global configuration var glb = new FileGlobalConfiguration(); glb.BaseUrl = result.BaseUrl; glb.DownstreamScheme = result.DownstreamScheme; glb.RequestIdKey = result.RequestIdKey; if (!String.IsNullOrEmpty(result.HttpHandlerOptions)) { glb.HttpHandlerOptions = result.HttpHandlerOptions.ToObject <FileHttpHandlerOptions>(); } if (!String.IsNullOrEmpty(result.LoadBalancerOptions)) { glb.LoadBalancerOptions = result.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!String.IsNullOrEmpty(result.QoSOptions)) { glb.QoSOptions = result.QoSOptions.ToObject <FileQoSOptions>(); } if (!String.IsNullOrEmpty(result.ServiceDiscoveryProvider)) { glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider.ToObject <FileServiceDiscoveryProvider>(); } file.GlobalConfiguration = glb; //get re route info var routeresult = (await connection.QueryAsync <OcelotReRoute>(_routeSql, new { result.OcelotId }))?.AsList(); if (routeresult != null && routeresult.Count > 0) { var reroutelist = new List <FileReRoute>(); foreach (var model in routeresult) { var m = new FileReRoute(); if (!String.IsNullOrEmpty(model.AuthenticationOptions)) { m.AuthenticationOptions = model.AuthenticationOptions.ToObject <FileAuthenticationOptions>(); } if (!String.IsNullOrEmpty(model.CacheOptions)) { m.FileCacheOptions = model.CacheOptions.ToObject <FileCacheOptions>(); } if (!String.IsNullOrEmpty(model.DelegatingHandlers)) { m.DelegatingHandlers = model.DelegatingHandlers.ToObject <List <string> >(); } if (!String.IsNullOrEmpty(model.LoadBalancerOptions)) { m.LoadBalancerOptions = model.LoadBalancerOptions.ToObject <FileLoadBalancerOptions>(); } if (!String.IsNullOrEmpty(model.QoSOptions)) { m.QoSOptions = model.QoSOptions.ToObject <FileQoSOptions>(); } if (!String.IsNullOrEmpty(model.DownstreamHostAndPorts)) { m.DownstreamHostAndPorts = model.DownstreamHostAndPorts.ToObject <List <FileHostAndPort> >(); } m.DownstreamPathTemplate = model.DownstreamPathTemplate; m.DownstreamScheme = model.DownstreamScheme; m.Key = model.RequestIdKey; m.Priority = model.Priority ?? 0; m.RequestIdKey = model.RequestIdKey; m.ServiceName = model.ServiceName; m.UpstreamHost = model.UpstreamHost; m.UpstreamHttpMethod = model.UpstreamHttpMethod?.ToObject <List <string> >(); m.UpstreamPathTemplate = model.UpstreamPathTemplate; reroutelist.Add(m); } file.ReRoutes = reroutelist; } } else { throw new Exception("未监测到任何可用的配置信息"); } } if (file.ReRoutes == null || file.ReRoutes.Count == 0) { return(new OkResponse <FileConfiguration>(null)); } return(new OkResponse <FileConfiguration>(file)); }
private DownstreamReRoute SetUpDownstreamReRoute(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { var fileReRouteOptions = _fileReRouteOptionsCreator.Create(fileReRoute); var requestIdKey = _requestIdKeyCreator.Create(fileReRoute, globalConfiguration); var reRouteKey = CreateReRouteKey(fileReRoute); var upstreamTemplatePattern = _upstreamTemplatePatternCreator.Create(fileReRoute); var authOptionsForRoute = _authOptionsCreator.Create(fileReRoute); var claimsToHeaders = _claimsToThingCreator.Create(fileReRoute.AddHeadersToRequest); var claimsToClaims = _claimsToThingCreator.Create(fileReRoute.AddClaimsToRequest); var claimsToQueries = _claimsToThingCreator.Create(fileReRoute.AddQueriesToRequest); var qosOptions = _qosOptionsCreator.Create(fileReRoute.QoSOptions, fileReRoute.UpstreamPathTemplate, fileReRoute.UpstreamHttpMethod.ToArray()); var rateLimitOption = _rateLimitOptionsCreator.Create(fileReRoute.RateLimitOptions, globalConfiguration); var region = _regionCreator.Create(fileReRoute); var httpHandlerOptions = _httpHandlerOptionsCreator.Create(fileReRoute.HttpHandlerOptions); var hAndRs = _headerFAndRCreator.Create(fileReRoute); var downstreamAddresses = _downstreamAddressesCreator.Create(fileReRoute); var lbOptions = CreateLoadBalancerOptions(fileReRoute.LoadBalancerOptions); var reRoute = new DownstreamReRouteBuilder() .WithKey(fileReRoute.Key) .WithDownstreamPathTemplate(fileReRoute.DownstreamPathTemplate) .WithUpstreamPathTemplate(fileReRoute.UpstreamPathTemplate) .WithUpstreamHttpMethod(fileReRoute.UpstreamHttpMethod) .WithUpstreamTemplatePattern(upstreamTemplatePattern) .WithIsAuthenticated(fileReRouteOptions.IsAuthenticated) .WithAuthenticationOptions(authOptionsForRoute) .WithClaimsToHeaders(claimsToHeaders) .WithClaimsToClaims(claimsToClaims) .WithRouteClaimsRequirement(fileReRoute.RouteClaimsRequirement) .WithIsAuthorised(fileReRouteOptions.IsAuthorised) .WithClaimsToQueries(claimsToQueries) .WithRequestIdKey(requestIdKey) .WithIsCached(fileReRouteOptions.IsCached) .WithCacheOptions(new CacheOptions(fileReRoute.FileCacheOptions.TtlSeconds, region)) .WithDownstreamScheme(fileReRoute.DownstreamScheme) .WithLoadBalancerOptions(lbOptions) .WithDownstreamAddresses(downstreamAddresses) .WithLoadBalancerKey(reRouteKey) .WithQosOptions(qosOptions) .WithEnableRateLimiting(fileReRouteOptions.EnableRateLimiting) .WithRateLimitOptions(rateLimitOption) .WithHttpHandlerOptions(httpHandlerOptions) .WithServiceName(fileReRoute.ServiceName) .WithUseServiceDiscovery(fileReRoute.UseServiceDiscovery) .WithUpstreamHeaderFindAndReplace(hAndRs.Upstream) .WithDownstreamHeaderFindAndReplace(hAndRs.Downstream) .WithUpstreamHost(fileReRoute.UpstreamHost) .WithDelegatingHandlers(fileReRoute.DelegatingHandlers) .WithAddHeadersToDownstream(hAndRs.AddHeadersToDownstream) .WithAddHeadersToUpstream(hAndRs.AddHeadersToUpstream) .WithDangerousAcceptAnyServerCertificateValidator(fileReRoute.DangerousAcceptAnyServerCertificateValidator) .Build(); return(reRoute); }
private Route SetUpAggregateRoute(IEnumerable <Route> routes, FileAggregateRoute aggregateRoute, FileGlobalConfiguration globalConfiguration) { var applicableRoutes = new List <DownstreamRoute>(); var allRoutes = routes.SelectMany(x => x.DownstreamRoute); foreach (var routeKey in aggregateRoute.RouteKeys) { var selec = allRoutes.FirstOrDefault(q => q.Key == routeKey); if (selec == null) { return(null); } applicableRoutes.Add(selec); } var upstreamTemplatePattern = _creator.Create(aggregateRoute); var route = new RouteBuilder() .WithUpstreamHttpMethod(aggregateRoute.UpstreamHttpMethod) .WithUpstreamPathTemplate(upstreamTemplatePattern) .WithDownstreamRoutes(applicableRoutes) .WithAggregateRouteConfig(aggregateRoute.RouteKeysConfig) .WithUpstreamHost(aggregateRoute.UpstreamHost) .WithAggregator(aggregateRoute.Aggregator) .Build(); return(route); }
/// <summary> /// 查询网关配置数据 /// </summary> /// <param name="gatewayId"></param> /// <returns></returns> private async Task <FileConfiguration> GetGatewayData(int gatewayId) { var fileConfig = new FileConfiguration(); var configInfo = await _configDbRepository.GetFirstAsync(it => it.GatewayId == gatewayId); if (configInfo != null) { // config var fgc = new FileGlobalConfiguration { BaseUrl = configInfo.BaseUrl, DownstreamScheme = configInfo.DownstreamScheme, RequestIdKey = configInfo.RequestIdKey, }; if (!string.IsNullOrWhiteSpace(configInfo.HttpHandlerOptions)) { fgc.HttpHandlerOptions = Json.ToObject <FileHttpHandlerOptions>(configInfo.HttpHandlerOptions); } if (!string.IsNullOrWhiteSpace(configInfo.LoadBalancerOptions)) { fgc.LoadBalancerOptions = Json.ToObject <FileLoadBalancerOptions>(configInfo.LoadBalancerOptions); } if (!string.IsNullOrWhiteSpace(configInfo.QoSOptions)) { fgc.QoSOptions = Json.ToObject <FileQoSOptions>(configInfo.QoSOptions); } if (!string.IsNullOrWhiteSpace(configInfo.RateLimitOptions)) { fgc.RateLimitOptions = Json.ToObject <FileRateLimitOptions>(configInfo.RateLimitOptions); } if (!string.IsNullOrWhiteSpace(configInfo.ServiceDiscoveryProvider)) { fgc.ServiceDiscoveryProvider = Json.ToObject <FileServiceDiscoveryProvider>(configInfo.ServiceDiscoveryProvider); } fileConfig.GlobalConfiguration = fgc; // reroutes var reRouteResult = await _routeDbRepository.GetListAsync(it => it.GatewayId == configInfo.GatewayId && it.State == 1); if (reRouteResult.Count > 0) { var reroutelist = new List <FileReRoute>(); foreach (var model in reRouteResult) { var m = new FileReRoute() { UpstreamHost = model.UpstreamHost, UpstreamPathTemplate = model.UpstreamPathTemplate, DownstreamPathTemplate = model.DownstreamPathTemplate, DownstreamScheme = model.DownstreamScheme, ServiceName = model.ServiceName, Priority = model.Priority, RequestIdKey = model.RequestIdKey, Key = model.Key, Timeout = model.Timeout, }; if (!string.IsNullOrWhiteSpace(model.UpstreamHttpMethod)) { m.UpstreamHttpMethod = Json.ToObject <List <string> >(model.UpstreamHttpMethod); } if (!string.IsNullOrWhiteSpace(model.DownstreamHostAndPorts)) { m.DownstreamHostAndPorts = Json.ToObject <List <FileHostAndPort> >(model.DownstreamHostAndPorts); } if (!string.IsNullOrWhiteSpace(model.SecurityOptions)) { m.SecurityOptions = Json.ToObject <FileSecurityOptions>(model.SecurityOptions); } if (!string.IsNullOrWhiteSpace(model.CacheOptions)) { m.FileCacheOptions = Json.ToObject <FileCacheOptions>(model.CacheOptions); } if (!string.IsNullOrWhiteSpace(model.HttpHandlerOptions)) { m.HttpHandlerOptions = Json.ToObject <FileHttpHandlerOptions>(model.HttpHandlerOptions); } if (!string.IsNullOrWhiteSpace(model.AuthenticationOptions)) { m.AuthenticationOptions = Json.ToObject <FileAuthenticationOptions>(model.AuthenticationOptions); } if (!string.IsNullOrWhiteSpace(model.RateLimitOptions)) { m.RateLimitOptions = Json.ToObject <FileRateLimitRule>(model.RateLimitOptions); } if (!string.IsNullOrWhiteSpace(model.LoadBalancerOptions)) { m.LoadBalancerOptions = Json.ToObject <FileLoadBalancerOptions>(model.LoadBalancerOptions); } if (!string.IsNullOrWhiteSpace(model.QoSOptions)) { m.QoSOptions = Json.ToObject <FileQoSOptions>(model.QoSOptions); } if (!string.IsNullOrWhiteSpace(model.DelegatingHandlers)) { m.DelegatingHandlers = Json.ToObject <List <string> >(model.DelegatingHandlers); } reroutelist.Add(m); } fileConfig.ReRoutes = reroutelist; } } return(fileConfig); }
/// <summary> /// 从数据库中获取配置信息 /// </summary> /// <returns></returns> public async Task <Response <FileConfiguration> > Get() { #region 提取配置信息 var file = new FileConfiguration(); //提取默认启用的路由配置信息 string glbsql = "select * from AhphGlobalConfiguration where IsDefault=1 and InfoStatus=1"; //提取全局配置信息 using (var connection = new MySqlConnection(_option.DbConnectionStrings)) { var result = await connection.QueryFirstOrDefaultAsync <GatewaySettings>(glbsql); if (result != null) { var glb = new FileGlobalConfiguration(); //赋值全局信息 //glb.BaseUrl = result.BaseUrl; //glb.DownstreamScheme = result.DownstreamScheme; //glb.RequestIdKey = result.RequestIdKey; //glb.HttpHandlerOptions = result.HttpHandlerOptions?.ToObject<FileHttpHandlerOptions>(); //glb.LoadBalancerOptions = result.LoadBalancerOptions?.ToObject<FileLoadBalancerOptions>(); //glb.QoSOptions = result.QoSOptions?.ToObject<FileQoSOptions>(); //glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider?.ToObject<FileServiceDiscoveryProvider>(); //file.GlobalConfiguration = glb; ////提取所有路由信息 //string routesql = "select T2.* from AhphConfigReRoutes T1 inner join AhphReRoute T2 on T1.ReRouteId=T2.ReRouteId where AhphId=@AhphId and InfoStatus=1"; //var routeresult = (await connection.QueryAsync<AhphReRoute>(routesql, new { result.AhphId }))?.AsList(); //if (routeresult != null && routeresult.Count > 0) //{ // var reroutelist = new List<FileReRoute>(); // foreach (var model in routeresult) // { // var m = new FileReRoute // { // AuthenticationOptions = model.AuthenticationOptions?.ToObject<FileAuthenticationOptions>(), // FileCacheOptions = model.CacheOptions?.ToObject<FileCacheOptions>(), // DelegatingHandlers = model.DelegatingHandlers?.ToObject<List<string>>(), // LoadBalancerOptions = model.LoadBalancerOptions?.ToObject<FileLoadBalancerOptions>(), // QoSOptions = model.QoSOptions?.ToObject<FileQoSOptions>(), // DownstreamHostAndPorts = model.DownstreamHostAndPorts?.ToObject<List<FileHostAndPort>>(), // //开始赋值 // DownstreamPathTemplate = model.DownstreamPathTemplate, // DownstreamScheme = model.DownstreamScheme, // Key = model.RequestIdKey, // Priority = model.Priority ?? 0, // RequestIdKey = model.RequestIdKey, // ServiceName = model.ServiceName, // UpstreamHost = model.UpstreamHost, // UpstreamHttpMethod = model.UpstreamHttpMethod?.ToObject<List<string>>(), // UpstreamPathTemplate = model.UpstreamPathTemplate // }; // reroutelist.Add(m); // } // file.ReRoutes = reroutelist; //} } else { throw new Exception("未监测到任何可用的配置信息"); } } #endregion if (file.ReRoutes == null || file.ReRoutes.Count == 0) { return(new OkResponse <FileConfiguration>(null)); } return(new OkResponse <FileConfiguration>(file)); }