AgentClient agentClient = consul.agentClient(); env.onStarted(() -> agentClient.register(registration)); env.onStop(() -> agentClient.deregister(registration.getId()));
/** * Getter accessor for attribute 'agentClient'. * * @return * current value of 'agentClient' */ public AgentClient getAgentClient() { if (agentClient == null) { this.agentClient = consul.agentClient(); } return agentClient; }
public void deregister(String name) { log.info("Will de register " + name); AgentClient agentClient = client.agentClient(); agentClient.deregister(name); } }
@Override public void start(StartContext startContext) throws StartException { this.client = this.consulInjector.getValue().agentClient(); }
/** Deregister a service from Consul */ public void deregister() { final AgentClient agent = consul.agentClient(); if (!agent.isRegistered(serviceId)) { LOGGER.info("No service registered with ID \"{}\"", serviceId); return; } LOGGER.info("Deregistering service ID \"{}\"", serviceId); try { consul.agentClient().deregister(serviceId); } catch (ConsulException e) { LOGGER.error("Failed to deregister service from Consul", e); } }
public synchronized void passHealthCheck() { if (!shouldPassHealthCheck) { // throwing an exception stops the scheduled task from running again. throw new RuntimeException("Stopping recurring health check task."); } try { consul.agentClient().pass(serviceId, "(" + serviceId + ") OK"); LOGGER.debug("Passed health check."); } catch (Throwable t) { fatalErrorConsumer.accept(new RuntimeException("Failed to tell Consul agent we passed health check.", t)); Throwables.throwIfUnchecked(t); throw new RuntimeException(t); } }
public static void deregisterService(String serviceId) { Consul consul = consulInstance(); consul.agentClient().deregister(serviceId); LOG.info("Deregistered Service: " + serviceId); }
@Override public void panic(String message, Throwable t) { synchronized (this) { panic = true; LOGGER.error("PANIC: " + message, t); try { consul.agentClient().fail(serviceId, formatMessageWithStackTrace(message, t)); } catch (Exception e) { LOGGER.error("Failed to report panic to Consul agent.", e); } try { // We just failed the health check with a specific error message; // don't need to fail again with the generic one. Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException e) { // Already shutting down? Not a problem. } } // todo think a little harder and exit in a more graceful way System.exit(1); }
public static Map<String, String> getPEServices() { LOG.info("Load PE service status"); Consul consul = consulInstance(); AgentClient agent = consul.agentClient(); Map<String, Service> services = consul.agentClient().getServices(); Map<String, HealthCheck> checks = agent.getChecks(); Map<String, String> peServices = new HashMap<>(); for(Map.Entry<String, Service> entry : services.entrySet()) { if(entry.getValue().getTags().contains(PE_SERVICE_NAME)) { String serviceId = entry.getValue().getId(); String serviceStatus = "critical"; if(checks.containsKey("service:" + entry.getKey())) { serviceStatus = checks.get("service:" + entry.getKey()).getStatus(); } LOG.info("Service id: " + serviceId + " service status: " + serviceStatus); peServices.put(serviceId, serviceStatus); } } return peServices; }
@Override protected Result check() throws Exception { try { consul.agentClient().ping(); return Result.healthy(); } catch (ConsulException e) { LOGGER.warn("Unable to ping consul", e); } return Result.unhealthy("Could not ping consul"); } }
@Override public void deregister(ServiceDefinition definition) { if (definition.getId() == null) { throw new IllegalArgumentException("ServiceID must be defined (definition=" + definition + ")"); } client.agentClient().deregister(definition.getId()); //remove the serviceId to the list of known server serviceList.remove(definition.getId()); }
@Test public void doHealthCheck() throws Exception { Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts("127.0.0.1", 8500)).build(); AgentClient agentClient = consul.agentClient(); String serviceName = "health-check-service"; String serviceTag = "test"; agentClient.register(9090, HostAndPort.fromParts("127.0.0.1", 8080), 3l, serviceName, "service-id", serviceTag); TimeUnit.MINUTES.sleep(2); } }
@Test public void registerServiceForConsul() throws Exception { Consul consul = Consul.builder().withHostAndPort(HostAndPort.fromParts("127.0.0.1", 8500)).build(); AgentClient agentClient = consul.agentClient(); String serviceId = UUID.randomUUID().toString(); String serviceName = "java-consul-service"; String serviceTag = "test"; long ttl = 3l; agentClient.register(9090, ttl, serviceName, serviceId, serviceTag); agentClient.pass(serviceId); System.out.println("succ."); TimeUnit.MINUTES.sleep(2); } }
consul.agentClient().toggleMaintenanceMode(serviceId, enable, reason);
@Override protected void doStop() throws Exception { if (scheduler != null) { getCamelContext().getExecutorServiceManager().shutdownNow(scheduler); scheduler = null; } if (configuration.isDeregisterServicesOnStop()) { for (Service service: client.agentClient().getServices().values()) { try { if (serviceList.contains(service.getId())) { client.agentClient().deregister(service.getId()); serviceList.remove(service.getId()); } } catch (Exception e) { LOGGER.warn("Error de-registering service: " + service, e); } } client = null; } }
public synchronized void heartbeat() throws ClusterMembershipException { if (panic) { throw new ClusterMembershipException("Already permanently failed a health check."); } try { consul.agentClient().pass(serviceId, "(" + serviceId + ") OK"); } catch (NotRegisteredException e) { // todo re-register? maybe only if we haven't skipped too many heartbeats since last "pass"? if (hasCause(e, ConnectException.class)) { throw new ClusterMembershipException("Lost connection to Consul agent.", e); } throw new ClusterMembershipException("Consul doesn't think we're registered.", e); } }
public SessionTask(Consul consul, String serviceName, String serviceId, Consumer<Throwable> fatalErrorConsumer) { serviceId = defaultIfNull(serviceId, serviceName); this.serviceId = serviceId; this.serviceName = requireNonNull(serviceName); this.consul = requireNonNull(consul); this.fatalErrorConsumer = requireNonNull(fatalErrorConsumer); try { final List<String> tags = singletonList("couchbase-elasticsearch-connector");// emptyList(); final Map<String, String> meta = singletonMap("uuid", serviceUuid); // todo catch exception, retry with backoff (wait for consul agent to start) final int sessionTtlSeconds = HEALTH_CHECK_INTERVAL_SECONDS * 2; consul.agentClient().register(0, sessionTtlSeconds, this.serviceName, this.serviceId, tags, meta); passHealthCheck(); this.sessionId = consul.sessionClient().createSession(ImmutableSession.builder() .name("couchbase:cbes:" + this.serviceId) .behavior("delete") .lockDelay("15s") .addChecks("service:" + this.serviceId) // consul client library names the health check "service:<serviceId>" .build() ).getId(); } catch (Throwable t) { fatalErrorConsumer.accept(t); // todo need to send to fatalErrorConsumer? throw t; } }
public void register(String name, int port) { log.info("Will register " + name + " with port " + port); AgentClient agentClient = client.agentClient(); Registration service = ImmutableRegistration.builder().id(name).name(name).port(port) .check(Registration.RegCheck.http("http://localhost:" + port + Constants.HEALTH_CONTEXT, 60, 5)).build(); agentClient.register(service); }
@Override public void sendHeartbeat() throws SiteWhereException { if (getConsulClient() != null) { AgentClient agentClient = getConsulClient().agentClient(); try { String serviceId = getMicroservice().getId().toString(); if (agentClient.isRegistered(serviceId)) { agentClient.pass(serviceId); } } catch (NotRegisteredException e) { throw new SiteWhereException("Unable to send heartbeat.", e); } } else { getLogger().info("Skipping heartbeat. Consul client not connected."); } }
System.out.println(consul.agentClient().getMembers());