use of com.tencent.polaris.api.pojo.ServiceEventKey in project polaris-java by polarismesh.
the class InstancesDetectTask method doInstanceDetectForService.
private void doInstanceDetectForService(ServiceKey serviceKey) throws PolarisException {
ServiceEventKey svcEventKey = new ServiceEventKey(serviceKey, EventType.INSTANCE);
ServiceInstances instances = extensions.getLocalRegistry().getInstances(new ResourceFilter(svcEventKey, true, true));
if (!instances.isInitialized() || instances.getInstances().size() == 0) {
return;
}
Map<Instance, DetectResult> aliveResults = new HashMap<>();
for (Instance instance : instances.getInstances()) {
if (destroy.get()) {
// 如果要停止定时任务,则剩下的实例探测也没必要进行下去了
break;
}
DetectResult result = detectInstance(instance);
if (result == null || result.getRetStatus() != RetStatus.RetSuccess) {
continue;
}
aliveResults.put(instance, result);
}
if (MapUtils.isNotEmpty(aliveResults)) {
ServiceUpdateRequest updateRequest = buildInstanceUpdateResult(serviceKey, aliveResults);
LOG.info("update cache for outlier detect, value is {}", updateRequest);
extensions.getLocalRegistry().updateInstances(updateRequest);
}
}
use of com.tencent.polaris.api.pojo.ServiceEventKey in project polaris-java by polarismesh.
the class BaseFlow method commonGetOneInstance.
/**
* 通用获取单个服务实例的方法,用于SDK内部调用
*
* @param extensions 插件上下文
* @param serviceKey 服务信息
* @param coreRouterNames 核心路由插件链
* @param lbPolicy 负载均衡策略
* @param protocol 协议信息
* @param hashKey 一致性hash的key
* @return 过滤后的实例
*/
public static Instance commonGetOneInstance(Extensions extensions, ServiceKey serviceKey, List<String> coreRouterNames, String lbPolicy, String protocol, String hashKey) {
ServiceEventKey svcEventKey = new ServiceEventKey(serviceKey, EventType.INSTANCE);
LOG.info("[ConnectionManager]start to discover service {}", svcEventKey);
DefaultServiceEventKeysProvider provider = new DefaultServiceEventKeysProvider();
provider.setSvcEventKey(svcEventKey);
// 为性能考虑,优先使用本地缓存
provider.setUseCache(true);
FlowControlParam flowControlParam = new DefaultFlowControlParam();
APIConfig apiConfig = extensions.getConfiguration().getGlobal().getAPI();
flowControlParam.setTimeoutMs(apiConfig.getTimeout());
flowControlParam.setMaxRetry(apiConfig.getMaxRetryTimes());
flowControlParam.setRetryIntervalMs(apiConfig.getRetryInterval());
// 执行服务路由
ServiceInfo dstSvcInfo = new ServiceInfo();
Map<String, String> metadata = new HashMap<>();
metadata.put("protocol", protocol);
dstSvcInfo.setMetadata(metadata);
RouteInfo routeInfo = new RouteInfo(null, null, dstSvcInfo, null, "");
ResourcesResponse resourcesResponse = BaseFlow.syncGetResources(extensions, false, provider, flowControlParam);
LOG.info("[ConnectionManager]success to discover service {}", svcEventKey);
ServiceInstances serviceInstances = resourcesResponse.getServiceInstances(svcEventKey);
RouterChainGroup sysRouterChainGroup = extensions.getSysRouterChainGroup();
List<ServiceRouter> coreRouters = Extensions.loadServiceRouters(coreRouterNames, extensions.getPlugins(), false);
RouterChainGroup routerChainGroup = new DefaultRouterChainGroup(sysRouterChainGroup.getBeforeRouters(), coreRouters, sysRouterChainGroup.getAfterRouters());
ServiceInstances instancesAfterRoute = BaseFlow.processServiceRouters(routeInfo, serviceInstances, routerChainGroup);
// 执行负载均衡
LoadBalancer loadBalancer = (LoadBalancer) extensions.getPlugins().getPlugin(PluginTypes.LOAD_BALANCER.getBaseType(), lbPolicy);
Criteria criteria = new Criteria();
criteria.setHashKey(hashKey);
return BaseFlow.processLoadBalance(loadBalancer, criteria, instancesAfterRoute);
}
use of com.tencent.polaris.api.pojo.ServiceEventKey in project polaris-java by polarismesh.
the class CacheObject method onEventUpdate.
@Override
public boolean onEventUpdate(ServerEvent event) {
ServiceEventKey serviceEventKey = event.getServiceEventKey();
PolarisException error = event.getError();
remoteUpdated.set(true);
boolean svcDeleted = false;
Collection<ResourceEventListener> resourceEventListeners = registry.getResourceEventListeners();
if (null != error) {
// 收取消息有出错
RegistryCacheValue registryCacheValue = loadValue(false);
// 没有服务信息直接删除
if (error.getCode() == ErrorCode.SERVICE_NOT_FOUND) {
if (deleted.compareAndSet(false, true)) {
registry.removeCache(serviceEventKey);
for (ResourceEventListener listener : resourceEventListeners) {
listener.onResourceDeleted(svcEventKey, registryCacheValue);
}
svcDeleted = true;
}
} else {
LOG.error(String.format("received error notify for service %s", serviceEventKey), error);
}
} else {
Object message = event.getValue();
RegistryCacheValue cachedValue = value.get();
CachedStatus cachedStatus = cacheHandler.compareMessage(cachedValue, message);
if (cachedStatus == CachedStatus.CacheChanged || cachedStatus == CachedStatus.CacheNotExists) {
LOG.info("OnServiceUpdate: cache {} is pending to update", svcEventKey);
this.registry.saveMessageToFile(serviceEventKey, (Message) message);
RegistryCacheValue newCachedValue = cacheHandler.messageToCacheValue(cachedValue, message, false);
setValue(newCachedValue);
if (cachedStatus == CachedStatus.CacheChanged) {
for (ResourceEventListener listener : resourceEventListeners) {
listener.onResourceUpdated(svcEventKey, cachedValue, newCachedValue);
}
}
} else if (cachedStatus == CachedStatus.CacheEmptyButNoData) {
LOG.error("OnServiceUpdate: {} is empty, but discover returns no data", svcEventKey);
}
boolean newRemoteCache = null == cachedValue || cachedValue.isLoadedFromFile();
if (newRemoteCache && serviceEventKey.getEventType() == EventType.INSTANCE) {
// 设置就绪状态
registry.setServerServiceReady(serviceEventKey);
}
}
synchronized (lock) {
if (error != null && ErrorCode.SERVICE_NOT_FOUND.equals(error.getCode())) {
notifyEvent(null);
}
notifyEvent(error);
}
return svcDeleted;
}
use of com.tencent.polaris.api.pojo.ServiceEventKey in project polaris-java by polarismesh.
the class InMemoryRegistry method loadFileCache.
private void loadFileCache(String persistPath) {
LOG.info("start to load local cache files from {}", persistPath);
Map<ServiceEventKey, Message> loadCachedServices = messagePersistHandler.loadPersistedServices(ResponseProto.DiscoverResponse.getDefaultInstance());
for (Map.Entry<ServiceEventKey, Message> entry : loadCachedServices.entrySet()) {
ServiceEventKey svcEventKey = entry.getKey();
Message message = entry.getValue();
if (null == message) {
LOG.warn("load local cache, response is null, service event:{}", svcEventKey);
continue;
}
CacheHandler cacheHandler = cacheHandlers.get(svcEventKey.getEventType());
if (null == cacheHandler) {
LOG.warn("[LocalRegistry]resource type {} not registered, ignore the file", svcEventKey.getEventType());
continue;
}
CacheObject cacheObject = new CacheObject(cacheHandler, svcEventKey, this, message);
resourceMap.put(svcEventKey, cacheObject);
}
LOG.info("loaded {} services from local cache", loadCachedServices.size());
}
use of com.tencent.polaris.api.pojo.ServiceEventKey in project polaris-java by polarismesh.
the class InMemoryRegistry method updateInstances.
@Override
public void updateInstances(ServiceUpdateRequest request) {
Collection<InstanceProperty> instanceProperties = request.getProperties();
if (CollectionUtils.isEmpty(instanceProperties)) {
return;
}
RegistryCacheValue cacheValue = getResource(new ServiceEventKey(request.getServiceKey(), EventType.INSTANCE), true, true);
if (null == cacheValue) {
// 服务不存在,忽略
return;
}
for (InstanceProperty instanceProperty : instanceProperties) {
InstanceByProto instance = (InstanceByProto) instanceProperty.getInstance();
InstanceLocalValue instanceLocalValue = instance.getInstanceLocalValue();
Map<String, Object> properties = instanceProperty.getProperties();
LOG.info("update instance properties for instance {}, properties {}", instance.getId(), properties);
for (Map.Entry<String, Object> entry : properties.entrySet()) {
switch(entry.getKey()) {
case InstanceProperty.PROPERTY_CIRCUIT_BREAKER_STATUS:
onCircuitBreakStatus(entry.getValue(), instanceLocalValue, instance);
break;
case InstanceProperty.PROPERTY_DETECT_RESULT:
instanceLocalValue.setDetectResult((DetectResult) entry.getValue());
break;
default:
break;
}
}
}
}
Aggregations