Search in sources :

Example 36 with Member

use of com.alibaba.nacos.core.cluster.Member in project nacos by alibaba.

the class ServerLoaderController method getServerLoadMetrics.

private Map<String, Object> getServerLoadMetrics() {
    List<ServerLoaderMetrics> responseList = new LinkedList<>();
    // default include self.
    int memberSize = serverMemberManager.allMembersWithoutSelf().size();
    CountDownLatch countDownLatch = new CountDownLatch(memberSize);
    for (Member member : serverMemberManager.allMembersWithoutSelf()) {
        if (MemberUtil.isSupportedLongCon(member)) {
            ServerLoaderInfoRequest serverLoaderInfoRequest = new ServerLoaderInfoRequest();
            try {
                clusterRpcClientProxy.asyncRequest(member, serverLoaderInfoRequest, new RequestCallBack() {

                    @Override
                    public Executor getExecutor() {
                        return null;
                    }

                    @Override
                    public long getTimeout() {
                        return 200L;
                    }

                    @Override
                    public void onResponse(Response response) {
                        if (response instanceof ServerLoaderInfoResponse) {
                            ServerLoaderMetrics metrics = new ServerLoaderMetrics();
                            metrics.setAddress(member.getAddress());
                            metrics.setMetric(((ServerLoaderInfoResponse) response).getLoaderMetrics());
                            responseList.add(metrics);
                        }
                        countDownLatch.countDown();
                    }

                    @Override
                    public void onException(Throwable e) {
                        LOGGER.error("Get metrics fail,member={}", member.getAddress(), e);
                        countDownLatch.countDown();
                    }
                });
            } catch (NacosException e) {
                LOGGER.error("Get metrics fail,member={}", member.getAddress(), e);
                countDownLatch.countDown();
            }
        } else {
            countDownLatch.countDown();
        }
    }
    try {
        ServerLoaderInfoResponse handle = serverLoaderInfoRequestHandler.handle(new ServerLoaderInfoRequest(), new RequestMeta());
        ServerLoaderMetrics metrics = new ServerLoaderMetrics();
        metrics.setAddress(serverMemberManager.getSelf().getAddress());
        metrics.setMetric(handle.getLoaderMetrics());
        responseList.add(metrics);
    } catch (NacosException e) {
        LOGGER.error("Get self metrics fail", e);
    }
    try {
        countDownLatch.await(1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        LOGGER.warn("Get  metrics timeout,metrics info may not complete.");
    }
    int max = 0;
    int min = -1;
    int total = 0;
    for (ServerLoaderMetrics serverLoaderMetrics : responseList) {
        String sdkConCountStr = serverLoaderMetrics.getMetric().get("sdkConCount");
        if (StringUtils.isNotBlank(sdkConCountStr)) {
            int sdkConCount = Integer.parseInt(sdkConCountStr);
            if (max == 0 || max < sdkConCount) {
                max = sdkConCount;
            }
            if (min == -1 || sdkConCount < min) {
                min = sdkConCount;
            }
            total += sdkConCount;
        }
    }
    Map<String, Object> responseMap = new HashMap<>(9);
    responseList.sort(Comparator.comparing(ServerLoaderMetrics::getAddress));
    responseMap.put("detail", responseList);
    responseMap.put("memberCount", serverMemberManager.allMembers().size());
    responseMap.put("metricsCount", responseList.size());
    responseMap.put("completed", responseList.size() == serverMemberManager.allMembers().size());
    responseMap.put("max", max);
    responseMap.put("min", min);
    responseMap.put("avg", total / responseList.size());
    responseMap.put("threshold", total / responseList.size() * 1.1);
    responseMap.put("total", total);
    return responseMap;
}
Also used : RequestCallBack(com.alibaba.nacos.api.remote.RequestCallBack) HashMap(java.util.HashMap) RequestMeta(com.alibaba.nacos.api.remote.request.RequestMeta) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) NacosException(com.alibaba.nacos.api.exception.NacosException) ServerLoaderInfoResponse(com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse) Response(com.alibaba.nacos.api.remote.response.Response) Executor(java.util.concurrent.Executor) ServerLoaderInfoResponse(com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse) ServerLoaderInfoRequest(com.alibaba.nacos.api.remote.request.ServerLoaderInfoRequest) Member(com.alibaba.nacos.core.cluster.Member)

Example 37 with Member

use of com.alibaba.nacos.core.cluster.Member in project nacos by alibaba.

the class NacosClusterV2Controller method listNodes.

/**
 * The console displays the list of cluster members.
 *
 * @param address match address
 * @param state match state
 *
 * @return members that matches condition
 */
@GetMapping(value = "/nodes")
public RestResult<Collection<Member>> listNodes(@RequestParam(value = "address", required = false) String address, @RequestParam(value = "state", required = false) String state) {
    NodeState nodeState = null;
    if (StringUtils.isNoneBlank(state)) {
        try {
            nodeState = NodeState.valueOf(state.toUpperCase(Locale.ROOT));
        } catch (IllegalArgumentException e) {
            return RestResultUtils.failedWithMsg(400, "Illegal state: " + state);
        }
    }
    Collection<Member> members = memberManager.allMembers();
    Collection<Member> result = new ArrayList<>();
    for (Member member : members) {
        if (StringUtils.isNoneBlank(address) && !StringUtils.startsWith(member.getAddress(), address)) {
            continue;
        }
        if (nodeState != null && member.getState() != nodeState) {
            continue;
        }
        result.add(member);
    }
    return RestResultUtils.success(result);
}
Also used : NodeState(com.alibaba.nacos.core.cluster.NodeState) ArrayList(java.util.ArrayList) Member(com.alibaba.nacos.core.cluster.Member) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 38 with Member

