Search in sources :

Example 1 with ServiceEventKey

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);
    }
}
Also used : ResourceFilter(com.tencent.polaris.api.plugin.registry.ResourceFilter) ServiceInstances(com.tencent.polaris.api.pojo.ServiceInstances) Instance(com.tencent.polaris.api.pojo.Instance) HashMap(java.util.HashMap) ServiceUpdateRequest(com.tencent.polaris.api.plugin.registry.ServiceUpdateRequest) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) DetectResult(com.tencent.polaris.api.pojo.DetectResult)

Example 2 with ServiceEventKey

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);
}
Also used : ServiceRouter(com.tencent.polaris.api.plugin.route.ServiceRouter) DefaultServiceEventKeysProvider(com.tencent.polaris.api.pojo.DefaultServiceEventKeysProvider) HashMap(java.util.HashMap) LoadBalancer(com.tencent.polaris.api.plugin.loadbalance.LoadBalancer) Criteria(com.tencent.polaris.api.rpc.Criteria) ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) ServiceInstances(com.tencent.polaris.api.pojo.ServiceInstances) APIConfig(com.tencent.polaris.api.config.global.APIConfig) DefaultRouterChainGroup(com.tencent.polaris.api.plugin.compose.DefaultRouterChainGroup) RouterChainGroup(com.tencent.polaris.api.plugin.compose.RouterChainGroup) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) RouteInfo(com.tencent.polaris.api.plugin.route.RouteInfo) DefaultRouterChainGroup(com.tencent.polaris.api.plugin.compose.DefaultRouterChainGroup)

Example 3 with ServiceEventKey

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;
}
Also used : PolarisException(com.tencent.polaris.api.exception.PolarisException) RegistryCacheValue(com.tencent.polaris.api.pojo.RegistryCacheValue) CachedStatus(com.tencent.polaris.api.plugin.registry.CacheHandler.CachedStatus) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) ResourceEventListener(com.tencent.polaris.api.plugin.registry.ResourceEventListener)

Example 4 with ServiceEventKey

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());
}
Also used : Message(com.google.protobuf.Message) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) CacheHandler(com.tencent.polaris.api.plugin.registry.CacheHandler) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 5 with ServiceEventKey

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;
            }
        }
    }
}
Also used : InstanceByProto(com.tencent.polaris.client.pojo.InstanceByProto) RegistryCacheValue(com.tencent.polaris.api.pojo.RegistryCacheValue) InstanceLocalValue(com.tencent.polaris.api.pojo.InstanceLocalValue) InstanceProperty(com.tencent.polaris.api.plugin.registry.InstanceProperty) ServiceEventKey(com.tencent.polaris.api.pojo.ServiceEventKey) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

ServiceEventKey (com.tencent.polaris.api.pojo.ServiceEventKey)23 ServiceKey (com.tencent.polaris.api.pojo.ServiceKey)11 DefaultServiceEventKeysProvider (com.tencent.polaris.api.pojo.DefaultServiceEventKeysProvider)5 HashMap (java.util.HashMap)5 ServiceInstances (com.tencent.polaris.api.pojo.ServiceInstances)4 ResourcesResponse (com.tencent.polaris.client.flow.ResourcesResponse)4 ServiceInstancesByProto (com.tencent.polaris.client.pojo.ServiceInstancesByProto)4 PolarisException (com.tencent.polaris.api.exception.PolarisException)3 ResourceFilter (com.tencent.polaris.api.plugin.registry.ResourceFilter)3 RegistryCacheValue (com.tencent.polaris.api.pojo.RegistryCacheValue)3 Message (com.google.protobuf.Message)2 DefaultRouterChainGroup (com.tencent.polaris.api.plugin.compose.DefaultRouterChainGroup)2 CachedStatus (com.tencent.polaris.api.plugin.registry.CacheHandler.CachedStatus)2 RouteInfo (com.tencent.polaris.api.plugin.route.RouteInfo)2 ServiceRouter (com.tencent.polaris.api.plugin.route.ServiceRouter)2 Instance (com.tencent.polaris.api.pojo.Instance)2 EventType (com.tencent.polaris.api.pojo.ServiceEventKey.EventType)2 ServiceInfo (com.tencent.polaris.api.pojo.ServiceInfo)2 ServiceRule (com.tencent.polaris.api.pojo.ServiceRule)2 ServiceProto (com.tencent.polaris.client.pb.ServiceProto)2