public void Constructor_Initializes()
        {
            AgentServiceRegistration serviceRegistration = new AgentServiceRegistration()
            {
                ID      = "ID",
                Name    = "foobar",
                Address = "test.foo.bar",
                Port    = 1234,
                Tags    = new string[] { "foo=bar" }
            };
            ConsulDiscoveryOptions opts         = new ConsulDiscoveryOptions();
            ConsulRegistration     registration = new ConsulRegistration(serviceRegistration, opts);
            ThisServiceInstance    thiz         = new ThisServiceInstance(registration);

            Assert.Equal("test.foo.bar", thiz.Host);
            Assert.Equal("foobar", thiz.ServiceId);
            Assert.False(thiz.IsSecure);
            Assert.Equal(1234, thiz.Port);
            Assert.Single(thiz.Metadata);
            Assert.Contains("foo", thiz.Metadata.Keys);
            Assert.Contains("bar", thiz.Metadata.Values);
            Assert.Equal(new Uri("http://test.foo.bar:1234"), thiz.Uri);
        }
        public void GetInstanceId_ReturnsExpected()
        {
            var options = new ConsulDiscoveryOptions()
            {
                InstanceId = "instanceId"
            };

            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string>()
            {
                { "spring:application:name", "foobar" }
            })
                         .Build();

            var result = ConsulRegistration.GetInstanceId(options, new ApplicationInstanceInfo(config));

            Assert.Equal("instanceId", result);

            options.InstanceId = null;

            result = ConsulRegistration.GetInstanceId(options, new ApplicationInstanceInfo(config));
            Assert.StartsWith("foobar-", result);
        }
Exemple #3
0
        public void CreateCheck_ReturnsExpected()
        {
            ConsulDiscoveryOptions options = new ConsulDiscoveryOptions();
            var result = ConsulRegistration.CreateCheck(1234, options);

            Assert.NotNull(result);
            Assert.Equal(DateTimeConversions.ToTimeSpan(options.Heartbeat.Ttl), result.TTL);
            Assert.Equal(DateTimeConversions.ToTimeSpan(options.HealthCheckCriticalTimeout), result.DeregisterCriticalServiceAfter);

            options.Heartbeat = null;
            Assert.Throws <ArgumentException>(() => ConsulRegistration.CreateCheck(0, options));

            int port = 1234;

            result = ConsulRegistration.CreateCheck(port, options);
            var uri = new Uri($"{options.Scheme}://{options.HostName}:{port}{options.HealthCheckPath}");

            Assert.Equal(uri.ToString(), result.HTTP);
            Assert.Equal(DateTimeConversions.ToTimeSpan(options.HealthCheckInterval), result.Interval);
            Assert.Equal(DateTimeConversions.ToTimeSpan(options.HealthCheckTimeout), result.Timeout);
            Assert.Equal(DateTimeConversions.ToTimeSpan(options.HealthCheckCriticalTimeout), result.DeregisterCriticalServiceAfter);
            Assert.Equal(options.HealthCheckTlsSkipVerify, result.TLSSkipVerify);
        }
        public void Options_DontUseInetUtilsByDefault()
        {
            // arrange
            var mockNetUtils = new Mock <InetUtils>(null, null);

            mockNetUtils.Setup(n => n.FindFirstNonLoopbackHostInfo()).Returns(new HostInfo()
            {
                Hostname = "FromMock", IpAddress = "254.254.254.254"
            }).Verifiable();
            var config = new ConfigurationBuilder().Build();
            var opts   = new ConsulDiscoveryOptions()
            {
                NetUtils = mockNetUtils.Object
            };

            config.GetSection(ConsulDiscoveryOptions.CONSUL_DISCOVERY_CONFIGURATION_PREFIX).Bind(opts);

            // act
            opts.ApplyNetUtils();

            // assert
            mockNetUtils.Verify(n => n.FindFirstNonLoopbackHostInfo(), Times.Never);
        }
        public void Constructor_SetsProperties()
        {
            AgentServiceRegistration areg = new AgentServiceRegistration()
            {
                ID      = "id",
                Name    = "name",
                Address = "address",
                Port    = 1234,
                Tags    = new string[] { "foo=bar" }
            };

            ConsulDiscoveryOptions options = new ConsulDiscoveryOptions();
            var reg = new ConsulRegistration(areg, options);

            Assert.Equal("id", reg.InstanceId);
            Assert.Equal("name", reg.ServiceId);
            Assert.Equal("address", reg.Host);
            Assert.Equal(1234, reg.Port);
            Assert.Single(reg.Metadata);
            Assert.Contains("foo", reg.Metadata.Keys);
            Assert.Contains("bar", reg.Metadata.Values);
            Assert.False(reg.IsSecure);
            Assert.Equal(new Uri("http://address:1234"), reg.Uri);
        }
