Ejemplo n.º 1
0
        public Response <DownstreamRoute> Get(string path, string httpMethod, IInternalConfiguration configuration, string upstreamHost)
        {
            var downstreamRoutes = new List <DownstreamRoute>();

            var applicableReRoutes = configuration.ReRoutes
                                     .Where(r => RouteIsApplicableToThisRequest(r, httpMethod, upstreamHost))
                                     .OrderByDescending(x => x.UpstreamTemplatePattern.Priority);

            foreach (var reRoute in applicableReRoutes)
            {
                var urlMatch = _urlMatcher.Match(path, reRoute.UpstreamTemplatePattern.Template);

                if (urlMatch.Data.Match)
                {
                    downstreamRoutes.Add(GetPlaceholderNamesAndValues(path, reRoute));
                }
            }

            if (downstreamRoutes.Any())
            {
                var notNullOption = downstreamRoutes.FirstOrDefault(x => !string.IsNullOrEmpty(x.ReRoute.UpstreamHost));
                var nullOption    = downstreamRoutes.FirstOrDefault(x => string.IsNullOrEmpty(x.ReRoute.UpstreamHost));

                return(notNullOption != null ? new OkResponse <DownstreamRoute>(notNullOption) : new OkResponse <DownstreamRoute>(nullOption));
            }

            return(new ErrorResponse <DownstreamRoute>(new UnableToFindDownstreamRouteError(path, httpMethod)));
        }
Ejemplo n.º 2
0
        private void GivenTheConfigurationIs(IInternalConfiguration config)
        {
            var response = new Responses.OkResponse <IInternalConfiguration>(config);

            _configRepo
            .Setup(x => x.Get()).Returns(response);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 设置配置信息
        /// </summary>
        /// <param name="internalConfiguration">配置信息</param>
        /// <returns></returns>
        public Response AddOrReplace(IInternalConfiguration internalConfiguration)
        {
            var key = _options.RedisOcelotKeyPrefix + nameof(InternalConfiguration);

            _ocelotCache.Add(key, (InternalConfiguration)internalConfiguration, TimeSpan.FromSeconds(_options.CacheTime), "");
            return(new OkResponse());
        }
        /// <summary>
        /// 设置配置信息
        /// </summary>
        /// <param name="internalConfiguration">配置信息</param>
        /// <returns></returns>
        public Response AddOrReplace(IInternalConfiguration internalConfiguration)
        {
            var key = _options.RedisKeyPrefix + "-internalConfiguration";

            RedisHelper.Set(key, internalConfiguration.ToJson());
            return(new OkResponse());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 设置配置信息
        /// </summary>
        /// <param name="internalConfiguration">配置信息</param>
        /// <returns></returns>
        public Response AddOrReplace(IInternalConfiguration internalConfiguration)
        {
            var key = CzarCacheRegion.InternalConfigurationRegion;

            _ocelotCache.Add(key, (InternalConfiguration)internalConfiguration, TimeSpan.FromSeconds(_options.CzarCacheTime), "");
            return(new OkResponse());
        }
Ejemplo n.º 6
0
 private void GivenTheConfiguration(IInternalConfiguration config)
 {
     _upstreamHost       = "doesnt matter";
     _upstreamUrlPath    = "/auth/test";
     _upstreamHttpMethod = "GET";
     _configuration      = config;
 }
Ejemplo n.º 7
0
 private void GivenTheConfiguration(IInternalConfiguration config, string upstreamUrlPath)
 {
     _upstreamHost       = "doesnt matter";
     _upstreamUrlPath    = upstreamUrlPath;
     _upstreamHttpMethod = "GET";
     _configuration      = config;
 }
 private void GivenTheFollowingConfig(IInternalConfiguration config)
 {
     _config = config;
     _repo
     .Setup(x => x.Get())
     .Returns(new OkResponse <IInternalConfiguration>(_config));
 }
Ejemplo n.º 9
0
 /// <summary>
 /// 将数据替换掉
 /// </summary>
 /// <param name="internalConfiguration"></param>
 /// <returns></returns>
 public Response AddOrReplace(IInternalConfiguration internalConfiguration)
 {
     lock (LockObject)
     {
         //存储基本的配置
         redis.RedisString().Add(RedisCacheKey, internalConfiguration);
     }
     return(new OkResponse());
 }
Ejemplo n.º 10
0
        public Response AddOrReplace(IInternalConfiguration internalConfiguration)
        {
            lock (LockObject)
            {
                _internalConfiguration = internalConfiguration;
            }

            return(new OkResponse());
        }
Ejemplo n.º 11
0
        public IDownstreamRouteProvider Get(IInternalConfiguration config)
        {
            if (!config.ReRoutes.Any() && IsServiceDiscovery(config.ServiceProviderConfiguration))
            {
                return(_providers[nameof(DownstreamRouteCreator)]);
            }

            return(_providers[nameof(DownstreamRouteFinder)]);
        }
        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)]);
        }
