Example #1
0
        public async Task OneHostHasNetworkErrorShouldMoveToNextHost()
        {
            var port = DisposablePort.GetPort().Port;
            var dict = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "host1,host2" },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() }
            };

            int counter = 0;
            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https")
                    {
                        throw new HttpRequestException();
                    }

                    counter++;

                    if (req.RequestUri.Host == "host1")
                    {
                        throw new HttpRequestException();
                    }
                    return(HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"));
                });
                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            }, dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;
                TracingContext.SetRequestID("1");

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                for (int i = 0; i < 3; i++)
                {
                    var server = await serviceProxy.Invoke(request, typeof(string));

                    server.ShouldBe("host2");
                }

                counter.ShouldBe(3);
            }
        }
 public virtual void SetUp()
 {
     unitTesting = new TestingKernel <ConsoleLog>(mockConfig: MockConfig);
     Metric.ShutdownContext(ServiceProxyProvider.METRICS_CONTEXT_NAME);
     TracingContext.SetUpStorage();
     TracingContext.SetRequestID("1");
 }
        /// <summary>
        /// Retrieves the next reachable <see cref="RemoteHost"/>.
        /// </summary>
        /// <param name="affinityToken">
        /// A string to generate a consistent affinity to a specific host within the set of available hosts.
        /// Identical strings will return the same host for a given pool of reachable hosts. A request ID is usually provided.
        /// </param>
        /// <returns>A reachable <see cref="RemoteHost"/>.</returns>
        /// <exception cref="EnvironmentException">Thrown when there is no reachable <see cref="RemoteHost"/> available.</exception>
        public IEndPointHandle GetNextHost(string affinityToken = null)
        {
            LastEndpointRequest = DateTime.UtcNow;

            var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);

            if (hostOverride != null)
            {
                return(new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Hostname, hostOverride.Port ?? GetConfig().DefaultPort));
            }

            lock (_lock)
            {
                Health.Activate();

                if (ReachableHosts.Count == 0)
                {
                    var lastExceptionEndPoint = UnreachableHosts.FirstOrDefault();

                    // TODO: Exception throwing code should be in this class, not in another.
                    throw DiscoverySource.AllEndpointsUnreachable(EndPointsResult, lastExceptionEndPoint?.LastException, lastExceptionEndPoint == null ? null : $"{lastExceptionEndPoint.HostName}:{lastExceptionEndPoint.Port}", string.Join(", ", UnreachableHosts));
                }

                Counter++;

                ulong hostId = affinityToken == null ? Counter : (ulong)affinityToken.GetHashCode();

                return(ReachableHosts[(int)(hostId % (ulong)ReachableHosts.Count)]);
            }
        }
        public async Task <IEndPointHandle> GetOrWaitForNextHost(CancellationToken cancellationToken)
        {
            var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);

            if (hostOverride != null)
            {
                return(new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Hostname, hostOverride.Port ?? GetConfig().DefaultPort));
            }

            if (ReachableHosts.Count > 0)
            {
                return(GetNextHost());
            }

            lock (_lock)
            {
                if (FirstAvailableHostCompletionSource == null)
                {
                    FirstAvailableHostCompletionSource = new TaskCompletionSource <RemoteHost>();
                }

                cancellationToken.Register(() => FirstAvailableHostCompletionSource?.SetCanceled());
            }

            return(await FirstAvailableHostCompletionSource.Task.ConfigureAwait(false));
        }
        public async Task Setup()
        {
            IDiscovery discovery = Substitute.For <IDiscovery>();

            _discoveryConfig = new DiscoveryConfig {
                Services = new ServiceDiscoveryCollection(new Dictionary <string, ServiceDiscoveryConfig>(), new ServiceDiscoveryConfig(), new PortAllocationConfig())
            };

            Dictionary <string, string> configDic = new Dictionary <string, string>();

            _currentEnvironment = Prod;
            var environment = Substitute.For <IEnvironment>();

            environment.DeploymentEnvironment.Returns(_ => _currentEnvironment);
            _unitTestingKernel = new TestingKernel <ConsoleLog>(mockConfig: configDic);
            _unitTestingKernel.Rebind <IEnvironment>().ToConstant(environment);
            _unitTestingKernel.Rebind <IDiscovery>().ToConstant(discovery);
            _unitTestingKernel.Rebind <Func <DiscoveryConfig> >().ToMethod(_ => () => _discoveryConfig);

            _loadBalancerByEnvironment = new Dictionary <string, ILoadBalancer>();
            _loadBalancerByEnvironment.Add(Prod, new MasterLoadBalancer());
            _loadBalancerByEnvironment.Add(Staging, new StagingLoadBalancer());
            _loadBalancerByEnvironment.Add(Canary, new PreferredEnvironmentLoadBalancer());
            discovery.CreateLoadBalancer(Arg.Any <DeploymentIdentifier>(), Arg.Any <ReachabilityCheck>(), TrafficRoutingStrategy.RandomByRequestID)
            .ReturnsForAnyArgs(c => _loadBalancerByEnvironment[c.Arg <DeploymentIdentifier>().DeploymentEnvironment]);
            _serviceDiscovery = _unitTestingKernel.Get <Func <string, ReachabilityCheck, IMultiEnvironmentServiceDiscovery> >()(ServiceName, (x, y) => new Task(null));

            TracingContext.SetPreferredEnvironment(null);
        }
        public virtual void SetUp()
        {
            _testinghost = new NonOrleansServiceTester <ConfigurableHost <IDemoService> >();

            //    Metric.Context("Service");
            TracingContext.SetRequestID("1");
        }
 public virtual void SetUp()
 {
     _testinghost    = new NonOrleansServiceTester <TestingHost <IDemoService> >();
     _insecureClient = _testinghost.GetServiceProxy <IDemoService>();
     Metric.ShutdownContext("Service");
     TracingContext.SetRequestID("1");
 }
