Java Code Examples for com.ecwid.consul.v1.Response#getConsulIndex()

The following examples show how to use com.ecwid.consul.v1.Response#getConsulIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    while (!stopWatch) {
        Response<List<HealthService>> response = lookupHealthService(serviceName, lastConsulIndex);
        Long currentIndex = response.getConsulIndex();
        if (currentIndex != null && currentIndex > lastConsulIndex) {
            List<ServiceInstance> currentInstances = convert(response);
            Collection<ServiceInstance> addList = CollectionUtils.subtract(
                    currentInstances, lastInstances);
            Collection<ServiceInstance> deleteList = CollectionUtils.subtract(
                    lastInstances, currentInstances);
            listener.notify(addList, deleteList);
            lastInstances = currentInstances;
            lastConsulIndex = currentIndex;
        }
    }
}
 
Example 2
Source File: ConsulPropertySource.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
public void init() {
	if (!this.context.endsWith("/")) {
		this.context = this.context + "/";
	}

	Response<List<GetValue>> response = this.source.getKVValues(this.context,
			this.configProperties.getAclToken(), QueryParams.DEFAULT);

	this.initialIndex = response.getConsulIndex();

	final List<GetValue> values = response.getValue();
	ConsulConfigProperties.Format format = this.configProperties.getFormat();
	switch (format) {
	case KEY_VALUE:
		parsePropertiesInKeyValueFormat(values);
		break;
	case PROPERTIES:
	case YAML:
		parsePropertiesWithNonKeyValueFormat(values, format);
	}
}
 
Example 3
Source File: ConsulPropertySource.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
public void init() {
    if (!this.context.endsWith("/")) {
        this.context = this.context + "/";
    }

    if (configProperties.isTokenEnabled() && StringUtils.isEmpty(bmsAuthClient.getToken())) {
        bmsAuthClient.getTokenFromServer(configProperties.getAuthUri());
    }

    logger.info("Try to get KV from consul for context: " + this.context);
    Response<List<GetValue>> response = this.source.getKVValues(this.context,
            this.bmsAuthClient.getToken(), new QueryParams(ConsistencyMode.STALE));

    this.initialIndex = response.getConsulIndex();

    final List<GetValue> values = response.getValue();
    Format format = this.configProperties.getFormat();
    switch (format) {
        case KEY_VALUE:
            parsePropertiesInKeyValueFormat(values);
            logger.info("Properties for context " + this.context + "is ");
            for (Map.Entry<String, Object> entry : this.properties.entrySet()) {
                logger.info(entry.getKey() + ": " + entry.getValue().toString());
            }
            break;
        case PROPERTIES:
            break;
        case YAML:
            parsePropertiesWithNonKeyValueFormat(values, format);
            break;
        default:
            break;
    }
}
 
Example 4
Source File: ConsulNamingService.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doSubscribe(SubscribeInfo subscribeInfo, NotifyListener listener) {
    final String serviceName = subscribeInfo.getServiceId();
    Response<List<HealthService>> response = lookupHealthService(serviceName, -1);
    List<ServiceInstance> instances = convert(response);
    log.info("lookup {} instances from consul", instances.size());
    WatchTask watchTask = new WatchTask(serviceName, instances, response.getConsulIndex(), listener);
    watchExecutor.submit(watchTask);
    watchTaskMap.putIfAbsent(subscribeInfo, watchTask);
}
 
Example 5
Source File: ConsulDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public String readSource() throws Exception {
    if (this.client == null) {
        throw new IllegalStateException("Consul has not been initialized or error occurred");
    }
    Response<GetValue> response = getValueImmediately(ruleKey);
    if (response != null) {
        GetValue value = response.getValue();
        lastIndex = response.getConsulIndex();
        return value != null ? value.getDecodedValue() : null;
    }
    return null;
}
 
Example 6
Source File: ConsulCatalogWatch.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Timed("consul.watch-catalog-services")
public void catalogServicesWatch() {
	try {
		long index = -1;
		if (this.catalogServicesIndex.get() != null) {
			index = this.catalogServicesIndex.get().longValue();
		}

		CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
				.setQueryParams(new QueryParams(
						this.properties.getCatalogServicesWatchTimeout(), index))
				.setToken(this.properties.getAclToken()).build();
		Response<Map<String, List<String>>> response = this.consul
				.getCatalogServices(request);
		Long consulIndex = response.getConsulIndex();
		if (consulIndex != null) {
			this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
		}

		if (log.isTraceEnabled()) {
			log.trace("Received services update from consul: " + response.getValue()
					+ ", index: " + consulIndex);
		}
		this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
	}
	catch (Exception e) {
		log.error("Error watching Consul CatalogServices", e);
	}
}
 
