Exemplo n.º 1
0
        public Service ToService()
        {
            ServiceHostAndPort serviceHostAndPort = new ServiceHostAndPort(this.DownstreamHost, this.DownstreamPort, this.Scheme);
            var service = new Service(this.Name, serviceHostAndPort, this.Id, this.Version, this.Tags);

            return(service);
        }
Exemplo n.º 2
0
        private async Task <Uri> GetSwaggerUri(SwaggerEndPointConfig endPoint, RouteOptions route)
        {
            var conf = _configurationCreator.Create(_options.CurrentValue.GlobalConfiguration);

            var downstreamRoute = new DownstreamRouteBuilder()
                                  .WithUseServiceDiscovery(true)
                                  .WithServiceName(endPoint.Service.Name)
                                  .WithServiceNamespace(route?.ServiceNamespace)
                                  .Build();

            Response <IServiceDiscoveryProvider> serviceProvider = _serviceDiscovery.Get(conf, downstreamRoute);

            if (serviceProvider.IsError)
            {
                throw new InvalidOperationException(GetErrorMessage(endPoint));
            }

            ServiceHostAndPort service = (await serviceProvider.Data.Get()).FirstOrDefault()?.HostAndPort;

            if (service is null)
            {
                throw new InvalidOperationException(GetErrorMessage(endPoint));
            }

            var builder = new UriBuilder(GetScheme(service, route), service.DownstreamHost, service.DownstreamPort)
            {
                Path = endPoint.Service.Path
            };

            return(builder.Uri);
        }
Exemplo n.º 3
0
 private void GivenTheLoadBalancerReturns()
 {
     _hostAndPort = new ServiceHostAndPort("127.0.0.1", 80);
     _loadBalancer
     .Setup(x => x.Lease(It.IsAny <DownstreamContext>()))
     .ReturnsAsync(new OkResponse <ServiceHostAndPort>(_hostAndPort));
 }
        public async Task MarkAsBad(ServiceHostAndPort serviceHostAndPort)
        {
            var services = await _services();

            int i = services.FindIndex(p => p.HostAndPort.DownstreamHost == serviceHostAndPort.DownstreamHost && p.HostAndPort.DownstreamPort == serviceHostAndPort.DownstreamPort && p.HostAndPort.Scheme == serviceHostAndPort.Scheme);

            _failings[i] = services[i];
        }