Example #8
0
        public async Task RequestContextShouldOverrideHostOnly()
        {
            const string serviceName = "DemoService";
            int          defaultPort = DisposablePort.GetPort().Port;

            var dict = new Dictionary <string, string> {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            var kernel          = new TestingKernel <ConsoleLog>(k => k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope(), dict);
            var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
            var serviceProxy    = providerFactory(serviceName);

            var messageHandler = new MockHttpMessageHandler();

            messageHandler
            .When("*")
            .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}:{req.RequestUri.Port}'"));
            string overrideHost = "override-host";

            serviceProxy.HttpMessageHandler = messageHandler;

            TracingContext.SetHostOverride(serviceName, overrideHost);

            var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

            for (int i = 0; i < 50; i++)
            {
                var host = (string)await serviceProxy.Invoke(request, typeof(string));

                host.ShouldBe($"{overrideHost}:{defaultPort}");
            }
        }
Example #9
0
        public async Task MemoizeAsync_MultipleFailingCallsWithSuppressCaching_ThrowExceptionForEachSuppressedCacheCallAndReturnCachedValueForNonSuppressedCachedCalls()
        {
            string firstValue  = "first Value";
            var    refreshTask = new TaskCompletionSource <Thing>();
            var    dataSource  = CreateDataSource(firstValue, refreshTask);
            var    memoizer    = CreateMemoizer(CreateCache());

            using (TracingContext.SuppressCaching(CacheSuppress.RecursiveAllDownstreamServices))
            {
                //Cache result for a successful call
                var actual = await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, new object[] { "someString" }, GetPolicy()); //1 call to data source
                actual.Id.ShouldBe(firstValue);

                //Should throw for each call to the data source
                refreshTask.SetException(new Exception("Boo!!"));

                //because we are in SuppressCaching using block, all calls will try to go to data source and fail
                for (int i = 0; i < 10; i++) //10 calls to data source
                {
                    var task = (Task <Thing>)memoizer.Memoize(dataSource, ThingifyTaskThing, new object[] { "someString" }, GetPolicy());
                    task.ShouldThrow <EnvironmentException>();
                }
            }

            for (int i = 0; i < 5; i++)
            {
                //We are not in SuppressCaching using block, get cached result (NOT FROM DATA SOURCE)
                var value = await(Task <Thing>) memoizer.Memoize(dataSource, ThingifyTaskThing, new object[] { "someString" }, GetPolicy()); //should not call data source
                value.Id.ShouldBe(firstValue);
            }

            //We have total of 11 calls to data source: first one which cached the result, another failing 10 under SuppressCaching using block
            dataSource.Received(11).ThingifyTaskThing("someString");
        }
