public IActionResult CreateReRoute(string id, FileReRouteViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var validator = new FileReRouteValidator();
            var results   = validator.Validate(model.FileReRoute);

            if (!results.IsValid)
            {
                results.Errors.ToList().ForEach(e => ModelState.AddModelError($"FileReRoute.{e.PropertyName}", e.ErrorMessage));
                return(View(model));
            }

            var routes = _fileConfigRepo.Get();

            routes.Data.ReRoutes.Add(model.FileReRoute);
            _fileConfigRepo.Set(routes.Data);

            _reload.AddReloadFlag();

            return(RedirectToAction("Index"));
        }
Пример #2
0
        public async Task <IActionResult> Get()
        {
            _logger.LogInformation("get demo log");
            //对ReRoute对象操作是对FileConfiguration.ReRoutes属性的操作
            var response = await _repo.Get();

            if (response.IsError)
            {
                return(new BadRequestObjectResult(response.Errors));
            }
            return(new OkObjectResult(response.Data.ReRoutes));
        }
Пример #3
0
        private int GetDelay()
        {
            int delay = 1000;

            Response <File.FileConfiguration> fileConfig = Task.Run(async() => await _fileConfigurationRepository.Get()).Result;

            if (fileConfig?.Data?.GlobalConfiguration?.ServiceDiscoveryProvider != null &&
                !fileConfig.IsError &&
                fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval > 0)
            {
                delay = fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval;
            }
            else
            {
                Response <IInternalConfiguration> internalConfig = _internalConfigRepo.Get();
                if (internalConfig?.Data?.ServiceProviderConfiguration != null &&
                    !internalConfig.IsError &&
                    internalConfig.Data.ServiceProviderConfiguration.PollingInterval > 0)
                {
                    delay = internalConfig.Data.ServiceProviderConfiguration.PollingInterval;
                }
            }

            return(delay);
        }
Пример #4
0
        public async Task Should_Get_Config()
        {
            GivenIHaveAConfiguration();
            var response = await _fileConfigRepository.Get();

            response.ShouldNotBeNull();
            response.Errors.Count.ShouldBe(0);
            response.IsError.ShouldBe(false);
            var routes = response.Data.Routes;
            var route  = routes.FirstOrDefault(c => c.UpstreamPathTemplate.Equals("/connect/token"));

            route.Timeout.ShouldBe(4399);
            route.Priority.ShouldBe(3389);
            route.DelegatingHandlers.Count.ShouldBeGreaterThan(0);
            route.DelegatingHandlers[0].ShouldBe("Taitans");
            route.Key.ShouldBe("WO_CAO");
            route.UpstreamHost.ShouldBe("http://www.Taitans.com");
            route.DownstreamHostAndPorts.ShouldNotBeNull();

            route.HttpHandlerOptions.ShouldNotBeNull();
            route.HttpHandlerOptions.AllowAutoRedirect.ShouldBe(true);
            route.HttpHandlerOptions.UseCookieContainer.ShouldBe(true);
            route.HttpHandlerOptions.UseProxy.ShouldBe(true);
            route.HttpHandlerOptions.UseTracing.ShouldBe(true);

            route.AuthenticationOptions.ShouldNotBeNull();
            route.AuthenticationOptions.AllowedScopes.Count.ShouldBe(1);
            route.RateLimitOptions.ShouldNotBeNull();
            route.RateLimitOptions.ClientWhitelist.Count.ShouldBe(1);
            route.LoadBalancerOptions.ShouldNotBeNull();
            route.LoadBalancerOptions.Expiry.ShouldBe(95);
            route.LoadBalancerOptions.Key.ShouldBe("Taitans");
            route.LoadBalancerOptions.Type.ShouldBe("www.Taitans.com");
            route.QoSOptions.ShouldNotBeNull();
            route.QoSOptions.DurationOfBreak.ShouldBe(24300);
            route.QoSOptions.ExceptionsAllowedBeforeBreaking.ShouldBe(802);
            route.QoSOptions.TimeoutValue.ShouldBe(30624);
            route.DownstreamScheme.ShouldBe("http");
            route.DownstreamHttpMethod.ShouldBe("GET");
            route.ServiceName.ShouldBe("Taitans-cn");
            route.RouteIsCaseSensitive.ShouldBe(true);
            route.FileCacheOptions.ShouldNotBeNull();
            route.FileCacheOptions.TtlSeconds.ShouldBe(2020);
            route.FileCacheOptions.Region.ShouldBe("github.com/Taitans");
            route.RequestIdKey.ShouldNotBeNull("ttgzs.cn");
            route.AddQueriesToRequest.ShouldContainKeyAndValue("NB", "www.Taitans.com");
            route.RouteClaimsRequirement.ShouldContainKeyAndValue("MVP", "www.Taitans.com");
            route.AddClaimsToRequest.ShouldContainKeyAndValue("AT", "www.Taitans.com");
            route.DownstreamHeaderTransform.ShouldContainKeyAndValue("CVT", "www.Taitans.com");
            route.UpstreamHeaderTransform.ShouldContainKeyAndValue("DCT", "www.Taitans.com");
            route.AddHeadersToRequest.ShouldContainKeyAndValue("Trubost", "www.Taitans.com");
            route.ChangeDownstreamPathTemplate.ShouldContainKeyAndValue("EVCT", "www.Taitans.com");
            route.UpstreamHost.ShouldBe("http://www.Taitans.com");
            route.UpstreamHttpMethod.Count.ShouldBe(1);
            route.UpstreamPathTemplate.ShouldBe("/connect/token");
            route.DownstreamPathTemplate.ShouldBe("/connect/token");
            route.DangerousAcceptAnyServerCertificateValidator.ShouldBe(true);
            route.SecurityOptions.IPAllowedList.Count.ShouldBe(1);
            route.SecurityOptions.IPBlockedList.Count.ShouldBe(1);
        }