Exemplo n.º 5
0
 private string GetScheme(ServiceHostAndPort service, RouteOptions route)
 => (route != null && !route.DownstreamScheme.IsNullOrEmpty())
     ? route.DownstreamScheme
     : !service.Scheme.IsNullOrEmpty()
     ? service.Scheme
     : service.DownstreamPort
 switch
 {
     443 => Uri.UriSchemeHttps,
Exemplo n.º 6
0
        public async Task <Response <ServiceHostAndPort> > Lease(HttpContext context)
        {
            // todo: consider using body lenght in job weight
            var bodyLength = context.Response.ContentLength;

            var dbContext = _serviceProvider.GetRequiredService <CsContext>();

            var servers = dbContext.Servers.ToDictionary(x => x, x => new List <JobTask>());

            foreach (var serverJobTask in dbContext.ServerJobTasks
                     .Where(x => !x.Task.EndTime.HasValue)
                     .Include(x => x.Server)
                     .Include(x => x.Task))
            {
                servers[serverJobTask.Server].Add(serverJobTask.Task);
            }


            var server = await ChooseServer(servers) ?? dbContext.Servers.FirstOrDefault();

            var data = GetRequestId();

            var type = GetRequestType(context);
            var task = new JobTask()
            {
                StartTime = DateTime.Now,
                Type      = type,
                RequestId = data,
            };
            var link = new ServerJobTask
            {
                Task   = task,
                Server = server,
            };

            await dbContext.Tasks.AddAsync(task);

            await dbContext.ServerJobTasks.AddAsync(link);

            await dbContext.SaveChangesAsync();

            await Task.Delay(5000);


            var hostAndPort = new ServiceHostAndPort(server.Host, server.Port, server.Scheme);

            var message = $"in {hostAndPort.Scheme}://{hostAndPort.DownstreamHost}: {hostAndPort.DownstreamPort}";

            _logger.LogInformation(message);


            var result = new OkResponse <ServiceHostAndPort>(hostAndPort);

            return(result);
        }
Exemplo n.º 7
0
        public void should_return_error_if_services_are_empty()
        {
            var serviceName = "products";

            var hostAndPort = new ServiceHostAndPort("localhost", 80);

            this.Given(x => x.GivenAHostAndPort(hostAndPort))
            .And(x => x.GivenTheLoadBalancerStarts(new List <Service>(), serviceName))
            .When(x => x.WhenIGetTheNextHostAndPort())
            .Then(x => x.ThenServiceAreEmptyErrorIsReturned())
            .BDDfy();
        }
Exemplo n.º 8
0
        public void should_return_host_and_port()
        {
            var hostAndPort = new ServiceHostAndPort("127.0.0.1", 80);

            var services = new List <Service>
            {
                new Service("product", hostAndPort, string.Empty, string.Empty, new string[0])
            };

            this.Given(x => x.GivenServices(services))
            .When(x => x.WhenIGetTheNextHostAndPort())
            .Then(x => x.ThenTheHostAndPortIs(hostAndPort))
            .BDDfy();
        }
        public void should_return_services()
        {
            var hostAndPort = new ServiceHostAndPort("127.0.0.1", 80);

            var services = new List <Service>
            {
                new Service("product", hostAndPort, string.Empty, string.Empty, new string[0])
            };

            this.Given(x => x.GivenServices(services))
            .When(x => x.WhenIGetTheService())
            .Then(x => x.ThenTheFollowingIsReturned(services))
            .BDDfy();
        }
Exemplo n.º 10
0
        public void should_return_error_if_no_services_then_when_services_available_return_host_and_port()
        {
            var hostAndPort = new ServiceHostAndPort("127.0.0.1", 80);

            var services = new List <Service>
            {
                new Service("product", hostAndPort, string.Empty, string.Empty, new string[0])
            };

            this.Given(_ => WhenIGetTheNextHostAndPort())
            .And(_ => ThenThereIsAnError())
            .And(_ => GivenServices(services))
            .When(_ => WhenIGetTheNextHostAndPort())
            .Then(_ => ThenTheHostAndPortIs(hostAndPort))
            .BDDfy();
        }
Exemplo n.º 11
0
        public void should_get_next_url()
        {
            var serviceName = "products";

            var hostAndPort = new ServiceHostAndPort("localhost", 80);

            var availableServices = new List <Service>
            {
                new Service(serviceName, hostAndPort, string.Empty, string.Empty, new string[0])
            };

            this.Given(x => x.GivenAHostAndPort(hostAndPort))
            .And(x => x.GivenTheLoadBalancerStarts(availableServices, serviceName))
            .When(x => x.WhenIGetTheNextHostAndPort())
            .Then(x => x.ThenTheNextHostAndPortIsReturned())
            .BDDfy();
        }
Exemplo n.º 12
0
        public void Release(ServiceHostAndPort hostAndPort)
        {
            lock (_syncLock)
            {
                var matchingLease = _leases.FirstOrDefault(l => l.HostAndPort.DownstreamHost == hostAndPort.DownstreamHost &&
                                                           l.HostAndPort.DownstreamPort == hostAndPort.DownstreamPort);

                if (matchingLease != null)
                {
                    var replacementLease = new Lease(hostAndPort, matchingLease.Connections - 1);

                    _leases.Remove(matchingLease);

                    _leases.Add(replacementLease);
                }
            }
        }
Exemplo n.º 13
0
        public void Release(ServiceHostAndPort hostAndPort)
        {
            var dbContext     = _serviceProvider.GetRequiredService <CsContext>();
            var requestScoped = _serviceProvider.GetRequiredService <IRequestScopedDataRepository>();
            var data          = requestScoped.Get <string>("RequestId").Data;


            var jobTask = dbContext
                          .ServerJobTasks
                          .Include(x => x.Task)
                          .Include(x => x.Server)
                          .FirstOrDefault(x => x.Task.RequestId == data);

            if (jobTask != null)
            {
                jobTask.Task.EndTime = DateTime.Now;
                dbContext.SaveChanges();
            }

            _logger.LogInformation(
                $"release: {hostAndPort.Scheme}://{hostAndPort.DownstreamHost}: {hostAndPort.DownstreamPort}");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Parse string to WeightServiceHostAndPort list,
        /// exp: 127.0.0.1:100-3,127.0.0.2:101-2,127.0.0.3:102-5
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static List <WeightServiceHostAndPort> ConvertToWeightHostAndPorts(string value)
        {
            var weightHostAndPorts = new List <WeightServiceHostAndPort>();

            if (value.IsNullOrWhiteSpace())
            {
                return(weightHostAndPorts);
            }

            foreach (var item in value.Split(','))
            {
                var valueArray       = item.Split('-');
                var weight           = int.Parse(valueArray[1]);
                var hostAndPortArray = valueArray[0].Split(':');

                var serviceHostAndPort = new ServiceHostAndPort(hostAndPortArray[0], int.Parse(hostAndPortArray[1]));

                var weightServiceHostAndPort = new WeightServiceHostAndPort(serviceHostAndPort, weight);
                weightHostAndPorts.Add(weightServiceHostAndPort);
            }

            return(weightHostAndPorts);
        }
Exemplo n.º 15
0
 public void Release(ServiceHostAndPort hostAndPort)
 {
     // Not relevant for these tests
     throw new NotImplementedException();
 }
Exemplo n.º 16
0
 public StickySession(ServiceHostAndPort hostAndPort, DateTime expiry, string key)
 {
     HostAndPort = hostAndPort;
     Expiry      = expiry;
     Key         = key;
 }
Exemplo n.º 17
0
        public Response <DownstreamUrl> Build(string downstreamPath, string downstreamScheme, ServiceHostAndPort downstreamHostAndPort)
        {
            if (string.IsNullOrEmpty(downstreamPath))
            {
                return(new ErrorResponse <DownstreamUrl>(new List <Error> {
                    new DownstreamPathNullOrEmptyError()
                }));
            }

            if (string.IsNullOrEmpty(downstreamScheme))
            {
                return(new ErrorResponse <DownstreamUrl>(new List <Error> {
                    new DownstreamSchemeNullOrEmptyError()
                }));
            }

            if (string.IsNullOrEmpty(downstreamHostAndPort.DownstreamHost))
            {
                return(new ErrorResponse <DownstreamUrl>(new List <Error> {
                    new DownstreamHostNullOrEmptyError()
                }));
            }


            var builder = new UriBuilder
            {
                Host   = downstreamHostAndPort.DownstreamHost,
                Path   = downstreamPath,
                Scheme = downstreamScheme
            };

            if (downstreamHostAndPort.DownstreamPort > 0)
            {
                builder.Port = downstreamHostAndPort.DownstreamPort;
            }

            var url = builder.Uri.ToString();

            return(new OkResponse <DownstreamUrl>(new DownstreamUrl(url)));
        }
Exemplo n.º 18
0
 public WeightServiceHostAndPort(ServiceHostAndPort hostAndPort, int weight)
 {
     HostAndPort = hostAndPort;
     Weight      = weight;
 }
Exemplo n.º 19
0
 public Lease(ServiceHostAndPort hostAndPort, int connections)
 {
     HostAndPort = hostAndPort;
     Connections = connections;
 }
Exemplo n.º 20
0
 public StickySession(ServiceHostAndPort hostAndPort, DateTime expiry)
 {
     HostAndPort = hostAndPort;
     Expiry      = expiry;
 }
Exemplo n.º 21
0
 private void GivenAHostAndPort(ServiceHostAndPort hostAndPort)
 {
     _hostAndPort = hostAndPort;
 }
Exemplo n.º 22
0
        private void GivenIHackAMessageInWithAPastExpiry()
        {
            var hostAndPort = new ServiceHostAndPort("999", 999);

            _bus.Publish(new StickySession(hostAndPort, DateTime.UtcNow.AddDays(-1), "321"), 0);
        }
Exemplo n.º 23
0
 public void Release(ServiceHostAndPort hostAndPort)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 24
0
 private void ThenTheHostAndPortIs(ServiceHostAndPort expected)
 {
     _result.Data.ShouldBe(expected);
 }
Exemplo n.º 25
0
 public void Release(ServiceHostAndPort hostAndPort)
 {
 }
Exemplo n.º 26
0
 public void Release(ServiceHostAndPort hostAndPort)
 {
     //Ocelot.Responder.Middleware.ResponderMiddleware
 }