Search in sources :

Example 1 with Instance

use of com.tencent.polaris.client.pb.ServiceProto.Instance in project polaris-java by polarismesh.

the class NamingService method buildServiceResponse.

private ResponseProto.DiscoverResponse buildServiceResponse(int code, String info, DiscoverRequest req) {
    ResponseProto.DiscoverResponse.Builder builder = ResponseProto.DiscoverResponse.newBuilder();
    builder.setCode(UInt32Value.newBuilder().setValue(code).build());
    CircuitBreakerProto.CircuitBreaker circuitBreaker;
    RateLimitProto.RateLimit rateLimit;
    RoutingProto.Routing routing;
    List<ServiceProto.Instance> instances;
    ServiceProto.Service service = req.getService();
    ServiceKey serviceKey = new ServiceKey(service.getNamespace().getValue(), service.getName().getValue());
    switch(req.getType()) {
        case UNKNOWN:
            break;
        case INSTANCE:
            instances = services.get(serviceKey);
            if (CollectionUtils.isNotEmpty(instances)) {
                builder.addAllInstances(instances);
            }
            builder.setType(DiscoverResponseType.INSTANCE);
            break;
        case CLUSTER:
            break;
        case ROUTING:
            routing = serviceRoutings.get(serviceKey);
            if (null != routing) {
                builder.setRouting(routing);
            }
            builder.setType(DiscoverResponseType.ROUTING);
            break;
        case CIRCUIT_BREAKER:
            circuitBreaker = serviceCircuitBreakers.get(serviceKey);
            if (null != circuitBreaker) {
                builder.setCircuitBreaker(circuitBreaker);
            }
            builder.setType(DiscoverResponseType.CIRCUIT_BREAKER);
            break;
        case RATE_LIMIT:
            rateLimit = serviceRateLimits.get(serviceKey);
            if (null != rateLimit) {
                builder.setRateLimit(rateLimit);
            }
            builder.setType(DiscoverResponseType.RATE_LIMIT);
            break;
        case SERVICES:
            Set<ServiceKey> keys = services.keySet();
            Map<String, ServiceProto.Service> tmp = new HashMap<>();
            String namespace = req.getService().getNamespace().getValue();
            System.out.println("get service param : " + namespace);
            keys.removeIf(serviceKey1 -> {
                if (StringUtils.isBlank(namespace)) {
                    return false;
                }
                return !Objects.equals(namespace, serviceKey1.getNamespace());
            });
            keys.forEach(key -> {
                tmp.put(key.getNamespace() + "##" + key.getService(), ServiceProto.Service.newBuilder().setNamespace(StringValue.newBuilder().setValue(key.getNamespace()).build()).setName(StringValue.newBuilder().setValue(key.getService()).build()).build());
            });
            final int[] index = { 0 };
            tmp.forEach((s, svc) -> {
                builder.addServices(index[0], svc);
                index[0]++;
            });
            builder.setType(DiscoverResponseType.SERVICES);
            break;
        case UNRECOGNIZED:
            break;
        default:
            break;
    }
    if (StringUtils.isNotBlank(info)) {
        builder.setInfo(StringValue.newBuilder().setValue(info).build());
    }
    builder.setService(service);
    return builder.build();
}
Also used : Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ServiceKey(com.tencent.polaris.api.pojo.ServiceKey) RateLimitProto(com.tencent.polaris.client.pb.RateLimitProto) RoutingProto(com.tencent.polaris.client.pb.RoutingProto) RateLimit(com.tencent.polaris.client.pb.RateLimitProto.RateLimit) CircuitBreaker(com.tencent.polaris.client.pb.CircuitBreakerProto.CircuitBreaker) CircuitBreakerProto(com.tencent.polaris.client.pb.CircuitBreakerProto) ServiceProto(com.tencent.polaris.client.pb.ServiceProto)

Example 2 with Instance

use of com.tencent.polaris.client.pb.ServiceProto.Instance in project polaris-java by polarismesh.