Пример #5
0
        private static async Task <Response> SetUpConfigFromConsul(IApplicationBuilder builder, IFileConfigurationRepository consulFileConfigRepo, IFileConfigurationSetter setter, IOptions <FileConfiguration> fileConfig)
        {
            Response config = null;

            var ocelotConfigurationRepository =
                (IOcelotConfigurationRepository)builder.ApplicationServices.GetService(
                    typeof(IOcelotConfigurationRepository));
            var ocelotConfigurationCreator =
                (IOcelotConfigurationCreator)builder.ApplicationServices.GetService(
                    typeof(IOcelotConfigurationCreator));

            var fileConfigFromConsul = await consulFileConfigRepo.Get();

            if (fileConfigFromConsul.Data == null)
            {
                config = await setter.Set(fileConfig.Value);
            }
            else
            {
                var ocelotConfig = await ocelotConfigurationCreator.Create(fileConfigFromConsul.Data);

                if (ocelotConfig.IsError)
                {
                    return(new ErrorResponse(ocelotConfig.Errors));
                }
                config = await ocelotConfigurationRepository.AddOrReplace(ocelotConfig.Data);

                //todo - this starts the poller if it has been registered...please this is so bad.
                var hack = builder.ApplicationServices.GetService(typeof(ConsulFileConfigurationPoller));
            }

            return(new OkResponse());
        }
Пример #6
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;
            }

            var asJson = ToJson(fileConfig.Data);

            if (!fileConfig.IsError && asJson != _previousAsJson)
            {
                var config = await _internalConfigCreator.Create(fileConfig.Data);

                if (!config.IsError)
                {
                    _internalConfigRepo.AddOrReplace(config.Data);
                }

                _previousAsJson = asJson;
            }

            _logger.LogInformation("Finished polling");
        }
        public IActionResult DeleteReRoute(string id)
        {
            var routes = _fileConfigRepo.Get();
            var route  = routes.Data.ReRoutes.FirstOrDefault(r => id == r.GetId());

            if (route == null)
            {
                return(RedirectToAction("Index"));
            }

            routes.Data.ReRoutes.Remove(route);
            _fileConfigRepo.Set(routes.Data);

            Reload(routes.Data);

            return(RedirectToAction("Index"));
        }
        public async Task <IEnumerable <RouteRule> > Get()
        {
            var repo = await _repo.Get();

            var fileRoutes = repo.Data.ReRoutes;
            List <RouteRule> routeRules = new List <RouteRule>();

            if (fileRoutes == null || fileRoutes.Count == 0)
            {
                return(routeRules);
            }
            foreach (var fileRoute in fileRoutes)
            {
                routeRules.Add(ObjectConverter.ConvertToRouteRule(fileRoute));
            }
            return(routeRules);
        }
