コード例 #1
0
 private static void AssertOneDefaultEndpoint(EndPointsResult result)
 {
     result.EndPoints.Length.ShouldBe(1);
     result.EndPoints[0].HostName.ShouldBe(Host1);
     result.EndPoints[0].Port.ShouldBe(Port1);
     result.ActiveVersion.ShouldBe(Version);
 }
コード例 #2
0
        /// <summary>
        /// Loads the specified settings, overwriting existing settings.
        /// </summary>
        /// <param name="updatedEndPointsResult"></param>
        /// this <see cref="RemoteHostPool"/>.
        /// <exception cref="ArgumentNullException">Thrown when </exception>
        /// <exception cref="EnvironmentException"></exception>
        private void ReloadEndpoints(EndPointsResult updatedEndPointsResult)
        {
            lock (_lock)
            {
                try
                {
                    var updatedEndPoints = updatedEndPointsResult.EndPoints;
                    if (updatedEndPoints.Any() == false)
                    {
                        Health.SetHealthFunction(() =>
                        {
                            var config = GetConfig();
                            if (IsHealthCheckSuppressed(config))
                            {
                                return(HealthCheckResult.Healthy($"No endpoints were discovered from source '{config.Source}' but the remote service was not in use for more than {config.SuppressHealthCheckAfterServiceUnused?.TotalSeconds} seconds."));
                            }
                            else
                            {
                                return(HealthCheckResult.Unhealthy($"No endpoints were discovered from source '{config.Source}'."));
                            }
                        });

                        EndPointsResult = updatedEndPointsResult;

                        ReachableHosts   = new List <RemoteHost>();
                        UnreachableHosts = new List <RemoteHost>();
                    }
                    else
                    {
                        if (EndPoints != null)
                        {
                            foreach (var removedEndPoint in EndPoints.Except(updatedEndPoints))
                            {
                                ReachableHosts.SingleOrDefault(h => h.Equals(removedEndPoint))?.StopMonitoring();
                                ReachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
                                UnreachableHosts.RemoveAll(h => h.Equals(removedEndPoint));
                            }
                        }

                        var newHosts = updatedEndPoints
                                       .Except(EndPoints ?? Enumerable.Empty <EndPoint>())
                                       .Select(ep => new RemoteHost(ep.HostName, this, _lock, ep.Port));

                        ReachableHosts.AddRange(newHosts);

                        EndPointsResult = updatedEndPointsResult;
                        Counter         = (ulong)_random.Next(0, ReachableHosts.Count);

                        Health.SetHealthFunction(CheckHealth);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Failed to process newly discovered endpoints", exception: ex);
                    Health.SetHealthFunction(() => HealthCheckResult.Unhealthy("Failed to process newly discovered endpoints: " + HealthMonitor.GetMessages(ex)));
                }
            }
        }
コード例 #3
0
        private void SetMockToReturnError(string query)
        {
            var result = new EndPointsResult {
                Error = new EnvironmentException("Mock: some error"), IsQueryDefined = true, ResponseLog = "Error response log"
            };

            _consulResult[query] = result;
            _resultChanged[query].Post(result);
        }
コード例 #4
0
        private void SetMockToReturnServiceNotDefined(string query)
        {
            var result = new EndPointsResult {
                IsQueryDefined = false
            };

            _consulResult[query] = result;
            _resultChanged[query].Post(result);
        }
コード例 #5
0
        public void SetResult(EndPointsResult result)
        {
            lock (_lastResultLocker)
            {
                var lastResult = _lastResult;

                _lastResult = result;
                Result      = result;

                if (lastResult?.Equals(result) == false && _initialized)
                {
                    _resultChanged.Post(result);
                }
            }
        }
コード例 #6
0
        private void CreateConsulMock(string serviceName)
        {
            var mock = Substitute.For <IConsulClient>();

            _consulResult[serviceName] = new EndPointsResult {
                EndPoints = new EndPoint[] { new ConsulEndPoint {
                                                 HostName = "dumy", Version = ServiceVersion
                                             } }, IsQueryDefined = true
            };
            _resultChanged[serviceName] = new BufferBlock <EndPointsResult>();

            mock.ResultChanged.Returns(t => _resultChanged[serviceName]);
            mock.Result.Returns(t => _consulResult[serviceName]);

            _consulClients[serviceName] = mock;
        }
コード例 #7
0
        private void SetMockToReturnHost(string query)
        {
            if (!_consulClients.ContainsKey(query))
            {
                CreateConsulMock(query);
            }
            var result = new EndPointsResult
            {
                EndPoints = new EndPoint[] { new ConsulEndPoint {
                                                 HostName = query, Version = ServiceVersion
                                             } },
                RequestLog     = "<Mock consul request log>",
                ResponseLog    = "<Mock consul response>",
                ActiveVersion  = ServiceVersion,
                IsQueryDefined = true
            };

            _consulResult[query] = result;
            _resultChanged[query].Post(result);
        }
コード例 #8
0
        public void SetEndPoints(string endPoints)
        {
            Result = new EndPointsResult {
                EndPoints = new EndPoint[0]
            };
            if (!string.IsNullOrWhiteSpace(endPoints))
            {
                Result = new EndPointsResult {
                    EndPoints = endPoints.Split(',').Select(_ => _.Trim())
                                .Where(a => !string.IsNullOrWhiteSpace(a))
                                .Select(_ => new EndPoint {
                        HostName = _
                    })
                                .ToArray()
                }
            }
            ;

            EndpointsChangedBroadcast.Post(Result);
            Task.Delay(100).Wait();
        }
コード例 #9
0
        public async Task Setup()
        {
            _configDic         = new Dictionary <string, string>();
            _unitTestingKernel = new TestingKernel <ConsoleLog>(k =>
            {
                k.Rebind <IDiscoverySourceLoader>().To <DiscoverySourceLoader>().InSingletonScope();
                k.Rebind <IEnvironmentVariableProvider>().To <EnvironmentVariableProvider>();
                _result = new EndPointsResult {
                    EndPoints = new[] { new ConsulEndPoint {
                                            HostName = "dumy", Version = ServiceVersion
                                        } }, ActiveVersion = ServiceVersion, IsQueryDefined = true
                };
                _resultChanged     = new BroadcastBlock <EndPointsResult>(null);
                _consulAdapterMock = Substitute.For <IConsulClient>();
                _consulAdapterMock.Result.Returns(_ => _result);
                _consulAdapterMock.ResultChanged.Returns(_resultChanged);
                k.Rebind <Func <string, IConsulClient> >().ToMethod(c => s => _consulAdapterMock);
            }, _configDic);

            _configRefresh    = _unitTestingKernel.Get <ManualConfigurationEvents>();
            _serviceDiscovery = _unitTestingKernel.Get <Func <string, ReachabilityChecker, ServiceDiscovery.ServiceDiscovery> >()("ServiceName", x => Task.FromResult(true));
        }
コード例 #10
0
 public override Exception AllEndpointsUnreachable(EndPointsResult endpointsResult, Exception lastException, string lastExceptionEndPoint, string unreachableHosts)
 {
     return(new EnvironmentException("All endpoints unreachable"));
 }
コード例 #11
0
 public DiscoverySourceMock(string deployment, string initialEndPoints) : base(deployment)
 {
     Result = new EndPointsResult {
         EndPoints = GetEndPointsInitialValue(initialEndPoints)
     };
 }