/// <summary> /// Gets the service /// </summary> /// <param name="serviceName">The global service name for servicestack services</param> /// <param name="tagName">the tagName to find the service for</param> /// <returns>The service for the tagName</returns> /// <exception cref="GatewayServiceDiscoveryException">throws exception if no service available for dto</exception> public static ConsulServiceResponse GetService(string serviceName, string tagName) { // todo add flag to allow warning services to be included in results // `passing` filters out any services with critical or warning health states // `near=_agent` sorts results by shortest round trip time var healthUri = ConsulUris.GetService(serviceName, tagName); try { var response = healthUri.GetJsonFromUrl(); if (string.IsNullOrWhiteSpace(response)) { throw new WebServiceException($"Expected json but received empty or null reponse from {healthUri}"); } return(GetConsulServiceResponses(response).First()); } catch (Exception e) { var message = $"No healthy services are currently registered to process the request of type '{tagName}'"; LogManager.GetLogger(typeof(ConsulClient)).Error(message, e); throw new GatewayServiceDiscoveryException(message, e); } }
/// <summary> /// Removes a service registration (and it's associated health checks) from consul /// </summary> /// <param name="serviceId">the id of the service to unregister</param> /// <exception cref="GatewayServiceDiscoveryException">throws exception if unregistering was not successful</exception> public static void UnregisterService(string serviceId) { ConsulUris.DeregisterService(serviceId).GetJsonFromUrl( null, response => { var logger = LogManager.GetLogger(typeof(ConsulClient)); if (response.StatusCode != HttpStatusCode.OK) { logger.Error($"Consul failed to unregister service `{serviceId}`"); throw new GatewayServiceDiscoveryException( $"Failed to unregister service: {serviceId}"); } logger.Debug($"Consul unregistered service: {serviceId}"); }); }
/// <summary> /// Returns a list of catalog services and tags /// </summary> /// <returns>service id's and tags</returns> /// <exception cref="GatewayServiceDiscoveryException">throws exception if unable to get services</exception> public static ConsulServiceResponse[] GetServices(string serviceName) { try { var response = ConsulUris.GetServices(serviceName).GetJsonFromUrl(); if (string.IsNullOrWhiteSpace(response)) { throw new WebServiceException( $"Expected json but received empty or null reponse from {ConsulUris.GetServices(serviceName)}"); } return(GetConsulServiceResponses(response)); } catch (Exception e) { const string message = "Unable to retrieve services from Consul"; LogManager.GetLogger(typeof(ConsulClient)).Error(message, e); throw new GatewayServiceDiscoveryException(message, e); } }