Пример #9
0
        public async Task <OperationResult> Get()
        {
            var response = await _repo.Get();

            if (response.IsError)
            {
                return(OperationResult.CreateError(JsonConvert.SerializeObject(response.Errors)));
            }

            return(OperationResult.CreateSuccess("ok", response.Data));
        }
Пример #10
0
        public async Task <IActionResult> Get()
        {
            _logger.LogInformation("get demo log");
            var response = await _repo.Get();

            if (response.IsError)
            {
                return(new BadRequestObjectResult(response.Errors));
            }
            return(new OkObjectResult(response.Data.GlobalConfiguration));
        }
Пример #11
0
        public async Task <IActionResult> Get()
        {
            var response = await _repo.Get();

            if (response.IsError)
            {
                return(new BadRequestObjectResult(response.Errors));
            }

            return(new OkObjectResult(response.Data));
        }
Пример #12
0
        public async Task ReloadConfig()
        {
            await Task.Run(
                () =>
            {
                var config = _fileConfigRepo.Get();
                _configSetter.Set(config.Data);
            });

            await RemoveReloadFlag();
        }
Пример #13
0
        /// <summary>
        /// 从缓存中获取配置信息
        /// </summary>
        /// <returns></returns>
        public Response <IInternalConfiguration> Get()
        {
            var key    = _options.RedisKeyPrefix + "-internalConfiguration";
            var result = RedisHelper.Get <InternalConfiguration>(key);

            if (result != null)
            {
                return(new OkResponse <IInternalConfiguration>(result));
            }
            var fileconfig     = _fileConfigurationRepository.Get().Result;
            var internalConfig = _internalConfigurationCreator.Create(fileconfig.Data).Result;

            AddOrReplace(internalConfig.Data);
            return(new OkResponse <IInternalConfiguration>(internalConfig.Data));
        }
Пример #14
0
        /// <summary>
        /// 从缓存中获取配置信息
        /// </summary>
        /// <returns></returns>
        public Response <IInternalConfiguration> Get()
        {
            var key    = _options.RedisOcelotKeyPrefix + nameof(InternalConfiguration);
            var result = _ocelotCache.Get(key, "");

            if (result != null)
            {
                return(new OkResponse <IInternalConfiguration>(result));
            }
            var fileconfig     = _fileConfigurationRepository.Get().Result;
            var internalConfig = _internalConfigurationCreator.Create(fileconfig.Data).Result;

            AddOrReplace(internalConfig.Data);
            return(new OkResponse <IInternalConfiguration>(internalConfig.Data));
        }
Пример #15
0
        /// <summary>
        /// 从缓存中获取配置信息
        /// </summary>
        /// <returns></returns>
        public Response <IInternalConfiguration> Get()
        {
            var key    = CzarCacheRegion.InternalConfigurationRegion;
            var result = _ocelotCache.Get(key, "");

            if (result != null)
            {
                return(new OkResponse <IInternalConfiguration>(result));
            }
            var fileconfig     = _fileConfigurationRepository.Get().Result;
            var internalConfig = _internalConfigurationCreator.Create(fileconfig.Data).Result;

            AddOrReplace(internalConfig.Data);
            return(new OkResponse <IInternalConfiguration>(internalConfig.Data));
        }