Example #10
0
        public async Task <RemoteHost> GetOrWaitForNextHost(CancellationToken cancellationToken)
        {
            var hostOverride = TracingContext.GetHostOverride(ServiceDeployment.ServiceName);

            if (hostOverride != null)
            {
                return(new OverriddenRemoteHost(ServiceDeployment.ServiceName, hostOverride, this));
            }

            if (ReachableHosts.Count > 0)
            {
                return(GetNextHost());
            }

            lock (_lock)
            {
                if (FirstAvailableHostCompletionSource == null)
                {
                    FirstAvailableHostCompletionSource = new TaskCompletionSource <RemoteHost>();
                }

                cancellationToken.Register(() => FirstAvailableHostCompletionSource?.SetCanceled());
            }

            return(await FirstAvailableHostCompletionSource.Task.ConfigureAwait(false));
        }
Example #11
0
        public async Task ServiceProxyRpcMessageShouldRemainSame()
        {
            const string serviceName = "DemoService";
            int          defaultPort = DisposablePort.GetPort().Port;
            var          dict        = new Dictionary <string, string>
            {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            Uri    uri            = null;
            string requestMessage = null;

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*").Respond(async req =>
                {
                    requestMessage = await req.Content.ReadAsStringAsync();
                    uri            = req.RequestUri;
                    return(HttpResponseFactory.GetResponse(HttpStatusCode.Accepted));
                });
                return(messageHandler);
            };

            using (var kernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            }, dict))
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();

                TracingContext.SetRequestID("g");

                var serviceProxy = providerFactory(serviceName);

                string expectedHost = "override-host";
                int    expectedPort = DisposablePort.GetPort().Port;

                TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort);

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());
                using (TracingContext.Tags.SetUnencryptedTag("test", 1))
                    await serviceProxy.Invoke(request, typeof(string));
                var body = requestMessage;
                Console.WriteLine($"error: {body}");

                JsonConvert.DeserializeObject <GigyaRequestProtocol>(body, new JsonSerializerSettings()
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                });


                uri.Host.ShouldBe(expectedHost);
                uri.Port.ShouldBe(expectedPort);
            }
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            bool isOrleansGrain = context.InterfaceMethod == null || context.InterfaceMethod.DeclaringType == null || context.InterfaceMethod.Module.Assembly.FullName.StartsWith("Orleans");
            //TODO add test that validate that we are not introducing new grain in micro dot
            bool isMicrodotGrain = isOrleansGrain == false && context.InterfaceMethod.DeclaringType.Name == nameof(IRequestProcessingGrain);
            bool isServiceGrain  = isOrleansGrain == false && isMicrodotGrain == false;

            var grainTags = new Lazy <GrainTags>(() => new GrainTags(context));
            // Drop the request if we're overloaded
            var loadSheddingConfig = _loadSheddingConfig();

            if (
                (loadSheddingConfig.ApplyToMicrodotGrains && isMicrodotGrain) ||
                (loadSheddingConfig.ApplyToServiceGrains && isServiceGrain)
                )
            {
                //Can brake the flow by throwing Overloaded
                RejectRequestIfLateOrOverloaded(grainTags);
            }
            var loggingConfig = _grainLoggingConfig();

            bool shouldLog = (loggingConfig.LogOrleansGrains && isOrleansGrain) ||
                             (loggingConfig.LogMicrodotGrains && isMicrodotGrain) ||
                             (loggingConfig.LogServiceGrains && isServiceGrain);

            shouldLog = shouldLog && !ShouldSkipLoggingUnderRatio(loggingConfig, TracingContext.TryGetRequestID());
            GrainCallEvent grainEvent = null;

            if (shouldLog)
            {
                RequestTimings.GetOrCreate(); // Ensure request timings is created here and not in the grain call.
                RequestTimings.Current.Request.Start();
                grainEvent = _eventPublisher.CreateEvent();

                grainEvent.ParentSpanId = TracingContext.TryGetParentSpanID();
                grainEvent.SpanId       = Guid.NewGuid().ToString("N");
                TracingContext.SetParentSpan(grainEvent.SpanId);
            }

            Exception ex = null;

            try
            {
                await context.Invoke();
            }
            catch (Exception e)
            {
                ex = e;
                throw;
            }
            finally
            {
                if (shouldLog)
                {
                    RequestTimings.Current.Request.Stop();
                    PublishEvent(ex, grainTags, grainEvent);
                }
            }
        }
        //   private readonly UserManager<ApplicationUser> _userManager;


        //  Guid CurrentGuid;

        public BusinessesController(
            TracingContext context
            //      UserManager<ApplicationUser> userManager
            )
        {
            _context = context;
            //      _userManager = userManager;
        }
