Ejemplo n.º 1
0
        private List <DiscoverableEndpoint> GetDiscoverableEndpoints()
        {
            var assembly = Assembly.GetEntryAssembly();

            var ergEndpointMembers = assembly.GetTypes()
                                     .Where(t => t.IsSubclassOf(typeof(ControllerBase)))
                                     .SelectMany(t => t.GetMembers()
                                                 .Where(m => Attribute.IsDefined(m, typeof(UtilityEndpointAttribute))));

            var discoverableEndpoints = new List <DiscoverableEndpoint>();

            foreach (var ergEndpointMember in ergEndpointMembers)
            {
                var attributeData = ergEndpointMember.GetCustomAttribute <UtilityEndpointAttribute>();
                var endpoint      = new DiscoverableEndpoint
                {
                    Alias       = attributeData.Alias,
                    Description = attributeData.Description,
                    Url         = GetUrlForActionName(ergEndpointMember.Name),
                    Method      = GetMethodForActionName(ergEndpointMember.Name)
                };

                discoverableEndpoints.Add(endpoint);
            }

            return(discoverableEndpoints);
        }
Ejemplo n.º 2
0
        void AppendToConsul(string id, string name, string[] tags, AgentServiceCheck check = null)
        {
            DiscoverableEndpoint newEndpoint = tags.ConvertConsulTagsToDiscoveryEndpoint();
            bool isNewOrUpdatedService       = IsNewOrUpdatedService(newEndpoint);

            if (isNewOrUpdatedService)
            {
                check = null; // Removes all health checks for now... too much noise
                var registration = new AgentServiceRegistration()
                {
                    ID      = id,
                    Name    = name,
                    Address = consulNodeIp,
                    Tags    = tags,
                    Check   = check
                };

                // this will clean old registrations
                var unRegister = client.Agent.ServiceDeregister(registration.ID).Result;
                var register   = client.Agent.ServiceRegister(registration).Result;
                //var result = client.Catalog.Services().Result;
                //foreach (var item in result.Response)
                //{
                //    client.Agent.ServiceDeregister(item.Key);
                //}
            }
        }
Ejemplo n.º 3
0
        private bool IsNewOrUpdatedService(DiscoverableEndpoint newEndpoint)
        {
            var result = client.Catalog.Service(newEndpoint.FullName).Result;

            if (ReferenceEquals(result, null))
            {
                return(false);
            }
            if (result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(false);
            }

            CatalogService[] currentServices = result.Response;
            if (ReferenceEquals(currentServices, null) || currentServices.Length == 0)
            {
                return(true);
            }

            foreach (var currentService in currentServices)
            {
                DiscoverableEndpoint endpointInConsul = currentService.ServiceTags.ConvertConsulTagsToDiscoveryEndpoint();
                if (newEndpoint.Equals(endpointInConsul) == false)
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 4
0
        public void RegisterServices(HttpConfiguration config, Assembly assembly, string boundedContext, Uri boundedContextBaseUri)
        {
            var methodsWithDiscoverableAttribute = assembly.GetTypes()
                                                   .SelectMany(t => t.GetMethods())
                                                   .Where(m => m.GetCustomAttributes(typeof(DiscoverableAttribute), false).Length > 0)
                                                   .Select(m => new { Method = m, Attr = (DiscoverableAttribute)m.GetCustomAttribute(typeof(DiscoverableAttribute), false) })
                                                   .ToArray();

            foreach (var methodWithDiscoverableAttribute in methodsWithDiscoverableAttribute)
            {
                var method = methodWithDiscoverableAttribute.Method;
                var attr   = methodWithDiscoverableAttribute.Attr;

                var endpoint = new DiscoverableEndpoint(attr.EndpointName, new Uri(boundedContextBaseUri, GetUrl(config, method)), boundedContext, new DiscoveryVersion(attr.Version, attr.DepricateVersion));
                AppendToConsul(endpoint);
            }
        }
Ejemplo n.º 5
0
        private async Task <int> RunEndpoint(DiscoverableEndpoint endpoint)
        {
            Console.WriteLine($"[{endpoint.Alias}] running GET {endpoint.Url}");

            var response = await HttpClient.GetAsync(endpoint.Url);

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine($"[{endpoint.Alias}] an error occurred");
                Console.WriteLine($"[{endpoint.Alias}] {response.StatusCode}");
                return(1);
            }

            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"[{endpoint.Alias}] {response.StatusCode}");
            Console.WriteLine($"[{endpoint.Alias}] {content}");

            return(0);
        }