Example 7
Source File: ConfigWatch.java    From spring-cloud-formula with Apache License 2.0 4 votes vote down vote up
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues(String context) {
    if (this.running.get()) {
        if (this.properties.getFormat() != Format.FILES && !context.endsWith("/")) {
            context = context + "/";
        }

        try {
            Long currentIndex = this.consulIndexes.get(context);
            if (currentIndex == null) {
                currentIndex = -1L;
            }

            logger.debug("watching consul for context '" + context + "' with index " + currentIndex);

            if (properties.isTokenEnabled() && StringUtils.isEmpty(bmsAuthClient.getToken())) {
                bmsAuthClient.getTokenFromServer(properties.getAuthUri());
            }

            QueryParams queryParams = QueryParams.Builder.builder()
                    .setConsistencyMode(ConsistencyMode.STALE)
                    .setIndex(currentIndex)
                    .setWaitTime(this.properties.getWatch().getWaitTime())
                    .build();
            Response<List<GetValue>> response = this.consul.getKVValues(context, bmsAuthClient.getToken(),
                    queryParams);

            // if response.value == null, response was a 404, otherwise it was a 200
            // reducing churn if there wasn't anything
            if (response.getValue() != null && !response.getValue().isEmpty()) {
                Long newIndex = response.getConsulIndex();

                if (newIndex != null && !newIndex.equals(currentIndex)) {
                    // don't publish the same index again, don't publish the first
                    // time (-1) so index can be primed
                    if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
                        logger.trace("Context " + context + " has new index " + newIndex);
                        RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
                        this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
                    } else if (logger.isTraceEnabled()) {
                        logger.trace("Event for index already published for context " + context);
                    }
                    this.consulIndexes.put(context, newIndex);
                } else if (logger.isTraceEnabled()) {
                    logger.trace("Same index for context " + context);
                }
            } else if (logger.isTraceEnabled()) {
                logger.trace("No value for context " + context);
            }

        } catch (Exception e) {
            // OperationException(statusCode=403, statusMessage='Forbidden', statusContent='ACL not found')
            if (e instanceof OperationException && ((OperationException) e).getStatusCode() == 403) {
                logger.info("Token has expired, try to get new token from server.");
                String newToken = bmsAuthClient.getTokenFromServer(this.properties.getAuthUri());
                logger.info("New Token is: " + newToken);
            }
            // only fail fast on the initial query, otherwise just log the error
            if (this.firstTime && this.properties.isFailFast()) {
                logger.error(
                        "Fail fast is set and there was an error reading configuration from consul.");
                ReflectionUtils.rethrowRuntimeException(e);
            } else if (logger.isTraceEnabled()) {
                logger.trace("Error querying consul Key/Values for context '"
                        + context + "'", e);
            } else if (logger.isWarnEnabled()) {
                // simplified one line log message in the event of an agent failure
                logger.warn("Error querying consul Key/Values for context '"
                        + context + "'. Message: " + e.getMessage());
            }
        }
    }
    this.firstTime = false;
}
 
Example 8
Source File: ConfigWatch.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
@Timed("consul.watch-config-keys")
public void watchConfigKeyValues() {
	if (this.running.get()) {
		for (String context : this.consulIndexes.keySet()) {

			// turn the context into a Consul folder path (unless our config format
			// are FILES)
			if (this.properties.getFormat() != FILES && !context.endsWith("/")) {
				context = context + "/";
			}

			try {
				Long currentIndex = this.consulIndexes.get(context);
				if (currentIndex == null) {
					currentIndex = -1L;
				}

				log.trace("watching consul for context '" + context + "' with index "
						+ currentIndex);

				// use the consul ACL token if found
				String aclToken = this.properties.getAclToken();
				if (StringUtils.isEmpty(aclToken)) {
					aclToken = null;
				}

				Response<List<GetValue>> response = this.consul.getKVValues(context,
						aclToken,
						new QueryParams(this.properties.getWatch().getWaitTime(),
								currentIndex));

				// if response.value == null, response was a 404, otherwise it was a
				// 200
				// reducing churn if there wasn't anything
				if (response.getValue() != null && !response.getValue().isEmpty()) {
					Long newIndex = response.getConsulIndex();

					if (newIndex != null && !newIndex.equals(currentIndex)) {
						// don't publish the same index again, don't publish the first
						// time (-1) so index can be primed
						if (!this.consulIndexes.containsValue(newIndex)
								&& !currentIndex.equals(-1L)) {
							log.trace("Context " + context + " has new index "
									+ newIndex);
							RefreshEventData data = new RefreshEventData(context,
									currentIndex, newIndex);
							this.publisher.publishEvent(
									new RefreshEvent(this, data, data.toString()));
						}
						else if (log.isTraceEnabled()) {
							log.trace("Event for index already published for context "
									+ context);
						}
						this.consulIndexes.put(context, newIndex);
					}
					else if (log.isTraceEnabled()) {
						log.trace("Same index for context " + context);
					}
				}
				else if (log.isTraceEnabled()) {
					log.trace("No value for context " + context);
				}

			}
			catch (Exception e) {
				// only fail fast on the initial query, otherwise just log the error
				if (this.firstTime && this.properties.isFailFast()) {
					log.error(
							"Fail fast is set and there was an error reading configuration from consul.");
					ReflectionUtils.rethrowRuntimeException(e);
				}
				else if (log.isTraceEnabled()) {
					log.trace("Error querying consul Key/Values for context '"
							+ context + "'", e);
				}
				else if (log.isWarnEnabled()) {
					// simplified one line log message in the event of an agent
					// failure
					log.warn("Error querying consul Key/Values for context '"
							+ context + "'. Message: " + e.getMessage());
				}
			}
		}
	}
	this.firstTime = false;
}
 
Example 9
Source File: EventService.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
private void setLastIndex(Response<?> response) {
	Long consulIndex = response.getConsulIndex();
	if (consulIndex != null) {
		this.lastIndex.set(response.getConsulIndex());
	}
}