Example #14
0
        ///<inheritdoc />
        public async Task <NodeAndLoadBalancer> GetNode()
        {
            _lastUsageTime = DateTime.UtcNow;
            NodeAndLoadBalancer nodeAndLoadBalancer = null;
            string preferredEnvironment             = TracingContext.GetPreferredEnvironment();

            // 1. Use explicit host override if provided in request
            //    TBD: Theoretically if we only ever call a service through host overrides we might not have a health check for the service at all (though it is in use)
            var hostOverride = TracingContext.GetHostOverride(ServiceName);

            if (hostOverride != null)
            {
                return new NodeAndLoadBalancer {
                           Node                 = new Node(hostOverride.Host, hostOverride.Port),
                           LoadBalancer         = null,
                           PreferredEnvironment = preferredEnvironment ?? Environment.DeploymentEnvironment,
                }
            }
            ;

            // 2. Otherwise, use preferred environment if provided in request
            if (preferredEnvironment != null && (nodeAndLoadBalancer = await GetNodeAndLoadBalancer(preferredEnvironment, preferredEnvironment)) != null)
            {
                return(nodeAndLoadBalancer);
            }

            // 3. Otherwise, try use current environment
            if ((nodeAndLoadBalancer = await GetNodeAndLoadBalancer(Environment.DeploymentEnvironment, preferredEnvironment)) != null)
            {
                _healthStatus = new HealthMessage(Health.Healthy, message: null, suppressMessage: true); // No need for a health message since the load balancer we're returning already provides one
                return(nodeAndLoadBalancer);
            }

            // 4. We're in prod env and service is not deployed, no fallback possible
            if (Environment.DeploymentEnvironment == MASTER_ENVIRONMENT)
            {
                _healthStatus = new HealthMessage(Health.Unhealthy, "Service not deployed");
                throw ServiceNotDeployedException();
            }

            // 5. We're not in prod, but fallback to prod is disabled
            if (GetDiscoveryConfig().EnvironmentFallbackEnabled == false)
            {
                _healthStatus = new HealthMessage(Health.Unhealthy, "Service not deployed (and fallback to prod disabled)");
                throw ServiceNotDeployedException();
            }

            // 6. Otherwise, try fallback to prod
            if ((nodeAndLoadBalancer = await GetNodeAndLoadBalancer(MASTER_ENVIRONMENT, preferredEnvironment ?? Environment.DeploymentEnvironment)) != null)
            {
                _healthStatus = new HealthMessage(Health.Healthy, "Service not deployed, falling back to prod");
                return(nodeAndLoadBalancer);
            }

            _healthStatus = new HealthMessage(Health.Unhealthy, "Service not deployed, fallback to prod enabled but service not deployed in prod either");
            throw ServiceNotDeployedException();
        }