Пример #16
0
        private static async Task SetFileConfigInConsul(IApplicationBuilder builder,
                                                        IFileConfigurationRepository fileConfigRepo, IOptions <FileConfiguration> fileConfig,
                                                        IInternalConfigurationCreator internalConfigCreator, IInternalConfigurationRepository internalConfigRepo)
        {
            // get the config from consul.
            var fileConfigFromConsul = await fileConfigRepo.Get();

            if (IsError(fileConfigFromConsul))
            {
                ThrowToStopOcelotStarting(fileConfigFromConsul);
            }
            else if (ConfigNotStoredInConsul(fileConfigFromConsul))
            {
                //there was no config in consul set the file in config in consul
                await fileConfigRepo.Set(fileConfig.Value);
            }
            else
            {
                // create the internal config from consul data
                var internalConfig = await internalConfigCreator.Create(fileConfigFromConsul.Data);

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
                else
                {
                    // add the internal config to the internal repo
                    var response = internalConfigRepo.AddOrReplace(internalConfig.Data);

                    if (IsError(response))
                    {
                        ThrowToStopOcelotStarting(response);
                    }
                }

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
            }

            //todo - this starts the poller if it has been registered...please this is so bad.
            var hack = builder.ApplicationServices.GetService(typeof(ConsulFileConfigurationPoller));
        }
        private static async Task SetFileConfigInDataBase(IApplicationBuilder builder,
                                                          IFileConfigurationRepository fileConfigRepo, IOptionsMonitor <FileConfiguration> fileConfig,
                                                          IInternalConfigurationCreator internalConfigCreator, IInternalConfigurationRepository internalConfigRepo)
        {
            // get the config from consul.
            var fileConfigFromDataBase = await fileConfigRepo.Get();

            if (IsError(fileConfigFromDataBase))
            {
                ThrowToStopOcelotStarting(fileConfigFromDataBase);
            }
            //else if (ConfigNotStoredInDataBase(fileConfigFromDataBase))
            //{
            //    //there was no config in consul set the file in config in consul
            //    await fileConfigRepo.Set(fileConfig.CurrentValue);
            //}
            else
            {
                await fileConfigRepo.Set(fileConfigFromDataBase.Data);

                // create the internal config from consul data
                var internalConfig = await internalConfigCreator.Create(fileConfigFromDataBase.Data);

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
                else
                {
                    // add the internal config to the internal repo
                    var response = internalConfigRepo.AddOrReplace(internalConfig.Data);

                    if (IsError(response))
                    {
                        ThrowToStopOcelotStarting(response);
                    }
                }

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
            }
        }