Ejemplo n.º 13
0
 public PostgreSqlEventStorage(IServiceProvider serviceProvider, PostgreSqlOptions options, string name, string tableName)
 {
     this.providerName           = name;
     this.tableName              = tableName;
     this.options                = options;
     this._serviceProvider       = serviceProvider;
     this._logger                = serviceProvider.GetRequiredService <ILogger <PostgreSqlStateStorage> >();
     this._internalConfiguration = serviceProvider.GetRequiredService <IInternalConfiguration>();
     this.BuildSql(tableName);
 }
        public Response AddOrReplace(IInternalConfiguration internalConfiguration)
        {
            lock (LockObject)
            {
                _internalConfiguration = internalConfiguration;
            }

            _changeTokenSource.Activate();
            return(new OkResponse());
        }
Ejemplo n.º 15
0
        public RabbitConsumer(IServiceProvider serviceProvider, string providerName, ISerializer serializer)
        {
            this.providerName           = providerName;
            this._serviceProvider       = serviceProvider;
            this._serializer            = serializer;
            this._internalConfiguration = serviceProvider.GetRequiredService <IInternalConfiguration>();
            this._logger = serviceProvider.GetRequiredService <ILogger <RabbitConsumer> >();
            var _channelFactory = serviceProvider.GetRequiredServiceByName <IRabbitChannelFactory>(this.providerName);

            this._channel = _channelFactory.GetChannel();
        }
Ejemplo n.º 16
0
        private void TrySetGlobalRequestId(DownstreamContext context, IInternalConfiguration configuration)
        {
            var key = configuration.RequestId;

            if (!string.IsNullOrEmpty(key) && context.HttpContext.Request.Headers.TryGetValue(key, out var upstreamRequestIds))
            {
                context.HttpContext.TraceIdentifier = upstreamRequestIds.First();
            }

            _repo.Add("RequestId", context.HttpContext.TraceIdentifier);
        }
        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)]);
        }
Ejemplo n.º 18
0
 public HttpPeer(string hostAndPort, HttpClient httpClient, IBaseUrlFinder finder, IInternalConfiguration config, IIdentityServerConfiguration identityServerConfiguration)
 {
     _identityServerConfiguration = identityServerConfiguration;
     _config                 = config;
     Id                      = hostAndPort;
     _hostAndPort            = hostAndPort;
     _httpClient             = httpClient;
     _jsonSerializerSettings = new JsonSerializerSettings()
     {
         TypeNameHandling = TypeNameHandling.All
     };
     _baseSchemeUrlAndPort = finder.Find();
 }