Exemple #6
0
        internal static string[] CreateTags(ConsulDiscoveryOptions options)
        {
            List <string> tags = new List <string>();

            if (options.Tags != null)
            {
                tags.AddRange(options.Tags);
            }

            if (!string.IsNullOrEmpty(options.InstanceZone))
            {
                tags.Add(options.DefaultZoneMetadataName + "=" + options.InstanceZone);
            }

            if (!string.IsNullOrEmpty(options.InstanceGroup))
            {
                tags.Add("group=" + options.InstanceGroup);
            }

            // store the secure flag in the tags so that clients will be able to figure out whether to use http or https automatically
            tags.Add("secure=" + (options.Scheme == "https").ToString().ToLower());

            return(tags.ToArray());
        }
        private static bool SetHttpCheck(AgentServiceCheck check, ConsulDiscoveryOptions options)
        {
            var healthCheckUrl = options.HealthCheckUrl;

            if (string.IsNullOrEmpty(healthCheckUrl))
            {
                var hostString = options.HostName;
                var port       = options.Port;
                hostString += ":" + port;

                var healthCheckPath = options.HealthCheckPath;
                if (!healthCheckPath.StartsWith("/"))
                {
                    healthCheckPath = "/" + healthCheckPath;
                }

                healthCheckUrl = $"{options.Scheme}://{hostString}{healthCheckPath}";
            }

            TimeSpan?interval = null;

            if (!string.IsNullOrWhiteSpace(options.HealthCheckInterval))
            {
                interval = DateTimeConversions.ToTimeSpan(options.HealthCheckInterval);
            }

            if (string.IsNullOrEmpty(healthCheckUrl) || interval == null)
            {
                return(false);
            }

            check.HTTP     = healthCheckUrl;
            check.Interval = interval;

            return(true);
        }
        internal static string GetDefaultInstanceId(ConsulDiscoveryOptions options, IConfiguration config)
        {
            var    appName = GetAppName(options, config);
            string vcapId  = config.GetValue <string>("vcap:application:instance_id", null);

            if (!string.IsNullOrEmpty(vcapId))
            {
                return(appName + ":" + vcapId);
            }

            string springId = config.GetValue <string>("spring:application:instance_id", null);

            if (!string.IsNullOrEmpty(springId))
            {
                return(appName + ":" + springId);
            }

            Random rand = new Random();

#pragma warning disable SCS0005 // Weak random generator
            return(appName + ":" + rand.Next().ToString());

#pragma warning restore SCS0005 // Weak random generator
        }
Exemple #9
0
        public async void AddInstancesToListAsync_AddsExpected()
        {
            var options = new ConsulDiscoveryOptions();

            var queryResult = new QueryResult <ServiceEntry[]>()
            {
                Response = new ServiceEntry[]
                {
                    new ServiceEntry()
                    {
                        Service = new AgentService()
                        {
                            Service = "ServiceId",
                            Address = "foo.bar.com",
                            Port    = 1234,
                            Tags    = new string[] { "foo=bar", "secure=true" }
                        }
                    },
                    new ServiceEntry()
                    {
                        Service = new AgentService()
                        {
                            Service = "ServiceId",
                            Address = "foo1.bar1.com",
                            Port    = 5678,
                            Tags    = new string[] { "bar=foo", "secure=false" }
                        }
                    }
                }
            };

            var result    = Task.FromResult(queryResult);
            var clientMoq = new Mock <IConsulClient>();
            var healthMoq = new Mock <IHealthEndpoint>();

            clientMoq.Setup(c => c.Health).Returns(healthMoq.Object);
            healthMoq.Setup(h => h.Service("ServiceId", options.DefaultQueryTag, options.QueryPassing, QueryOptions.Default, default(CancellationToken))).Returns(result);

            var dc   = new ConsulDiscoveryClient(clientMoq.Object, options);
            var list = new List <IServiceInstance>();
            await dc.AddInstancesToListAsync(list, "ServiceId", QueryOptions.Default);

            Assert.Equal(2, list.Count);

            var inst = list[0];

            Assert.Equal("foo.bar.com", inst.Host);
            Assert.Equal("ServiceId", inst.ServiceId);
            Assert.True(inst.IsSecure);
            Assert.Equal(1234, inst.Port);
            Assert.Equal(2, inst.Metadata.Count);
            Assert.Contains("foo", inst.Metadata.Keys);
            Assert.Contains("secure", inst.Metadata.Keys);
            Assert.Contains("bar", inst.Metadata.Values);
            Assert.Contains("true", inst.Metadata.Values);
            Assert.Equal(new Uri("https://foo.bar.com:1234"), inst.Uri);

            inst = list[1];
            Assert.Equal("foo1.bar1.com", inst.Host);
            Assert.Equal("ServiceId", inst.ServiceId);
            Assert.False(inst.IsSecure);
            Assert.Equal(5678, inst.Port);
            Assert.Equal(2, inst.Metadata.Count);
            Assert.Contains("bar", inst.Metadata.Keys);
            Assert.Contains("secure", inst.Metadata.Keys);
            Assert.Contains("foo", inst.Metadata.Values);
            Assert.Contains("false", inst.Metadata.Values);
            Assert.Equal(new Uri("http://foo1.bar1.com:5678"), inst.Uri);
        }
