Java tutorial
/* Copyright (C) 2011 NTT DATA Corporation This program is free software; you can redistribute it and/or Modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.clustercontrol.agent.job; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.clustercontrol.agent.Agent; import com.clustercontrol.agent.AgentEndPointWrapper; import com.clustercontrol.agent.SendQueue; import com.clustercontrol.agent.util.AgentProperties; import com.clustercontrol.jobmanagement.bean.RunStatusConstant; import com.clustercontrol.util.CommandCreator; import com.clustercontrol.util.CommandExecutor; import com.clustercontrol.util.CommandExecutor.CommandResult; import com.clustercontrol.util.HinemosTime; import com.clustercontrol.ws.jobmanagement.JobEnvVariableInfo; import com.clustercontrol.ws.jobmanagement.RunInstructionInfo; import com.clustercontrol.ws.jobmanagement.RunResultInfo; /** * ?<BR> * * ?????? ?????? * */ public class CommandThread extends AgentThread { // static private Log m_log = LogFactory.getLog(CommandThread.class); // ????? private String m_inputEncoding = null; // ? private boolean m_scriptDelete = false; private Process process = null; private CommandExecutor cmdExec = null; private RunResultInfo resultInfo; private String scriptDir = Agent.getAgentHome() + "script/";; private String scriptFile; private final String REPLACE_STARTCOMMAND = "#[SCRIPT]"; /** * ?? * * @param args */ public static void main(String[] args) { try { CommandExecutor executor1 = new CommandExecutor(new String[] { "hostname" }); //System.out.println(executor1.getResult(executor1.execute()).stdout); executor1.addEnvironment("HINEMOS_AGENT_HOME", Agent.getAgentHome()); executor1.execute(); System.out.println(executor1.getResult().stdout); } catch (Exception e) { e.printStackTrace(); } } /** * ? */ public CommandThread() { super(); } /** * * * @param info * * @param sendQueue * ? * @param runHistory * */ public CommandThread(RunInstructionInfo info, SendQueue sendQueue) { super(info, sendQueue); // ? m_inputEncoding = AgentProperties.getProperty("job.stream.charset"); if (m_inputEncoding == null) { m_inputEncoding = System.getProperty("file.encoding"); } // m_scriptDelete = Boolean.parseBoolean(AgentProperties.getProperty("job.script.delete", "true")); m_log.info("job.stream.charset = " + m_inputEncoding + " job.script.delete = " + m_scriptDelete); // --------------------------- // -- ? // --------------------------- // ? resultInfo = new RunResultInfo(); resultInfo.setSessionId(m_info.getSessionId()); resultInfo.setJobunitId(m_info.getJobunitId()); resultInfo.setJobId(m_info.getJobId()); resultInfo.setFacilityId(m_info.getFacilityId()); resultInfo.setCommand(m_info.getCommand()); resultInfo.setCommandType(m_info.getCommandType()); resultInfo.setStopType(m_info.getStopType()); resultInfo.setStatus(RunStatusConstant.START); resultInfo.setTime(HinemosTime.getDateInstance().getTime()); m_log.info("run SessionID=" + m_info.getSessionId() + ", JobID=" + m_info.getJobId()); // Hinemos??? /* ????????????? VIP???????????????????? ???????*/ try { if (!AgentEndPointWrapper.jobResult(resultInfo)) { // ???????? m_log.warn("This job already run by other agent. SessionID=" + m_info.getSessionId() + ", JobID=" + m_info.getJobId()); return; } } catch (Exception e) { m_log.error("CommandThread() : " + e.getMessage(), e); return; } //?? try { List<String> scriptInfo = AgentEndPointWrapper.getScript(m_info.getSessionId(), m_info.getJobunitId(), m_info.getJobId()); if (scriptInfo.size() == 3 && m_info.getCommand().contains(REPLACE_STARTCOMMAND)) { String scriptName = scriptInfo.get(0); String scriptEncoding = scriptInfo.get(1); String scriptContent = scriptInfo.get(2); scriptFile = scriptDir + m_info.getSessionId() + "_" + m_info.getJobId() + "_" + scriptName; createScriptFile(scriptContent, scriptEncoding); String replaceStartCommand = m_info.getCommand().replace(REPLACE_STARTCOMMAND, scriptFile); m_info.setCommand(replaceStartCommand); } } catch (Exception e) { m_log.error("CommandThread() : " + e.getMessage(), e); // deleteScript(); return; } // --------------------------- // -- ?(OS???) // --------------------------- String[] cmd = null; String mode = AgentProperties.getProperty("job.command.mode"); String loginFlagKey = "job.command.login"; boolean loginFlag = false; try { String loginFlagStr = AgentProperties.getProperty(loginFlagKey, "false"); loginFlag = Boolean.parseBoolean(loginFlagStr); } catch (Exception e) { m_log.warn(e.getMessage()); } /** ??????? */ try { CommandCreator.PlatformType platform = CommandCreator.convertPlatform(mode); cmd = CommandCreator.createCommand(m_info.getUser(), m_info.getCommand(), platform, m_info.isSpecifyUser(), loginFlag); // --------------------------- // -- // --------------------------- for (int i = 0; i < cmd.length; i++) { m_log.info("Command Execute [" + i + "] : " + cmd[i]); } if (cmd.length == 0) { m_log.warn("Command Execute : cmd.length=0"); } cmdExec = new CommandExecutor(cmd, Charset.forName(m_inputEncoding), CommandExecutor._disableTimeout, m_limit_jobmsg); // ???? // TODO ??????????????? cmdExec.addEnvironment("HINEMOS_AGENT_HOME", Agent.getAgentHome()); for (JobEnvVariableInfo env : info.getJobEnvVariableInfoList()) { cmdExec.addEnvironment(env.getEnvVariableId(), env.getValue()); } process = cmdExec.execute(); // ? RunHistoryUtil.addRunHistory(m_info, process); } catch (Exception e) { // ? // ? m_log.error("CommandThread() : " + e.getMessage()); // Windows???????????????????????? String errorMessage = e.getMessage(); String targetStr = "CreateProcess error=2, "; //Windows????????? int ptr = errorMessage.lastIndexOf(targetStr); if (ptr != -1) { // ?????????????? errorMessage = errorMessage.substring(0, ptr + targetStr.length()) + "No such file or directory"; } // ? RunResultInfo runErrorInfo = new RunResultInfo(); runErrorInfo.setSessionId(m_info.getSessionId()); runErrorInfo.setJobunitId(m_info.getJobunitId()); runErrorInfo.setJobId(m_info.getJobId()); runErrorInfo.setFacilityId(m_info.getFacilityId()); runErrorInfo.setCommand(m_info.getCommand()); runErrorInfo.setCommandType(m_info.getCommandType()); runErrorInfo.setStopType(m_info.getStopType()); runErrorInfo.setStatus(RunStatusConstant.ERROR); runErrorInfo.setTime(HinemosTime.getDateInstance().getTime()); runErrorInfo.setErrorMessage(errorMessage); runErrorInfo.setMessage(""); m_sendQueue.put(runErrorInfo); // RunHistoryUtil.delRunHistory(m_info); // deleteScript(); m_log.info("run end"); return; } } /** * ?<BR> * * ReceiveTopic??????????? ?????? * */ /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { m_log.debug("run start"); if (RunHistoryUtil.findRunHistory(m_info) == null) { // ? or m_log.info("run() : process is null"); return; } // CommandResult cmdResult = cmdExec.getResult(); if (cmdResult.exitCode != null) { resultInfo.setStatus(RunStatusConstant.END); resultInfo.setEndValue(cmdResult.exitCode); } else { resultInfo.setStatus(RunStatusConstant.ERROR); } // ? resultInfo.setTime(HinemosTime.getDateInstance().getTime()); resultInfo.setErrorMessage(cmdResult.stderr); resultInfo.setMessage(cmdResult.stdout); m_sendQueue.put(resultInfo); ////? RunHistoryUtil.delRunHistory(m_info); // if (m_scriptDelete) { deleteScript(); } m_log.debug("run end"); } private void createScriptFile(String scriptContent, String encoding) throws IOException { PrintWriter pw = null; try { File f = new File(scriptFile); pw = new PrintWriter(f, encoding); pw.print(scriptContent.replaceAll("\n", System.getProperty("line.separator"))); f.setExecutable(true, false); m_log.debug("createScriptFile() : " + scriptFile); } finally { if (pw != null) { pw.close(); } } } private void deleteScript() { if (scriptFile == null) { return; } File f = new File(scriptFile); if (f.exists()) { boolean ret = f.delete(); if (!ret) { m_log.warn("deleteScript error"); } } m_log.debug("deleteScript() : " + scriptFile); } }