Example #15
0
        public virtual void SetUp()
        {
            _insecureClient      = _kernel.Get <IDemoService>();
            _exceptionSerializer = _kernel.Get <JsonExceptionSerializer>();

            Metric.ShutdownContext("Service");
            TracingContext.SetUpStorage();
            TracingContext.SetRequestID("1");

            _testinghost = new TestingHost <IDemoService>();
            _stopTask    = _testinghost.RunAsync(new ServiceArguments(ServiceStartupMode.CommandLineNonInteractive));
        }
Example #16
0
        public void SetUp()
        {
            Metric.ShutdownContext("Service");

            TracingContext.SetUpStorage();
            TracingContext.SetRequestID("1");


            var kernel = new TestingKernel <ConsoleLog>();

            _proxyInstance = kernel.Get <IDemoService>();
        }
        public async Task GotServiceFromPreferredEnvironment()
        {
            TracingContext.SetPreferredEnvironment(Canary);

            var node = await _serviceDiscovery.GetNode();

            Assert.IsInstanceOf <PreferredEnvironmentLoadBalancer>(node.LoadBalancer);
            Assert.AreEqual(node.Node.Hostname, CanaryHost);

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsTrue(hResult.IsHealthy);
        }
        public virtual void SetUp()
        {
            var kernel = new TestingKernel<ConsoleLog>();
            _insecureClient = kernel.Get<IDemoService>();
            _exceptionSerializer = kernel.Get<JsonExceptionSerializer>();

            Metric.ShutdownContext("Service");
            TracingContext.SetUpStorage();
            TracingContext.SetRequestID("1");

            _testinghost = new TestingHost<IDemoService>();
            _stopTask = _testinghost.RunAsync();
        }
Example #19
0
        public async Task RequestContextOverrideShouldFailOnFirstAttempt()
        {
            var port = DisposablePort.GetPort().Port;
            var dict = new Dictionary <string, string>
            {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "notImpotent" },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() }
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k => k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope(), dict)
                   )
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;

                //Disable  TracingContext.SetRequestID("1");

                CallContext.FreeNamedDataSlot("#ORL_RC");

                int counter        = 0;
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req =>
                {
                    counter++;

                    throw new HttpRequestException();
                });


                string overrideHost = "override-host";
                int    overridePort = 5318;
                TracingContext.SetHostOverride("DemoService", overrideHost, overridePort);
                serviceProxy.HttpMessageHandler = messageHandler;

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());

                for (int i = 0; i < 3; i++)
                {
                    Func <Task> act = () => serviceProxy.Invoke(request, typeof(string));

                    await act.ShouldThrowAsync <HttpRequestException>();
                }
                counter.ShouldBe(3);
            }
        }
Example #20
0
        // private readonly UserManager<ApplicationUser> _userManager;


        public TrackersController(TracingContext context, ILogger <TrackersController> logger,
                                  IWebHostEnvironment env,
                                  IHttpContextAccessor httpacc,
                                  ICookieService cookieService
                                  //      UserManager<ApplicationUser> userManager
                                  )
        {
            _context       = context;
            _logger        = logger;
            _env           = env;
            _httpacc       = httpacc;
            _cookieService = cookieService;
            //  _userManager = userManager;
        }
Example #21
0
        private uint GetIndexByTrafficRoutingStrategy()
        {
            switch (TrafficRoutingStrategy)
            {
            case TrafficRoutingStrategy.RoundRobin:
                return((uint)Interlocked.Increment(ref _roundRobinIndex));

            case TrafficRoutingStrategy.RandomByRequestID:
                return((uint?)TracingContext.TryGetRequestID()?.GetHashCode() ?? (uint)Interlocked.Increment(ref _roundRobinIndex));

            default:
                throw new ProgrammaticException($"The {nameof(TrafficRoutingStrategy)} '{TrafficRoutingStrategy}' is not supported by LoadBalancer.");
            }
        }