use of com.alibaba.nacos.core.cluster.Member in project nacos by alibaba.

the class ServerListManager method onReceiveServerStatus.

/**
 * Compatible with older version logic, In version 1.2.1 and before
 *
 * @param configInfo site:ip:lastReportTime:weight
 */
public synchronized void onReceiveServerStatus(String configInfo) {
    Loggers.SRV_LOG.info("receive config info: {}", configInfo);
    String[] configs = configInfo.split("\r\n");
    if (configs.length == 0) {
        return;
    }
    for (String config : configs) {
        // site:ip:lastReportTime:weight
        String[] params = config.split("#");
        if (params.length <= 3) {
            Loggers.SRV_LOG.warn("received malformed distro map data: {}", config);
            continue;
        }
        String[] info = InternetAddressUtil.splitIPPortStr(params[1]);
        Member server = Optional.ofNullable(memberManager.find(params[1])).orElse(Member.builder().ip(info[0]).state(NodeState.UP).port(Integer.parseInt(info[1])).build());
        // This metadata information exists from 1.3.0 onwards "version"
        if (server.getExtendVal(MemberMetaDataConstants.VERSION) == null) {
            // copy to trigger member change event
            server = server.copy();
            // received heartbeat from server of version before 1.3.0
            if (!server.getState().equals(NodeState.UP)) {
                Loggers.SRV_LOG.info("member {} state changed to UP", server);
            }
            server.setState(NodeState.UP);
        }
        server.setExtendVal(MemberMetaDataConstants.SITE_KEY, params[0]);
        server.setExtendVal(MemberMetaDataConstants.WEIGHT, params.length == 4 ? Integer.parseInt(params[3]) : 1);
        memberManager.update(server);
        if (!contains(server.getAddress())) {
            throw new IllegalArgumentException("server: " + server.getAddress() + " is not in serverlist");
        }
    }
}
Also used : Member(com.alibaba.nacos.core.cluster.Member)

Example 39 with Member

use of com.alibaba.nacos.core.cluster.Member in project nacos by alibaba.

the class JRaftProtocol method injectProtocolMetaData.

private void injectProtocolMetaData(ProtocolMetaData metaData) {
    Member member = memberManager.getSelf();
    member.setExtendVal("raftMetaData", metaData);
    memberManager.update(member);
}
Also used : Member(com.alibaba.nacos.core.cluster.Member)

Example 40 with Member

use of com.alibaba.nacos.core.cluster.Member in project nacos by alibaba.

the class UpgradeJudgement method onEvent.

@Override
public void onEvent(MembersChangeEvent event) {
    if (!event.hasTriggers()) {
        Loggers.SRV_LOG.info("Member change without no trigger. " + "It may be triggered by member lookup on startup. " + "Skip.");
        return;
    }
    Loggers.SRV_LOG.info("member change, event: {}", event);
    for (Member each : event.getTriggers()) {
        Object versionStr = each.getExtendVal(MemberMetaDataConstants.VERSION);
        // come from below 1.3.0
        if (null == versionStr) {
            checkAndDowngrade(false);
            all20XVersion.set(false);
            return;
        }
        Version version = VersionUtil.parseVersion(versionStr.toString());
        if (version.getMajorVersion() < MAJOR_VERSION) {
            checkAndDowngrade(version.getMinorVersion() >= MINOR_VERSION);
            all20XVersion.set(false);
            return;
        }
    }
    all20XVersion.set(true);
}
Also used : Version(org.codehaus.jackson.Version) Member(com.alibaba.nacos.core.cluster.Member)

Aggregations

Member (com.alibaba.nacos.core.cluster.Member)53 Test (org.junit.Test)17 NacosException (com.alibaba.nacos.api.exception.NacosException)11 HashMap (java.util.HashMap)11 Response (com.alibaba.nacos.api.remote.response.Response)8 CountDownLatch (java.util.concurrent.CountDownLatch)7 DistroDataRequest (com.alibaba.nacos.naming.cluster.remote.request.DistroDataRequest)6 Map (java.util.Map)5 ServerLoaderInfoResponse (com.alibaba.nacos.api.remote.response.ServerLoaderInfoResponse)4 NacosAsyncRestTemplate (com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate)4 DistroDataResponse (com.alibaba.nacos.naming.cluster.remote.response.DistroDataResponse)4 ArrayList (java.util.ArrayList)4 Collection (java.util.Collection)4 Before (org.junit.Before)4 GetMapping (org.springframework.web.bind.annotation.GetMapping)4 ServerAbilities (com.alibaba.nacos.api.ability.ServerAbilities)3 RequestCallBack (com.alibaba.nacos.api.remote.RequestCallBack)3 ServerRemoteAbility (com.alibaba.nacos.api.remote.ability.ServerRemoteAbility)3 RestResult (com.alibaba.nacos.common.model.RestResult)3 GenericType (com.alibaba.nacos.core.utils.GenericType)3