the class NamingService method registerInstance.

@Override
public void registerInstance(ServiceProto.Instance request, StreamObserver<ResponseProto.Response> responseObserver) {
    ServiceKey serviceKey = new ServiceKey(request.getNamespace().getValue(), request.getService().getValue());
    if (!services.containsKey(serviceKey)) {
        responseObserver.onNext(buildResponse(ServerCodes.NOT_FOUND_RESOURCE, String.format("service %s not found", serviceKey), request));
        responseObserver.onCompleted();
        return;
    }
    List<ServiceProto.Instance> instances = services.get(serviceKey);
    if (CollectionUtils.isNotEmpty(instances)) {
        for (ServiceProto.Instance instance : instances) {
            if (instance.getHost().getValue().equals(request.getHost().getValue()) && instance.getPort().getValue() == request.getPort().getValue()) {
                responseObserver.onNext(buildResponse(ServerCodes.EXISTED_RESOURCE, String.format("instance %s:%d exists", request.getHost().getValue(), request.getPort().getValue()), instance));
                responseObserver.onCompleted();
                return;
            }
        }
    }
    ServiceProto.Instance.Builder builder = ServiceProto.Instance.newBuilder();
    builder.mergeFrom(request);
    String instId = UUID.randomUUID().toString();
    builder.setId(StringValue.newBuilder().setValue(instId).build());
    ServiceProto.Instance nextInstance = builder.build();
    instances.add(nextInstance);
    ResponseProto.Response.Builder response = ResponseProto.Response.newBuilder();
    response.setCode(UInt32Value.newBuilder().setValue(ServerCodes.EXECUTE_SUCCESS).build());
    response.setInstance(nextInstance);
    responseObserver.onNext(response.build());
    responseObserver.onCompleted();
}
Also used : Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ServiceKey(com.tencent.polaris.api.pojo.ServiceKey) Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ServiceProto(com.tencent.polaris.client.pb.ServiceProto)

Example 3 with Instance

use of com.tencent.polaris.client.pb.ServiceProto.Instance in project polaris-java by polarismesh.

the class CompositeServiceUpdateTask method notifyServerEvent.

