Search in sources :

Example 6 with MachineInfo

use of com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo in project spring-boot-student by wyh-spring-ecosystem-student.

the class MetricFetcher method fetchOnce.

/**
 * fetch metric between [startTime, endTime], both side inclusive
 */
private void fetchOnce(String app, long startTime, long endTime, int maxWaitSeconds) {
    if (maxWaitSeconds <= 0) {
        throw new IllegalArgumentException("maxWaitSeconds must > 0, but " + maxWaitSeconds);
    }
    AppInfo appInfo = appManagement.getDetailApp(app);
    // auto remove for app
    if (appInfo.isDead()) {
        logger.info("Dead app removed: {}", app);
        appManagement.removeApp(app);
        return;
    }
    Set<MachineInfo> machines = appInfo.getMachines();
    logger.debug("enter fetchOnce(" + app + "), machines.size()=" + machines.size() + ", time intervalMs [" + startTime + ", " + endTime + "]");
    if (machines.isEmpty()) {
        return;
    }
    final String msg = "fetch";
    AtomicLong unhealthy = new AtomicLong();
    final AtomicLong success = new AtomicLong();
    final AtomicLong fail = new AtomicLong();
    long start = System.currentTimeMillis();
    /**
     * app_resource_timeSecond -> metric
     */
    final Map<String, MetricEntity> metricMap = new ConcurrentHashMap<>(16);
    final CountDownLatch latch = new CountDownLatch(machines.size());
    for (final MachineInfo machine : machines) {
        // auto remove
        if (machine.isDead()) {
            latch.countDown();
            appManagement.getDetailApp(app).removeMachine(machine.getIp(), machine.getPort());
            logger.info("Dead machine removed: {}:{} of {}", machine.getIp(), machine.getPort(), app);
            continue;
        }
        if (!machine.isHealthy()) {
            latch.countDown();
            unhealthy.incrementAndGet();
            continue;
        }
        final String url = "http://" + machine.getIp() + ":" + machine.getPort() + "/" + METRIC_URL_PATH + "?startTime=" + startTime + "&endTime=" + endTime + "&refetch=" + false;
        final HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
        httpclient.execute(httpGet, new FutureCallback<HttpResponse>() {

            @Override
            public void completed(final HttpResponse response) {
                try {
                    handleResponse(response, machine, metricMap);
                    success.incrementAndGet();
                } catch (Exception e) {
                    logger.error(msg + " metric " + url + " error:", e);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void failed(final Exception ex) {
                latch.countDown();
                fail.incrementAndGet();
                httpGet.abort();
                if (ex instanceof SocketTimeoutException) {
                    logger.error("Failed to fetch metric from <{}>: socket timeout", url);
                } else if (ex instanceof ConnectException) {
                    logger.error("Failed to fetch metric from <{}> (ConnectionException: {})", url, ex.getMessage());
                } else {
                    logger.error(msg + " metric " + url + " error", ex);
                }
            }

            @Override
            public void cancelled() {
                latch.countDown();
                fail.incrementAndGet();
                httpGet.abort();
            }
        });
    }
    try {
        latch.await(maxWaitSeconds, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.info(msg + " metric, wait http client error:", e);
    }
    long cost = System.currentTimeMillis() - start;
    // logger.info("finished " + msg + " metric for " + app + ", time intervalMs [" + startTime + ", " + endTime
    // + "], total machines=" + machines.size() + ", dead=" + dead + ", fetch success="
    // + success + ", fetch fail=" + fail + ", time cost=" + cost + " ms");
    writeMetric(metricMap);
}
Also used : MetricEntity(com.alibaba.csp.sentinel.dashboard.datasource.entity.MetricEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) CountDownLatch(java.util.concurrent.CountDownLatch) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) AppInfo(com.alibaba.csp.sentinel.dashboard.discovery.AppInfo) MachineInfo(com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo) AtomicLong(java.util.concurrent.atomic.AtomicLong) SocketTimeoutException(java.net.SocketTimeoutException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConnectException(java.net.ConnectException)

Example 7 with MachineInfo

use of com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo in project spring-boot-student by wyh-spring-ecosystem-student.

the class AppController method getMachinesByApp.

@GetMapping(value = "/{app}/machines.json")
public Result<List<MachineInfoVo>> getMachinesByApp(@PathVariable("app") String app) {
    AppInfo appInfo = appManagement.getDetailApp(app);
    if (appInfo == null) {
        return Result.ofSuccess(null);
    }
    List<MachineInfo> list = new ArrayList<>(appInfo.getMachines());
    Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp).thenComparingInt(MachineInfo::getPort));
    return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list));
}
Also used : MachineInfo(com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo) ArrayList(java.util.ArrayList) AppInfo(com.alibaba.csp.sentinel.dashboard.discovery.AppInfo) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 8 with MachineInfo