Example #22
0
        public async Task AllRequestsForSameCallID_SameHostSelected()
        {
            var port = DisposablePort.GetPort().Port;
            var dict = new Dictionary <string, string> {
                { "Discovery.Services.DemoService.Source", "Config" },
                { "Discovery.Services.DemoService.Hosts", "host1,host2" },
                { "Discovery.Services.DemoService.DefaultPort", port.ToString() }
            };

            Func <HttpClientConfiguration, HttpMessageHandler> messageHandlerFactory = _ =>
            {
                var messageHandler = new MockHttpMessageHandler();
                messageHandler
                .When("*")
                .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"));
                return(messageHandler);
            };

            using (var kernel =
                       new TestingKernel <ConsoleLog>(
                           k =>
            {
                k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope();
                k.Rebind <Func <HttpClientConfiguration, HttpMessageHandler> >().ToMethod(c => messageHandlerFactory);
            },
                           dict))
            {
                var providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var serviceProxy    = providerFactory("DemoService");
                serviceProxy.DefaultPort = port;

                //If we set Request Id we would like always to select same Host
                TracingContext.SetRequestID("dumyId1");
                var request        = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());
                var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string));

                string host;
                for (int i = 0; i < 50; i++)
                {
                    host = (string)await serviceProxy.Invoke(request, typeof(string));

                    host.ShouldBe(hostOfFirstReq);
                }

                TracingContext.SetRequestID("dumyId2");
                host = (string)await serviceProxy.Invoke(request, typeof(string));

                host.ShouldNotBe(hostOfFirstReq);
            }
        }
Example #23
0
        public async Task FallbackFromPreferredToMasterEnvironment()
        {
            _loadBalancerByEnvironment[Canary] = ServiceUndeployedLoadBalancer();

            TracingContext.SetPreferredEnvironment(Canary);

            var node = await _serviceDiscovery.GetNode();

            Assert.IsInstanceOf <MasterLoadBalancer>(node.LoadBalancer);
            Assert.AreEqual(node.Node.Hostname, ProdHost);

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsTrue(hResult.IsHealthy);
        }
        public async Task FallbackFromPreferredToMasterEnvironment()
        {
            _loadBalancerByEnvironment[Canary] = ServiceUndeployedLoadBalancer();

            _discoveryConfig.EnvironmentFallbackEnabled = true; // Even for preferred environmet, fallback is performed only if fallback is enabled

            TracingContext.SetPreferredEnvironment(Canary);

            var node = await _serviceDiscovery.GetNode();

            Assert.IsInstanceOf <MasterLoadBalancer>(node.LoadBalancer);
            Assert.AreEqual(node.Node.Hostname, ProdHost);

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsTrue(hResult.IsHealthy);
        }
        public async Task ServiceDiscoveryFlowAllDeployedwithoutOverrides()
        {
            _currentEnvironment = Staging;

            _discoveryConfig.EnvironmentFallbackEnabled = true;

            TracingContext.SetPreferredEnvironment(Canary);

            var node = await _serviceDiscovery.GetNode();

            Assert.IsInstanceOf <PreferredEnvironmentLoadBalancer>(node.LoadBalancer);
            Assert.AreEqual(node.Node.Hostname, CanaryHost);

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsTrue(hResult.IsHealthy);
        }
        public async Task FallbackFromPreferredToCurrentEnvironment()
        {
            _currentEnvironment = Staging;
            _loadBalancerByEnvironment[Canary] = ServiceUndeployedLoadBalancer();

            _discoveryConfig.EnvironmentFallbackEnabled = true;

            TracingContext.SetPreferredEnvironment(Canary);

            var node = await _serviceDiscovery.GetNode();

            Assert.IsInstanceOf <StagingLoadBalancer>(node.LoadBalancer);
            Assert.AreEqual(node.Node.Hostname, StagingHost);

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsTrue(hResult.IsHealthy);
        }
