Search in sources :

Example 6 with SSHException

use of com.sohu.cache.exception.SSHException in project new-cloud by xie-summer.

the class AppDataMigrateCenterImpl method showDataMigrateLog.

@Override
public String showDataMigrateLog(long id, int pageSize) {
    AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id);
    if (appDataMigrateStatus == null) {
        return "";
    }
    String logPath = appDataMigrateStatus.getLogPath();
    String host = appDataMigrateStatus.getMigrateMachineIp();
    StringBuilder command = new StringBuilder();
    command.append("/usr/bin/tail -n").append(pageSize).append(" ").append(logPath);
    try {
        return SSHUtil.execute(host, command.toString());
    } catch (SSHException e) {
        logger.error(e.getMessage(), e);
        return "";
    }
}
Also used : AppDataMigrateStatus(com.sohu.cache.entity.AppDataMigrateStatus) SSHException(com.sohu.cache.exception.SSHException)

Example 7 with SSHException

use of com.sohu.cache.exception.SSHException in project new-cloud by xie-summer.

the class SSHUtil method getMachineInfo.

/**
 * Get HostPerformanceEntity[cpuUsage, memUsage, load] by ssh.<br>
 * 方法返回前已经释放了所有资源,调用方不需要关心
 *
 * @param ip
 * @param userName
 * @param password
 * @throws Exception
 * @since 1.0.0
 */