use of com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo in project XHuiCloud by sindaZeng.

the class AppController method getMachinesByApp.

@GetMapping(value = "/{app}/machines.json")
public Result<List<MachineInfoVo>> getMachinesByApp(@PathVariable("app") String app) {
    AppInfo appInfo = appManagement.getDetailApp(app);
    if (appInfo == null) {
        return Result.ofSuccess(null);
    }
    List<MachineInfo> list = new ArrayList<>(appInfo.getMachines());
    Collections.sort(list, Comparator.comparing(MachineInfo::getApp).thenComparing(MachineInfo::getIp).thenComparingInt(MachineInfo::getPort));
    return Result.ofSuccess(MachineInfoVo.fromMachineInfoList(list));
}
Also used : MachineInfo(com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo) ArrayList(java.util.ArrayList) AppInfo(com.alibaba.csp.sentinel.dashboard.discovery.AppInfo) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 9 with MachineInfo

use of com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo in project XHuiCloud by sindaZeng.

the class MachineRegistryController method receiveHeartBeat.

@ResponseBody
@RequestMapping("/machine")
public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) {
    if (app == null) {
        app = MachineDiscovery.UNKNOWN_APP_NAME;
    }
    if (ip == null) {
        return Result.ofFail(-1, "ip can't be null");
    }
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    if (port == -1) {
        logger.info("Receive heartbeat from " + ip + " but port not set yet");
        return Result.ofFail(-1, "your port not set yet");
    }
    String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v;
    version = version == null ? System.currentTimeMillis() : version;
    try {
        MachineInfo machineInfo = new MachineInfo();
        machineInfo.setApp(app);
        machineInfo.setAppType(appType);
        machineInfo.setHostname(hostname);
        machineInfo.setIp(ip);
        machineInfo.setPort(port);
        machineInfo.setHeartbeatVersion(version);
        machineInfo.setLastHeartbeat(System.currentTimeMillis());
        machineInfo.setVersion(sentinelVersion);
        appManagement.addMachine(machineInfo);
        return Result.ofSuccessMsg("success");
    } catch (Exception e) {
        logger.error("Receive heartbeat error", e);
        return Result.ofFail(-1, e.getMessage());
    }
}
Also used : MachineInfo(com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with MachineInfo

use of com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo in project XHuiCloud by sindaZeng.

the class MachineEntity method toMachineInfo.

public MachineInfo toMachineInfo() {
    MachineInfo machineInfo = new MachineInfo();
    machineInfo.setApp(app);
    machineInfo.setHostname(hostname);
    machineInfo.setIp(ip);
    machineInfo.setPort(port);
    machineInfo.setLastHeartbeat(timestamp.getTime());
    machineInfo.setHeartbeatVersion(timestamp.getTime());
    return machineInfo;
}
Also used : MachineInfo(com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo)

Aggregations

MachineInfo (com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo)20 AppInfo (com.alibaba.csp.sentinel.dashboard.discovery.AppInfo)10 MetricEntity (com.alibaba.csp.sentinel.dashboard.datasource.entity.MetricEntity)5 ConnectException (java.net.ConnectException)5 SocketTimeoutException (java.net.SocketTimeoutException)5 ArrayList (java.util.ArrayList)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicLong (java.util.concurrent.atomic.AtomicLong)5 HttpResponse (org.apache.http.HttpResponse)5 HttpGet (org.apache.http.client.methods.HttpGet)5 GetMapping (org.springframework.web.bind.annotation.GetMapping)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)5