@Override
public boolean notifyServerEvent(ServerEvent serverEvent) {
    taskStatus.compareAndSet(Status.RUNNING, Status.READY);
    lastUpdateTime.set(System.currentTimeMillis());
    try {
        if (serverEvent.getValue() instanceof DiscoverResponse) {
            DiscoverResponse discoverResponse = (DiscoverResponse) serverEvent.getValue();
            DiscoverResponse.Builder newDiscoverResponseBuilder = DiscoverResponse.newBuilder().mergeFrom(discoverResponse);
            CompositeConnector connector = (CompositeConnector) serverConnector;
            if (EventType.INSTANCE.equals(serviceEventKey.getEventType())) {
                // Get instance information list except polaris.
                List<DefaultInstance> extendInstanceList = new ArrayList<>();
                for (DestroyableServerConnector sc : connector.getServerConnectors()) {
                    if (!DefaultPlugins.SERVER_CONNECTOR_GRPC.equals(sc.getName())) {
                        List<DefaultInstance> instanceList = sc.syncGetServiceInstances(this);
                        if (extendInstanceList.isEmpty()) {
                            extendInstanceList.addAll(instanceList);
                        } else {
                        // TODO 多数据源合并去重
                        }
                    }
                }
                // Merge instance information list
                List<Instance> polarisInstanceList = discoverResponse.getInstancesList();
                for (DefaultInstance i : extendInstanceList) {
                    boolean needAdd = true;
                    for (Instance j : polarisInstanceList) {
                        if (i.getHost().equals(j.getHost().getValue()) && i.getPort() == j.getPort().getValue()) {
                            needAdd = false;
                            break;
                        }
                    }
                    if (needAdd) {
                        Instance.Builder instanceBuilder = Instance.newBuilder().setNamespace(StringValue.of(serviceEventKey.getNamespace())).setService(StringValue.of(i.getService())).setHost(StringValue.of(i.getHost())).setPort(UInt32Value.of(i.getPort())).setHealthy(BoolValue.of(true));
                        if (StringUtils.isNotBlank(i.getId())) {
                            instanceBuilder.setId(StringValue.of(i.getId()));
                        }
                        newDiscoverResponseBuilder.addInstances(instanceBuilder.build());
                    }
                }
                if (!newDiscoverResponseBuilder.getInstancesList().isEmpty()) {
                    serverEvent.setError(null);
                }
            } else if (EventType.SERVICE.equals(serviceEventKey.getEventType())) {
                // Get instance information list except polaris.
                List<ServiceInfo> extendServiceList = new ArrayList<>();
                for (DestroyableServerConnector sc : connector.getServerConnectors()) {
                    if (!DefaultPlugins.SERVER_CONNECTOR_GRPC.equals(sc.getName())) {
                        Services services = sc.syncGetServices(this);
                        if (extendServiceList.isEmpty()) {
                            extendServiceList.addAll(services.getServices());
                        } else {
                        // TODO 多数据源合并去重
                        }
                    }
                }
                // Merge service information list
                List<Service> polarisServiceList = discoverResponse.getServicesList();
                for (ServiceInfo i : extendServiceList) {
                    boolean needAdd = true;
                    for (Service j : polarisServiceList) {
                        if (i.getService().equals(j.getName().getValue())) {
                            needAdd = false;
                            break;
                        }
                    }
                    if (needAdd) {
                        Service service = Service.newBuilder().setNamespace(StringValue.of(serviceEventKey.getNamespace())).setName(StringValue.of(i.getService())).build();
                        newDiscoverResponseBuilder.addServices(service);
                    }
                }
                if (!newDiscoverResponseBuilder.getServicesList().isEmpty()) {
                    serverEvent.setError(null);
                }
            }
            serverEvent.setValue(newDiscoverResponseBuilder.build());
        }
    } catch (PolarisException e) {
        LOG.error("Merge other server response failed.", e);
        serverEvent.setError(e);
    } catch (Throwable throwable) {
        LOG.error("Merge other server response failed.", throwable);
        serverEvent.setError(new PolarisException(ErrorCode.INTERNAL_ERROR));
    }
    if (null == serverEvent.getError()) {
        successUpdates.addAndGet(1);
    }
    return getEventHandler().onEventUpdate(serverEvent);
}
Also used : DefaultInstance(com.tencent.polaris.api.pojo.DefaultInstance) Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ArrayList(java.util.ArrayList) Service(com.tencent.polaris.client.pb.ServiceProto.Service) DiscoverResponse(com.tencent.polaris.client.pb.ResponseProto.DiscoverResponse) ServiceInfo(com.tencent.polaris.api.pojo.ServiceInfo) PolarisException(com.tencent.polaris.api.exception.PolarisException) Services(com.tencent.polaris.api.pojo.Services) DefaultInstance(com.tencent.polaris.api.pojo.DefaultInstance) ArrayList(java.util.ArrayList) List(java.util.List) DestroyableServerConnector(com.tencent.polaris.plugins.connector.common.DestroyableServerConnector)

Example 4 with Instance

use of com.tencent.polaris.client.pb.ServiceProto.Instance in project polaris-java by polarismesh.

the class NamingService method batchAddInstances.

/**
 * 批量增加服务实例
 *
 * @param svcKey 服务名
 * @param portStart 起始端口
 * @param instCount 实例数
 * @param parameter 实例参数
 * @return 批量服务实例的IP和端口
 */