Example #27
0
        private async Task <HttpServiceRequest> ParseRequest(HttpListenerContext context)
        {
            var request = await _deserializationTime.Time(async() =>
            {
                using (var streamReader = new StreamReader(context.Request.InputStream))
                {
                    var json = await streamReader.ReadToEndAsync();
                    return(JsonConvert.DeserializeObject <HttpServiceRequest>(json, JsonSettings));
                }
            });

            request.TracingData           = request.TracingData ?? new TracingData();
            request.TracingData.RequestID = request.TracingData.RequestID ?? Guid.NewGuid().ToString("N");

            TracingContext.SetRequestID(request.TracingData.RequestID);
            TracingContext.SetSpan(request.TracingData.SpanID, request.TracingData.ParentSpanID);
            return(request);
        }
Example #28
0
        public async Task RequestContextShouldOverridePortAndHost()
        {
            const string serviceName = "DemoService";
            const int    defaultPort = 5555;
            var          dict        = new Dictionary <string, string>
            {
                { $"Discovery.Services.{serviceName}.Source", "Config" },
                { $"Discovery.Services.{serviceName}.Hosts", "host1" },
                { $"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString() }
            };

            using (var kernel = new TestingKernel <ConsoleLog>(k => k.Rebind <IDiscovery>().To <ServiceDiscovery.Rewrite.Discovery>().InSingletonScope(), dict))
            {
                var    providerFactory = kernel.Get <Func <string, ServiceProxyProvider> >();
                var    serviceProxy    = providerFactory(serviceName);
                Uri    uri             = null;
                string requestMessage  = null;
                var    messageHandler  = new MockHttpMessageHandler();
                messageHandler
                .When("*").Respond(async req =>
                {
                    requestMessage = await req.Content.ReadAsStringAsync();
                    uri            = req.RequestUri;
                    return(HttpResponseFactory.GetResponse(HttpStatusCode.Accepted));
                });

                serviceProxy.HttpMessageHandler = messageHandler;
                string expectedHost = "override-host";
                int    expectedPort = 5318;

                TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort);

                var request = new HttpServiceRequest("testMethod", null, new Dictionary <string, object>());
                await serviceProxy.Invoke(request, typeof(string));

                var body = requestMessage;
                JsonConvert.DeserializeObject <GigyaRequestProtocol>(body, new JsonSerializerSettings()
                {
                    MissingMemberHandling = MissingMemberHandling.Error
                });
                uri.Host.ShouldBe(expectedHost);
                uri.Port.ShouldBe(expectedPort);
            }
        }
        public void ServiceDiscoveryFlowNoServiceDeployed()
        {
            _currentEnvironment = Staging;

            _loadBalancerByEnvironment[Prod]    = ServiceUndeployedLoadBalancer();
            _loadBalancerByEnvironment[Staging] = ServiceUndeployedLoadBalancer();
            _loadBalancerByEnvironment[Canary]  = ServiceUndeployedLoadBalancer();

            _discoveryConfig.EnvironmentFallbackEnabled = true;

            TracingContext.SetPreferredEnvironment(Canary);

            _serviceDiscovery.GetNode().ShouldThrow <ServiceUnreachableException>();

            HealthCheckResult hResult = GetHealthResult();

            Assert.IsFalse(hResult.IsHealthy);
            Assert.IsTrue(hResult.Message.Contains("Service not deployed, fallback to prod enabled but service not deployed in prod either"));
        }
Example #30
0
        public async Task SingleGrainCall_CallSucceeds_PublishesEvent()
        {
            _flumeQueue.Clear();

            var requestId = nameof(SingleGrainCall_CallSucceeds_PublishesEvent) + Guid.NewGuid();

            TracingContext.SetRequestID(requestId);
            TracingContext.TryGetRequestID();

            await _serviceProxy.Add(5, 3);


            var events   = _flumeQueue.Events;
            var grainReq = events.Where(r => r.EventType == "grainReq")
                           .Select(r => (GrainCallEvent)r)
                           .Single(r => r.TargetType == typeof(CalculatorServiceGrain).FullName);

            Assert.AreEqual("Add", grainReq.TargetMethod);
            Assert.AreEqual(requestId, grainReq.RequestId);
        }
Example #31
0
        public void Initialize()
        {
            DokanOperationsFixture.InitInstance();

            context = new TracingContext(this);
        }