Пример #18
0
        private async Task Poll()
        {
            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);
                }
            }
        }
        public async Task OnOcelotConfigurationChanged(DateTime changedTime)
        {
            var fileConfig = await _fileConfigRepo.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("ocelot configuration changed on {changedTime}", changedTime.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        public async Task OnOcelotConfigurationChanged(ApigatewayConfigChangeCommand changeCommand)
        {
            var fileConfig = await _fileConfigRepo.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("ocelot configuration changed on {0}", changeCommand.DateTime);
        }
Пример #21
0
        public async Task UpdateInternalConfigurationCache()
        {
            var key = CzarCacheRegion.InternalConfigurationRegion;

            key = CzarOcelotHelper.GetKey(_options.RedisOcelotKeyPrefix, "", key);
            var fileconfig = await _fileConfigurationRepository.Get();

            var internalConfig = await _internalConfigurationCreator.Create(fileconfig.Data);

            var config = (InternalConfiguration)internalConfig.Data;

            if (_options.ClusterEnvironment)
            {
                RedisHelper.Set(key, config);              //加入redis缓存
                RedisHelper.Publish(key, config.ToJson()); //发布事件
            }
            else
            {
                _cache.Remove(key);
            }
        }
Пример #22
0
        /// <summary>
        /// 设置存储配置信息
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="fileConfigRepo"></param>
        /// <param name="internalConfigCreator"></param>
        /// <param name="internalConfigRepo"></param>
        /// <returns></returns>
        private static async Task SetFileConfigInDataBase(IApplicationBuilder builder,
                                                          IFileConfigurationRepository fileConfigRepo,
                                                          IInternalConfigurationCreator internalConfigCreator, IInternalConfigurationRepository internalConfigRepo)
        {
            // 从redis中获取数据
            var fileConfigFromDataBase = await fileConfigRepo.Get();

            if (IsError(fileConfigFromDataBase))
            {
                ThrowToStopOcelotStarting(fileConfigFromDataBase);
            }
            else
            {
                //设置存储
                await fileConfigRepo.Set(fileConfigFromDataBase.Data);

                // create the internal config from consul data
                var internalConfig = await internalConfigCreator.Create(fileConfigFromDataBase.Data);

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
                else
                {
                    //
                    var response = internalConfigRepo.AddOrReplace(internalConfig.Data);

                    if (IsError(response))
                    {
                        ThrowToStopOcelotStarting(response);
                    }
                }

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
            }
        }
Пример #23
0
        public IActionResult ReLoad()
        {
            var getResponse = _configRepo.Get().Result;

            if (getResponse.IsError)
            {
                _logger.Warn("加载Ocelot配置失败: " + JsonConvert.SerializeObject(getResponse.Errors));
                return(BadRequest(getResponse.Errors));
            }

            var setResponse = _setter.Set(getResponse.Data).Result;

            if (setResponse.IsError)
            {
                _logger.Warn("加载Ocelot配置失败: " + JsonConvert.SerializeObject(setResponse.Errors));
                return(BadRequest(setResponse.Errors));
            }

            _logger.Info("加载Ocelot配置成功: " + JsonConvert.SerializeObject(getResponse.Data));

            return(Ok(getResponse.Data));
        }
Пример #24
0
        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");
        }
        private static async Task SetFileConfigInSqlServer(IApplicationBuilder builder,
                                                           IFileConfigurationRepository fileConfigRepo, IOptionsMonitor <FileConfiguration> fileConfig,
                                                           IInternalConfigurationCreator internalConfigCreator, IInternalConfigurationRepository internalConfigRepo)
        {
            var fileConfigFromSqlServer = await fileConfigRepo.Get();

            if (IsError(fileConfigFromSqlServer))
            {
                ThrowToStopOcelotStarting(fileConfigFromSqlServer);
            }
            else if (ConfigNotStoredInConsul(fileConfigFromSqlServer))
            {
                await fileConfigRepo.Set(fileConfig.CurrentValue);
            }
            else
            {
                var internalConfig = await internalConfigCreator.Create(fileConfigFromSqlServer.Data);

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
                else
                {
                    var response = internalConfigRepo.AddOrReplace(internalConfig.Data);

                    if (IsError(response))
                    {
                        ThrowToStopOcelotStarting(response);
                    }
                }

                if (IsError(internalConfig))
                {
                    ThrowToStopOcelotStarting(internalConfig);
                }
            }
        }
Пример #26
0
        public async Task HandleEventAsync(ApigatewayConfigChangeEventData eventData)
        {
            if (Options.AppId.Equals(eventData.AppId))
            {
                var fileConfig = await _fileConfigRepo.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("ocelot configuration changed on {0}", eventData.DateTime);
            }
        }
Пример #27
0
        public async Task HandleEventAsync(OcelotConfigChangeCommand eventData)
        {
            _logger.LogInformation("************************ INCOMING MESSAGE ****************************");
            _logger.LogInformation(JsonConvert.SerializeObject(eventData));
            _logger.LogInformation("**********************************************************************");

            var fileConfig = await _fileConfigRepo.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("ocelot configuration changed on {0}", eventData.DateTime);
        }
Пример #28
0
 private void WhenISetTheConfiguration()
 {
     _repo.Set(_fileConfiguration);
     _result = _repo.Get().Data;
 }
Пример #29
0
        public IActionResult Index()
        {
            var repo = _fileConfigRepo.Get();

            return(View(repo.Result.Data));
        }
 public async Task <Response <FileConfiguration> > GetConfig()
 {
     return(await _fileConfigRepo.Get());
 }