Ejemplo n.º 6
0
        private long GetServiceUpdatedAt(string serviceId)
        {
            var endpointsFromAllNodes = new HashSet <DiscoverableEndpoint>();

            long updatedAt             = 0;
            var  consulServiceResponse = client.Catalog.Service(serviceId).Result;

            if (ReferenceEquals(null, consulServiceResponse) == false && consulServiceResponse.StatusCode == System.Net.HttpStatusCode.OK)
            {
                CatalogService[] currentServices = consulServiceResponse.Response;
                if (ReferenceEquals(null, currentServices) == false)
                {
                    foreach (var currentService in currentServices)
                    {
                        DiscoverableEndpoint endpoint = currentService.ServiceTags.ConvertConsulTagsToDiscoveryEndpoint();
                        long currentUpdatedAt         = currentService.ServiceTags.GetUpdatedAtTimestamp();

                        // We may have exactly the same service registered on different nodes at a different time which depends on deployment times
                        // In this case we get the most ancient possible timestamp
                        if (endpointsFromAllNodes.Any(ep => ep.Equals(endpoint)))
                        {
                            if (currentUpdatedAt < updatedAt)
                            {
                                updatedAt = currentUpdatedAt;
                            }
                        }
                        else
                        {
                            if (currentUpdatedAt > updatedAt)
                            {
                                updatedAt = currentUpdatedAt;
                            }
                        }

                        endpointsFromAllNodes.Add(endpoint);
                    }
                }
            }

            return(updatedAt);
        }
Ejemplo n.º 7
0
        public DiscoveryReaderResponseModel Get(string boundedContext)
        {
            long globalUpdatedAt = 0;
            var  foundEndpoints  = new HashSet <DiscoverableEndpoint>();

            var result = client.Catalog.Services().Result;

            if (ReferenceEquals(null, result) == true || result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(new DiscoveryReaderResponseModel(globalUpdatedAt, foundEndpoints));
            }

            var publicServices = result.Response.Where(x => x.Value.Any(y => ConsulHelper.IsPublic(y) == true));

            foreach (var publicService in publicServices)
            {
                var parsedTags = ConsulHelper.Parse(publicService.Value);
                if (parsedTags.ContainsDiscoverableEndpointTags() == false)
                {
                    continue;
                }
                if (parsedTags.TagsArePartOfBoundedContext(boundedContext) == false)
                {
                    continue;
                }

                DiscoverableEndpoint consulEndpoint = publicService.Value.ConvertConsulTagsToDiscoveryEndpoint();
                foundEndpoints.Add(consulEndpoint);
                long serviceUpdatedAt = GetServiceUpdatedAt(publicService.Key);
                if (serviceUpdatedAt > globalUpdatedAt)
                {
                    globalUpdatedAt = serviceUpdatedAt;
                }
            }

            return(new DiscoveryReaderResponseModel(globalUpdatedAt, foundEndpoints));
        }
Ejemplo n.º 8
0
        void AppendToConsul(DiscoverableEndpoint endpoint, Uri httpCheckUri = null)
        {
            var bcTag     = $"{ConsulHelper.BoundedContext}{ConsulHelper.Separator}{endpoint.BoundedContext}";
            var publicTag = $"{ConsulHelper.Visability}{ConsulHelper.Separator}public";
            var timeTag   = $"{ConsulHelper.UpdatedAt}{ConsulHelper.Separator}{DateTime.UtcNow.ToFileTimeUtc()}";

            var introducedAtVersionTag = $"{ConsulHelper.IntroducedAtVersion}{ConsulHelper.Separator}{endpoint.Version.IntroducedAtVersion}";
            var depricatedAtVersionTag = $"{ConsulHelper.DepricatedAtVersion}{ConsulHelper.Separator}{endpoint.Version.DepricatedAtVersion}";
            var endpointNameTag        = $"{ConsulHelper.EndpointName}{ConsulHelper.Separator}{endpoint.Name}";
            var endpointUrlTag         = $"{ConsulHelper.EndpointUrl}{ConsulHelper.Separator}{endpoint.Url}";

            var id   = endpoint.FullName;
            var name = endpoint.FullName;
            var tags = new[] { bcTag, introducedAtVersionTag, depricatedAtVersionTag, endpointUrlTag, endpointNameTag, timeTag, publicTag };

            AgentServiceCheck check = null;

            if (ReferenceEquals(null, httpCheckUri) == false)
            {
                check = DefaultCheck(httpCheckUri);
            }

            AppendToConsul(id, name, tags, check);
        }
Ejemplo n.º 9
0
 public void RegisterService(DiscoverableEndpoint endpoint, Uri httpCheckUri = null)
 {
     AppendToConsul(endpoint, httpCheckUri);
 }