package com.lanyuanxiaoyao.service.check.actions;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 检查
 *
 * @author lanyuanxiaoyao
 * @date 2024-02-22
 */
public abstract class Checker {
    private static final Logger logger = LoggerFactory.getLogger(Checker.class);

    public abstract void check() throws Exception;

    public abstract String description();

    protected boolean ping(String url) {
        String[] split = url.split(":");
        if (split.length != 2) {
            logger.error("Error url {}", url);
            return false;
        }
        InetSocketAddress address = NetUtil.createAddress(split[0], Integer.parseInt(split[1]));
        try {
            String command = StrUtil.format("ping {} -c 2 -w 2 -q", address.getHostString());
            Process exec = Runtime.getRuntime().exec(command);
            if (exec.waitFor(5, TimeUnit.SECONDS)) {
                return exec.exitValue() == 0;
            }
        } catch (Exception ignored) {
        }
        return false;
    }
}