public List<Node> batchAddInstances(ServiceKey svcKey, int portStart, int instCount, InstanceParameter parameter) {
    List<Node> nodes = new ArrayList<>();
    List<Instance> instances = new ArrayList<>();
    for (int i = 0; i < instCount; i++) {
        Node node = new Node("127.0.0.1", portStart + i);
        ServiceProto.Instance nextInstance = buildInstance(svcKey, node, parameter);
        instances.add(nextInstance);
        nodes.add(node);
    }
    List<Instance> existsInstances = services.get(svcKey);
    if (null == existsInstances) {
        services.put(svcKey, instances);
    } else {
        existsInstances.addAll(instances);
    }
    return nodes;
}
Also used : Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) Node(com.tencent.polaris.client.pojo.Node) ArrayList(java.util.ArrayList) Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ServiceProto(com.tencent.polaris.client.pb.ServiceProto)

Example 5 with Instance

use of com.tencent.polaris.client.pb.ServiceProto.Instance in project polaris-java by polarismesh.

the class NamingService method deregisterInstance.

@Override
public void deregisterInstance(ServiceProto.Instance request, StreamObserver<ResponseProto.Response> responseObserver) {
    ServiceKey serviceKey = new ServiceKey(request.getNamespace().getValue(), request.getService().getValue());
    if (!services.containsKey(serviceKey)) {
        responseObserver.onNext(buildResponse(ServerCodes.NOT_FOUND_RESOURCE, String.format("service %s not found", serviceKey), request));
        responseObserver.onCompleted();
        return;
    }
    int rIndex = -1;
    List<ServiceProto.Instance> instances = services.get(serviceKey);
    for (int i = 0; i < instances.size(); i++) {
        ServiceProto.Instance instance = instances.get(i);
        if (StringUtils.isNotBlank(request.getId().getValue())) {
            if (StringUtils.equals(request.getId().getValue(), request.getId().getValue())) {
                rIndex = i;
                break;
            }
        } else if (StringUtils.equals(request.getHost().getValue(), instance.getHost().getValue()) && request.getPort().getValue() == instance.getPort().getValue()) {
            rIndex = i;
            break;
        }
    }
    if (rIndex != -1) {
        instances.remove(rIndex);
    }
    if (CollectionUtils.isEmpty(instances)) {
        // 实例被删光则删除服务
        services.remove(serviceKey);
    }
    ResponseProto.Response.Builder response = ResponseProto.Response.newBuilder();
    response.setCode(UInt32Value.newBuilder().setValue(ServerCodes.EXECUTE_SUCCESS).build());
    response.setInstance(request);
    responseObserver.onNext(response.build());
    responseObserver.onCompleted();
}
Also used : Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ServiceKey(com.tencent.polaris.api.pojo.ServiceKey) Instance(com.tencent.polaris.client.pb.ServiceProto.Instance) ServiceProto(com.tencent.polaris.client.pb.ServiceProto)

Aggregations

Instance (com.tencent.polaris.client.pb.ServiceProto.Instance)6 ServiceProto (com.tencent.polaris.client.pb.ServiceProto)5 ServiceKey (com.tencent.polaris.api.pojo.ServiceKey)3 ArrayList (java.util.ArrayList)3 PolarisException (com.tencent.polaris.api.exception.PolarisException)1 DefaultInstance (com.tencent.polaris.api.pojo.DefaultInstance)1 ServiceInfo (com.tencent.polaris.api.pojo.ServiceInfo)1 Services (com.tencent.polaris.api.pojo.Services)1 CircuitBreakerProto (com.tencent.polaris.client.pb.CircuitBreakerProto)1 CircuitBreaker (com.tencent.polaris.client.pb.CircuitBreakerProto.CircuitBreaker)1 RateLimitProto (com.tencent.polaris.client.pb.RateLimitProto)1 RateLimit (com.tencent.polaris.client.pb.RateLimitProto.RateLimit)1 DiscoverResponse (com.tencent.polaris.client.pb.ResponseProto.DiscoverResponse)1 RoutingProto (com.tencent.polaris.client.pb.RoutingProto)1 Service (com.tencent.polaris.client.pb.ServiceProto.Service)1 Node (com.tencent.polaris.client.pojo.Node)1 DestroyableServerConnector (com.tencent.polaris.plugins.connector.common.DestroyableServerConnector)1 HashMap (java.util.HashMap)1 List (java.util.List)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1