Ejemplo n.º 19
0
        private static void CreateAdministrationArea(IApplicationBuilder builder, IInternalConfiguration configuration)
        {
            if (!string.IsNullOrEmpty(configuration.AdministrationPath))
            {
                builder.Map(configuration.AdministrationPath, app =>
                {
                    //todo - hack so we know that we are using internal identity server
                    var identityServerConfiguration = builder.ApplicationServices.GetService <IIdentityServerConfiguration>();
                    if (identityServerConfiguration != null)
                    {
                        app.UseIdentityServer();
                    }

                    app.UseAuthentication();
                    app.UseMvc();
                });
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Activate Grain
        /// </summary>
        /// <returns></returns>
        public override async Task OnActivateAsync()
        {
            try
            {
                this._eventBufferBlock      = new DataflowBufferBlock <EventTransactionModel <TStateKey> >(this.TriggerEventStorage);
                this._internalConfiguration = this.ServiceProvider.GetRequiredService <IInternalConfiguration>();
                this._mqPublisher           = this.ServiceProvider.GetRequiredService <IMQPublisher>();
                this._eventSourcing         = await this.ServiceProvider.GetEventSourcing <TState, TStateKey>(this).Init(this.StateId);

                this.State = await this._eventSourcing.ReadSnapshotAsync();

                this.PublishOptions = this._internalConfiguration.GetEventPublishOptions(this);
                await base.OnActivateAsync();
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, $"{StateId} Activate Grain failure");
                throw ex;
            }
        }
 private void GivenTheReRoutes(List <ReRoute> reRoutes, ServiceProviderConfiguration config)
 {
     _config = new InternalConfiguration(reRoutes, "", config, "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build());
 }
Ejemplo n.º 22
0
 public MQSubscriber(IServiceProvider serviceProvider, IInternalConfiguration configuration, ILogger <MQSubscriber> logger)
 {
     this._serviceProvider = serviceProvider;
     this._configuration   = configuration;
     this._logger          = logger;
 }
 private void GivenTheFollowingConfig(IInternalConfiguration config)
 {
     _config = config;
     _httpContext.Items.SetIInternalConfiguration(config);
 }
Ejemplo n.º 24
0
 private static bool UsingNacosServiceDiscoveryProvider(IInternalConfiguration configuration)
 {
     return(configuration?.ServiceProviderConfiguration != null && configuration.ServiceProviderConfiguration.Type?.ToLower() == "nacos");
 }
Ejemplo n.º 25
0
        public Response <DownstreamRoute> Get(string upstreamUrlPath, string upstreamQueryString, string upstreamHttpMethod, IInternalConfiguration configuration, string upstreamHost)
        {
            var serviceName = GetServiceName(upstreamUrlPath);

            var downstreamPath = GetDownstreamPath(upstreamUrlPath);

            if (HasQueryString(downstreamPath))
            {
                downstreamPath = RemoveQueryString(downstreamPath);
            }

            var downstreamPathForKeys = $"/{serviceName}{downstreamPath}";

            var loadBalancerKey = CreateLoadBalancerKey(downstreamPathForKeys, upstreamHttpMethod, configuration.LoadBalancerOptions);

            if (_cache.TryGetValue(loadBalancerKey, out var downstreamRoute))
            {
                return(downstreamRoute);
            }

            var qosOptions = _qoSOptionsCreator.Create(configuration.QoSOptions, downstreamPathForKeys, new List <string> {
                upstreamHttpMethod
            });

            var upstreamPathTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue(upstreamUrlPath).Build();

            var downstreamReRouteBuilder = new DownstreamReRouteBuilder()
                                           .WithServiceName(serviceName)
                                           .WithLoadBalancerKey(loadBalancerKey)
                                           .WithDownstreamPathTemplate(downstreamPath)
                                           .WithUseServiceDiscovery(true)
                                           .WithHttpHandlerOptions(configuration.HttpHandlerOptions)
                                           .WithQosOptions(qosOptions)
                                           .WithDownstreamScheme(configuration.DownstreamScheme)
                                           .WithLoadBalancerOptions(configuration.LoadBalancerOptions)
                                           .WithUpstreamPathTemplate(upstreamPathTemplate);

            var rateLimitOptions = configuration.ReRoutes != null
                ? configuration.ReRoutes
                                   .SelectMany(x => x.DownstreamReRoute)
                                   .FirstOrDefault(x => x.ServiceName == serviceName)
                : null;

            if (rateLimitOptions != null)
            {
                downstreamReRouteBuilder
                .WithRateLimitOptions(rateLimitOptions.RateLimitOptions)
                .WithEnableRateLimiting(true);
            }

            var downstreamReRoute = downstreamReRouteBuilder.Build();

            var reRoute = new ReRouteBuilder()
                          .WithDownstreamReRoute(downstreamReRoute)
                          .WithUpstreamHttpMethod(new List <string>()
            {
                upstreamHttpMethod
            })
                          .WithUpstreamPathTemplate(upstreamPathTemplate)
                          .Build();

            downstreamRoute = new OkResponse <DownstreamRoute>(new DownstreamRoute(new List <PlaceholderNameAndValue>(), reRoute));

            _cache.AddOrUpdate(loadBalancerKey, downstreamRoute, (x, y) => downstreamRoute);

            return(downstreamRoute);
        }
 private static bool ServiceFabricRequest(IInternalConfiguration config, DownstreamRoute downstreamRoute)
 {
     return(config.ServiceProviderConfiguration.Type?.ToLower() == "servicefabric" && downstreamRoute.UseServiceDiscovery);
 }
Ejemplo n.º 27
0
 public static void SetIInternalConfiguration(this IDictionary <object, object> input, IInternalConfiguration config)
 {
     input.Upsert("IInternalConfiguration", config);
 }
Ejemplo n.º 28
0
 private void GivenTheRoutes(List <Route> routes)
 {
     _config = new InternalConfiguration(routes, "", null, "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1"));
 }
 private void GivenTheFollowingConfig(IInternalConfiguration config)
 {
     _config = config;
     _downstreamContext.Configuration = config;
 }
 private void GivenTheConfigurationIs(IInternalConfiguration config)
 {
     _config = config;
 }