@Override public void onComplete(ConsulResponse<ResponseBody> consulResponse) { // Note that response.body() and response.body().byteStream() should be closed. // see: https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html try (ResponseBody responseBody = consulResponse.getResponse()) { try (InputStream inputStream = responseBody.byteStream()) { Files.copy(inputStream, destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING); callback.onResponse(consulResponse.getIndex()); } } catch (IOException e) { callback.onFailure(e); } }
protected <T> void processConsulResponse(Message message, ConsulResponse<T> response) throws Exception { message.setHeader(ConsulConstants.CONSUL_INDEX, response.getIndex()); message.setHeader(ConsulConstants.CONSUL_LAST_CONTACT, response.getLastContact()); message.setHeader(ConsulConstants.CONSUL_KNOWN_LEADER, response.isKnownLeader()); setBodyAndResult(message, response.getResponse()); }
/** * Lists events for the Consul agent. * * GET /v1/event/list?name={name} * * @param name Event name to filter. * @param queryOptions The query options to use. * @return A {@link com.orbitz.consul.model.ConsulResponse} object containing * a list of {@link com.orbitz.consul.model.event.Event} objects. */ public EventResponse listEvents(String name, QueryOptions queryOptions) { Map<String, String> query = StringUtils.isNotEmpty(name) ? ImmutableMap.of("name", name) : Collections.emptyMap(); ConsulResponse<List<Event>> response = http.extractConsulResponse(api.listEvents(query)); return ImmutableEventResponse.of(response.getResponse(), response.getIndex()); }
@Override public void onComplete(ConsulResponse<Optional<Value>> consulResponse) { if (isStarting() || isStarted()) { Optional<Value> value = consulResponse.getResponse(); if (value.isPresent()) { Optional<String> sid = value.get().getSession(); if (!sid.isPresent()) { // If the key is not held by any session, try acquire a // lock (become leader) boolean lock = acquireLock(); LOGGER.debug("Try to acquire lock on path '{}' with id '{}', result '{}'", path, sessionId.get(), lock); localMember.setMaster(lock); } else { boolean master = sid.get().equals(sessionId.get()); if (!master) { LOGGER.debug("Path {} is held by session {}, local session is {}", path, sid.get(), sessionId.get()); } localMember.setMaster(sid.get().equals(sessionId.get())); } } index.set(consulResponse.getIndex()); watch(); } }
@Override public void onComplete(ConsulResponse<Optional<Value>> consulResponse) { if (isRunAllowed()) { Optional<Value> value = consulResponse.getResponse(); if (value.isPresent()) { Optional<String> sid = value.get().getSession(); if (sid.isPresent() && ObjectHelper.isNotEmpty(sid.get())) { // If the key is not held by any session, try acquire a // lock (become leader) LOGGER.debug("Try to take leadership ..."); setLeader(keyValueClient.acquireLock(servicePath, sessionId)); } else if (!sessionId.equals(sid) && leader.get()) { // Looks like I've lost leadership setLeader(false); } } index.set(consulResponse.getIndex()); run(); } }
@Override public void onComplete(ConsulResponse<List<Event>> response) { callback.onComplete(ImmutableEventResponse.of(response.getResponse(), response.getIndex())); }
public static ConsulResponse<Value> awaitChange(KeyValueClient kv, String key, BigInteger index) { while (true) { final ConsulResponse<Value> response = kv.getConsulResponseWithValue(key, ImmutableQueryOptions.builder() .index(index) .wait("5m") .build()) .orElse(null); if (response == null) { LOGGER.debug("Document does not exist: {}", key); return null; } if (index.equals(response.getIndex())) { LOGGER.debug("Long poll timed out, polling again for {}", key); } else { return response; } } }
public static void atomicUpdate(KeyValueClient kv, ConsulResponse<Value> initialResponse, Function<String, String> mutator) throws IOException { final Value v = initialResponse.getResponse(); final String key = v.getKey(); LOGGER.debug("Updating key {}", key); final String oldValue = v.getValueAsString(UTF_8).orElse(missingDocumentValue); final String newValue = mutator.apply(oldValue); if (Objects.equals(newValue, oldValue)) { return; } final long index = initialResponse.getIndex().longValue(); final PutOptions options = ImmutablePutOptions.builder().cas(index).build(); boolean success = kv.putValue(key, newValue, 0, options, UTF_8); if (!success) { LOGGER.info("Failed to put new document (optimistic locking failure?); reloading and retrying"); atomicUpdate(kv, key, mutator); } }
index = value.getIndex();
private static void atomicUpdate(KeyValueClient kv, String key, Function<String, String> mutator) throws IOException { while (true) { final ConsulResponse<Value> r = kv.getConsulResponseWithValue(key).orElse(null); if (r == null) { // Don't automatically create the document, because it might need to be associated with another node's session. // For example, an RPC endpoint doc is updated by both client and server, but is tied to the server session. throw new IOException("Can't update non-existent document: " + key); } final BigInteger index = r.getIndex(); final String oldValue = r.getResponse().getValueAsString(UTF_8).orElse(missingDocumentValue); final String newValue = mutator.apply(oldValue); if (Objects.equals(newValue, oldValue)) { return; } final PutOptions options = ImmutablePutOptions.builder().cas(index.longValue()).build(); boolean success = kv.putValue(key, newValue, 0, options, UTF_8); if (success) { return; } // todo truncated exponential backoff, please! Die if timeout! //MILLISECONDS.sleep(100); } }
public static void awaitRemoval(KeyValueClient kv, String key) { BigInteger index = BigInteger.ZERO; while (true) { final ConsulResponse<Value> response = kv.getConsulResponseWithValue(key, ImmutableQueryOptions.builder() .index(index) .wait("5m") .build()) .orElse(null); if (response == null) { return; } index = response.getIndex(); } }
@Override public void onComplete(ConsulResponse<List<Value>> consulResponse) { callback.onComplete( new ConsulResponse<>(getSingleValue(consulResponse.getResponse()), consulResponse.getLastContact(), consulResponse.isKnownLeader(), consulResponse.getIndex())); }
@Override public void onComplete(ConsulResponse<T> consulResponse) { if (isRunAllowed()) { onResponse(consulResponse.getResponse()); setIndex(consulResponse.getIndex()); watch(); } }
index = response.getIndex();
@Override public void run() { CatalogClient client = this.catalogClientInjector.getValue(); BigInteger index = null; while (true) { QueryOptions options = QueryOptions.BLANK; if (index != null) { options = ImmutableQueryOptions.builder() .wait("60s") .index(index) .build(); } ConsulResponse<Map<String, List<String>>> services = client.getServices(options); index = services.getIndex(); Map<String, List<String>> response = services.getResponse(); response.keySet().forEach(e -> { setupWatcher(e); }); try { Thread.sleep(1000); } catch (InterruptedException e) { break; } } }
/** * Returns a {@link ConsulResponse<Value>} for a specific key from the kv store. * Contains the consul response headers along with the configuration value. * * GET /v1/kv/{key} * * @param key The key to retrieve. * @param queryOptions The query options. * @return An {@link Optional} containing the ConsulResponse or {@link Optional#empty()} */ public Optional<ConsulResponse<Value>> getConsulResponseWithValue(String key, QueryOptions queryOptions) { try { ConsulResponse<List<Value>> consulResponse = http.extractConsulResponse(api.getValue(trimLeadingSlash(key), queryOptions.toQuery()), NOT_FOUND_404); Optional<Value> consulValue = getSingleValue(consulResponse.getResponse()); if (consulValue.isPresent()) { ConsulResponse<Value> result = new ConsulResponse<>(consulValue.get(), consulResponse.getLastContact(), consulResponse.isKnownLeader(), consulResponse.getIndex()); return Optional.of(result); } } catch (ConsulException ignored) { if (ignored.getCode() != NOT_FOUND_404) { throw ignored; } } return Optional.empty(); }