/// <summary>
        ///  Used: https://stackoverflow.com/a/40256772
        /// </summary>
        /// <returns></returns>
        public async Task Discover(IEnumerable <string> serviceNames)
        {
            if (!_options.ResolveClientsOnStartup)
            {
                return;
            }

            try
            {
                foreach (var serviceName in serviceNames?.Distinct())
                {
                    _logger.LogInformation($"Resolving service: '{serviceName}'.");

                    var serviceNameUri = ServiceFabricUriBuilder.Build(serviceName);
                    var partitions     = await _fabricClient.QueryManager.GetPartitionListAsync(serviceNameUri);

                    foreach (var partition in partitions)
                    {
                        _logger.LogInformation($"Discovered service partition: '{partition.PartitionInformation.Kind}':'{partition.PartitionInformation.Id}'");
                        var key = partition.PartitionInformation.Kind switch
                        {
                            ServicePartitionKind.Singleton => ServicePartitionKey.Singleton,
                            _ => throw new ArgumentOutOfRangeException($"Partitionkind: '{partition.PartitionInformation.Kind}' unknown."),
                        };
                        try
                        {
                            var resolved = await _servicePartitionResolver.ResolveAsync(serviceNameUri, key, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), CancellationToken.None);

                            foreach (var endpoint in resolved.Endpoints)
                            {
                                _logger.LogInformation($"Discovered service endpoint: '{endpoint.Address}'");
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError($"Could not resolve service: '{serviceNameUri}'.", ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
            }
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation($"{nameof(FileConfigurationPoller)} is starting.");

            _timer = new Timer(async x =>
            {
                if (_polling)
                {
                    return;
                }

                _polling = true;
                await Poll();
                _polling = false;
            }, null, _options.Delay, _options.Delay);

            return(Task.CompletedTask);
        }
示例#3
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     if (_option.EnableTimer)
     {//判断是否启用自动更新
         _logger.LogInformation($"{nameof(DbConfigurationPoller)} is starting.");
         _timer = new Timer(async x =>
         {
             if (_polling)
             {
                 return;
             }
             _polling = true;
             await Poll();
             _polling = false;
         }, null, _option.TimerDelay, _option.TimerDelay);
     }
     return(Task.CompletedTask);
 }
 public Task StartAsync(CancellationToken cancellationToken)
 {
     if (_option.AutoUpdate)
     {
         _logger.LogInformation($"{nameof(DBConfigurationPoller)} is starting.");
         _timer = new Timer(async x =>
         {
             if (_polling)
             {
                 return;
             }
             _polling = true;
             await Poll();
             _polling = false;
         }, null, _option.UpdateInterval, _option.UpdateInterval);
     }
     return(Task.CompletedTask);
 }
        public IDownstreamRouteProvider Get(IInternalConfiguration config)
        {
            if (!config.ReRoutes.Any() && IsServiceDiscovery(config.ServiceProviderConfiguration))
            {
                _logger.LogInformation($"Selected {nameof(DownstreamRouteCreator)} as DownstreamRouteProvider for this request");
                return(_providers[nameof(DownstreamRouteCreator)]);
            }

            return(_providers[nameof(DownstreamRouteFinder)]);
        }
        public IDownstreamRouteProvider Get(IInternalConfiguration config)
        {
            //todo - this is a bit hacky we are saying there are no reRoutes or there are reRoutes but none of them have
            //an upstream path template which means they are dyanmic and service discovery is on...
            if ((!config.ReRoutes.Any() || config.ReRoutes.All(x => string.IsNullOrEmpty(x.UpstreamPathTemplate.Value))) && IsServiceDiscovery(config.ServiceProviderConfiguration))
            {
                _logger.LogInformation($"Selected {nameof(DownstreamRouteCreator)} as DownstreamRouteProvider for this request");
                return(_providers[nameof(DownstreamRouteCreator)]);
            }

            return(_providers[nameof(DownstreamRouteFinder)]);
        }
        public async Task <Response <FileConfiguration> > Get()
        {
            _logger.LogInformation("Get route rules");
            var config = _cache.Get(_configurationKey, _configurationKey);

            if (config == null)
            {
                var ocelotCfg = _configDbDal.GetOcelotConfigBySection(OcelotConfigurationSection.All);
                _logger.LogInformation("Get route rules from DB");
                if (ocelotCfg != null)
                {
                    config = JsonConvert.DeserializeObject <FileConfiguration>(ocelotCfg.Payload);
                    _cache.AddAndDelete(_configurationKey, config, new TimeSpan(0, 0, 15), null);
                }
            }
            foreach (var item in config.ReRoutes)
            {
                _logger.LogInformation($"Get Rule : {item.Key} - {item.UpstreamPathTemplate} -> {item.DownstreamPathTemplate}");
            }
            return(new OkResponse <FileConfiguration>(config));
        }
示例#8
0
        private async Task Poll()
        {
            _logger.LogInformation("Started polling");

            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}");
                return;
            }
            else
            {
                var config = await _internalConfigCreator.Create(fileConfig.Data);

                if (!config.IsError)
                {
                    _internalConfigRepo.AddOrReplace(config.Data);
                }
            }
            _logger.LogInformation("Finished polling");
        }
        private async Task Poll()
        {
            _logger.LogInformation("Started polling consul");

            var fileConfig = await _repo.Get();

            if (fileConfig.IsError)
            {
                _logger.LogWarning($"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.LogInformation("Finished polling consul");
        }
示例#10
0
        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);
        }
示例#11
0
 public IActionResult Index()
 {
     log.LogInformation("*********Start*************");
     return(View());
 }