Exemple #10
0
 public ConsulServerList(string clientName, ConsulClient consulClient, IOptions <ConsulDiscoveryOptions> optionsAccessor)
 {
     _clientName             = clientName;
     _consulClient           = consulClient;
     _consulDiscoveryOptions = optionsAccessor.Value;
 }
        public void GetAllInstances_ReturnsExpected()
        {
            var options = new ConsulDiscoveryOptions();

            var queryResult1 = new QueryResult <Dictionary <string, string[]> >()
            {
                Response = new Dictionary <string, string[]>
                {
                    { "ServiceId", new string[] { "I1", "I2" } },
                }
            };
            var result1 = Task.FromResult(queryResult1);

            var queryResult2 = new QueryResult <ServiceEntry[]>()
            {
                Response = new ServiceEntry[]
                {
                    new ServiceEntry()
                    {
                        Service = new AgentService()
                        {
                            Service = "ServiceId",
                            Address = "foo.bar.com",
                            Port    = 1234,
                            Tags    = new string[] { "foo=bar", "secure=true" }
                        }
                    },
                    new ServiceEntry()
                    {
                        Service = new AgentService()
                        {
                            Service = "ServiceId",
                            Address = "foo1.bar1.com",
                            Port    = 5678,
                            Tags    = new string[] { "bar=foo", "secure=false" }
                        }
                    }
                }
            };
            var result2 = Task.FromResult(queryResult2);

            var clientMoq = new Mock <IConsulClient>();
            var catMoq    = new Mock <ICatalogEndpoint>();

            clientMoq.Setup(c => c.Catalog).Returns(catMoq.Object);
            catMoq.Setup(c => c.Services(QueryOptions.Default, default)).Returns(result1);

            var healthMoq = new Mock <IHealthEndpoint>();

            clientMoq.Setup(c => c.Health).Returns(healthMoq.Object);
            healthMoq.Setup(h => h.Service("ServiceId", options.DefaultQueryTag, options.QueryPassing, QueryOptions.Default, default)).Returns(result2);

            var dc   = new ConsulDiscoveryClient(clientMoq.Object, options);
            var list = dc.GetAllInstances(QueryOptions.Default);

            Assert.Equal(2, list.Count);

            var inst = list[0];

            Assert.Equal("foo.bar.com", inst.Host);
            Assert.Equal("ServiceId", inst.ServiceId);
            Assert.True(inst.IsSecure);
            Assert.Equal(1234, inst.Port);
            Assert.Equal(2, inst.Metadata.Count);
            Assert.Contains("foo", inst.Metadata.Keys);
            Assert.Contains("secure", inst.Metadata.Keys);
            Assert.Contains("bar", inst.Metadata.Values);
            Assert.Contains("true", inst.Metadata.Values);
            Assert.Equal(new Uri("https://foo.bar.com:1234"), inst.Uri);

            inst = list[1];
            Assert.Equal("foo1.bar1.com", inst.Host);
            Assert.Equal("ServiceId", inst.ServiceId);
            Assert.False(inst.IsSecure);
            Assert.Equal(5678, inst.Port);
            Assert.Equal(2, inst.Metadata.Count);
            Assert.Contains("bar", inst.Metadata.Keys);
            Assert.Contains("secure", inst.Metadata.Keys);
            Assert.Contains("foo", inst.Metadata.Values);
            Assert.Contains("false", inst.Metadata.Values);
            Assert.Equal(new Uri("http://foo1.bar1.com:5678"), inst.Uri);
        }
Exemple #12
0
 /// <summary>
 /// Perform post-configuration on ConsulDiscoveryOptions
 /// </summary>
 /// <param name="config">Application Configuration</param>
 /// <param name="options">ConsulDiscoveryOptions to configure</param>
 /// <param name="netOptions">Optional InetOptions</param>
 public static void UpdateDiscoveryOptions(IConfiguration config, ConsulDiscoveryOptions options, InetOptions netOptions)
 {
     options.NetUtils = new InetUtils(netOptions);
     options.ApplyNetUtils();
     options.ApplyConfigUrls(config.GetAspNetCoreUrls(), ConfigurationUrlHelpers.WILDCARD_HOST);
 }