public static MachineStats getMachineInfo(String ip, int port, String userName, String password) throws SSHException {
    if (StringUtil.isBlank(ip)) {
        try {
            throw new IllegalParamException("Param ip is empty!");
        } catch (IllegalParamException e) {
            throw new SSHException(e.getMessage(), e);
        }
    }
    port = IntegerUtil.defaultIfSmallerThan0(port, ConstUtils.SSH_PORT_DEFAULT);
    final MachineStats systemPerformanceEntity = new MachineStats();
    systemPerformanceEntity.setIp(ip);
    sshTemplate.execute(ip, port, userName, password, new SSHCallback() {

        @Override
        public Result call(SSHSession session) {
            // 解析top命令
            session.executeCommand(COMMAND_TOP, new DefaultLineProcessor() {

                @Override
                public void process(String line, int lineNum) throws Exception {
                    if (lineNum > 5) {
                        return;
                    }
                    if (1 == lineNum) {
                        // 第一行,通常是这样:
                        // top - 19:58:52 up 416 days, 30 min, 1 user, load average:
                        // 0.00, 0.00, 0.00
                        int loadAverageIndex = line.indexOf(LOAD_AVERAGE_STRING);
                        String loadAverages = line.substring(loadAverageIndex).replace(LOAD_AVERAGE_STRING, EMPTY_STRING);
                        String[] loadAverageArray = loadAverages.split(",");
                        if (3 == loadAverageArray.length) {
                            systemPerformanceEntity.setLoad(StringUtil.trimToEmpty(loadAverageArray[0]));
                        }
                    } else if (3 == lineNum) {
                        // 第三行通常是这样:
                        // , 0.0% sy, 0.0% ni, 100.0% id, 0.0% wa,
                        // 0.0% hi, 0.0% si
                        // redhat:%Cpu(s):  0.0 us
                        // centos7:Cpu(s): 0.0% us
                        double cpuUs = getUsCpu(line);
                        systemPerformanceEntity.setCpuUsage(String.valueOf(cpuUs));
                    }
                }
            });
            // 解析memory
            session.executeCommand(COMMAND_MEM, new LineProcessor() {

                private String totalMem;

                private String freeMem;

                private String buffersMem;

                private String cachedMem;

                @Override
                public void process(String line, int lineNum) throws Exception {
                    if (line.contains(MEM_TOTAL)) {
                        totalMem = matchMemLineNumber(line).trim();
                    } else if (line.contains(MEM_FREE)) {
                        freeMem = matchMemLineNumber(line).trim();
                    } else if (line.contains(MEM_BUFFERS)) {
                        buffersMem = matchMemLineNumber(line).trim();
                    } else if (line.contains(MEM_CACHED)) {
                        cachedMem = matchMemLineNumber(line).trim();
                    }
                }

                @Override
                public void finish() {
                    if (!StringUtil.isBlank(totalMem, freeMem, buffersMem)) {
                        Long totalMemLong = NumberUtils.toLong(totalMem);
                        Long freeMemLong = NumberUtils.toLong(freeMem);
                        Long buffersMemLong = NumberUtils.toLong(buffersMem);
                        Long cachedMemLong = NumberUtils.toLong(cachedMem);
                        Long usedMemFree = freeMemLong + buffersMemLong + cachedMemLong;
                        Double memoryUsage = 1 - (NumberUtils.toDouble(usedMemFree.toString()) / NumberUtils.toDouble(totalMemLong.toString()) / 1.0);
                        systemPerformanceEntity.setMemoryTotal(String.valueOf(totalMemLong));
                        systemPerformanceEntity.setMemoryFree(String.valueOf(usedMemFree));
                        DecimalFormat df = new DecimalFormat("0.00");
                        systemPerformanceEntity.setMemoryUsageRatio(df.format(memoryUsage * 100));
                    }
                }
            });
            // 统计磁盘使用状况
            /**
             * 内容通常是这样: Filesystem 容量 已用 可用 已用% 挂载点 /dev/xvda2 5.8G 3.2G 2.4G
             * 57% / /dev/xvda1 99M 8.0M 86M 9% /boot none 769M 0 769M 0%
             * /dev/shm /dev/xvda7 68G 7.1G 57G 12% /home /dev/xvda6 2.0G 36M
             * 1.8G 2% /tmp /dev/xvda5 2.0G 199M 1.7G 11% /var
             */
            session.executeCommand(COMMAND_DF_LH, new LineProcessor() {

                private Map<String, String> diskUsageMap = new HashMap<String, String>();

                @Override
                public void process(String line, int lineNum) throws Exception {
                    if (lineNum == 1) {
                        return;
                    }
                    line = line.replaceAll(" {1,}", WORD_SEPARATOR);
                    String[] lineArray = line.split(WORD_SEPARATOR);
                    if (6 == lineArray.length) {
                        String diskUsage = lineArray[4];
                        String mountedOn = lineArray[5];
                        diskUsageMap.put(mountedOn, diskUsage);
                    }
                }

                @Override
                public void finish() {
                    systemPerformanceEntity.setDiskUsageMap(diskUsageMap);
                }
            });
            return null;
        }
    });
    // 统计当前网络流量 @TODO
    Double traffic = 0.0;
    systemPerformanceEntity.setTraffic(traffic.toString());
    return systemPerformanceEntity;
}
Also used : DefaultLineProcessor(com.sohu.cache.ssh.SSHTemplate.DefaultLineProcessor) SSHCallback(com.sohu.cache.ssh.SSHTemplate.SSHCallback) DecimalFormat(java.text.DecimalFormat) MachineStats(com.sohu.cache.entity.MachineStats) LineProcessor(com.sohu.cache.ssh.SSHTemplate.LineProcessor) DefaultLineProcessor(com.sohu.cache.ssh.SSHTemplate.DefaultLineProcessor) SSHException(com.sohu.cache.exception.SSHException) Result(com.sohu.cache.ssh.SSHTemplate.Result) SSHSession(com.sohu.cache.ssh.SSHTemplate.SSHSession) IllegalParamException(com.sohu.cache.exception.IllegalParamException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with SSHException

use of com.sohu.cache.exception.SSHException in project new-cloud by xie-summer.

the class MachineCenterImpl method createRemoteFile.

/**
 * 根据content的配置内容创建配置文件,并推送到目标server的约定目录下;
 * 文件内容有更新,会覆写;
 *
 * @param host     要推送到的目标server;
 * @param fileName 配置文件名
 * @param content  配置文件的内容
 * @return 配置文件在远程server上的绝对路径,如果为null则表示失败;
 */
@Override
public String createRemoteFile(final String host, String fileName, List<String> content) {
    checkArgument(!Strings.isNullOrEmpty(host), "invalid host.");
    checkArgument(!Strings.isNullOrEmpty(fileName), "invalid fileName.");
    checkArgument(content != null && content.size() > 0, "content is empty.");
    String localAbsolutePath = MachineProtocol.TMP_DIR + fileName;
    File tmpDir = new File(MachineProtocol.TMP_DIR);
    if (!tmpDir.exists()) {
        if (!tmpDir.mkdirs()) {
            logger.error("cannot create /tmp/cachecloud directory.");
            return null;
        }
    }
    Path path = Paths.get(MachineProtocol.TMP_DIR + fileName);
    String remotePath = MachineProtocol.CONF_DIR + fileName;
    /**
     * 将配置文件的内容写到本地
     */
    try {
        BufferedWriter bufferedWriter = Files.newBufferedWriter(path, Charset.forName(MachineProtocol.ENCODING_UTF8));
        try {
            for (String line : content) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } finally {
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }
    } catch (IOException e) {
        logger.error("write redis config file error, ip: {}, filename: {}, content: {}, e", host, fileName, content, e);
        return null;
    } finally {
    }
    /**
     * 将配置文件推送到目标机器上
     */
    try {
        SSHUtil.scpFileToRemote(host, localAbsolutePath, MachineProtocol.CONF_DIR);
    } catch (SSHException e) {
        logger.error("scp config file to remote server error: ip: {}, fileName: {}", host, fileName, e);
        return null;
    }
    /**
     * 删除临时文件
     */
    File file = new File(localAbsolutePath);
    if (file.exists()) {
        file.delete();
    }
    return remotePath;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) File(java.io.File) BufferedWriter(java.io.BufferedWriter) SSHException(com.sohu.cache.exception.SSHException)

Example 9 with SSHException

use of com.sohu.cache.exception.SSHException in project cachecloud by sohutv.

the class MachineCenterImpl method createRemoteFile.

/**
 * 根据content的配置内容创建配置文件,并推送到目标server的约定目录下;
 * 文件内容有更新,会覆写;
 *
 * @param host     要推送到的目标server;
 * @param fileName 配置文件名
 * @param content  配置文件的内容
 * @return 配置文件在远程server上的绝对路径,如果为null则表示失败;
 */
@Override
public String createRemoteFile(final String host, String fileName, List<String> content) {
    checkArgument(!Strings.isNullOrEmpty(host), "invalid host.");
    checkArgument(!Strings.isNullOrEmpty(fileName), "invalid fileName.");
    checkArgument(content != null && content.size() > 0, "content is empty.");
    String localAbsolutePath = MachineProtocol.TMP_DIR + fileName;
    File tmpDir = new File(MachineProtocol.TMP_DIR);
    if (!tmpDir.exists()) {
        if (!tmpDir.mkdirs()) {
            logger.error("cannot create /tmp/cachecloud directory.");
            return null;
        }
    }
    Path path = Paths.get(MachineProtocol.TMP_DIR + fileName);
    String remotePath = MachineProtocol.CONF_DIR + fileName;
    /**
     * 将配置文件的内容写到本地
     */
    try {
        BufferedWriter bufferedWriter = Files.newBufferedWriter(path, Charset.forName(MachineProtocol.ENCODING_UTF8));
        try {
            for (String line : content) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } finally {
            if (bufferedWriter != null)
                bufferedWriter.close();
        }
    } catch (IOException e) {
        logger.error("write redis config file error, ip: {}, filename: {}, content: {}, e", host, fileName, content, e);
        return null;
    } finally {
    }
    /**
     * 将配置文件推送到目标机器上
     */
    try {
        SSHUtil.scpFileToRemote(host, localAbsolutePath, MachineProtocol.CONF_DIR);
    } catch (SSHException e) {
        logger.error("scp config file to remote server error: ip: {}, fileName: {}", host, fileName, e);
        return null;
    }
    /**
     * 删除临时文件
     */
    File file = new File(localAbsolutePath);
    if (file.exists()) {
        file.delete();
    }
    return remotePath;
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) File(java.io.File) BufferedWriter(java.io.BufferedWriter) SSHException(com.sohu.cache.exception.SSHException)

Example 10 with SSHException

use of com.sohu.cache.exception.SSHException in project cachecloud by sohutv.

the class AppDataMigrateCenterImpl method showDataMigrateConf.

@Override
public String showDataMigrateConf(long id) {
    AppDataMigrateStatus appDataMigrateStatus = appDataMigrateStatusDao.get(id);
    if (appDataMigrateStatus == null) {
        return "";
    }
    String configPath = appDataMigrateStatus.getConfigPath();
    String host = appDataMigrateStatus.getMigrateMachineIp();
    String command = "cat " + configPath;
    try {
        return SSHUtil.execute(host, command);
    } catch (SSHException e) {
        logger.error(e.getMessage(), e);
        return "";
    }
}
Also used : AppDataMigrateStatus(com.sohu.cache.entity.AppDataMigrateStatus) SSHException(com.sohu.cache.exception.SSHException)

Aggregations

SSHException (com.sohu.cache.exception.SSHException)10 AppDataMigrateStatus (com.sohu.cache.entity.AppDataMigrateStatus)4 BufferedWriter (java.io.BufferedWriter)4 File (java.io.File)4 IOException (java.io.IOException)4 Path (java.nio.file.Path)4 MachineStats (com.sohu.cache.entity.MachineStats)2 IllegalParamException (com.sohu.cache.exception.IllegalParamException)2 DefaultLineProcessor (com.sohu.cache.ssh.SSHTemplate.DefaultLineProcessor)2 LineProcessor (com.sohu.cache.ssh.SSHTemplate.LineProcessor)2 Result (com.sohu.cache.ssh.SSHTemplate.Result)2 SSHCallback (com.sohu.cache.ssh.SSHTemplate.SSHCallback)2 SSHSession (com.sohu.cache.ssh.SSHTemplate.SSHSession)2 DecimalFormat (java.text.DecimalFormat)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2