合并,解决冲突

glusterfs-api
chenlw 9 years ago
commit 355b6e47a4

@ -1,228 +1,228 @@
package com.platform.controller; package com.platform.controller;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.base.BaseController; import com.base.BaseController;
import com.platform.entities.DataInfoEntity; import com.platform.entities.DataInfoEntity;
import com.platform.entities.FolderNode; import com.platform.entities.FolderNode;
import com.platform.entities.GatherOracleInfo; import com.platform.entities.GatherOracleInfo;
import com.platform.entities.OracleConnectorParams; import com.platform.entities.OracleConnectorParams;
import com.platform.entities.PagerOptions; import com.platform.entities.PagerOptions;
import com.platform.entities.VolumeEntity; import com.platform.entities.VolumeEntity;
import com.platform.service.DataInfoService; import com.platform.service.DataInfoService;
import com.platform.service.IGfsService; import com.platform.service.IGfsService;
import com.platform.service.IMySqlService; import com.platform.service.IMySqlService;
import com.platform.service.IOracleExtractService; import com.platform.service.IOracleExtractService;
import com.platform.service.OracleExtractHelper; import com.platform.service.OracleExtractHelper;
import com.platform.service.OracleStatusService; import com.platform.service.OracleStatusService;
import com.platform.service.impl.MySqlServiceImpl; import com.platform.service.impl.MySqlServiceImpl;
import com.platform.test.Brick; import com.platform.test.Brick;
import com.platform.test.FolderReader; import com.platform.test.FolderReader;
import com.platform.test.Volume; import com.platform.test.Volume;
import com.platform.utils.Configs; import com.platform.utils.Configs;
import com.platform.utils.UtilsHelper; import com.platform.utils.UtilsHelper;
@Controller @Controller
public class DataModelController extends BaseController{ public class DataModelController extends BaseController{
@Resource(name = "dataInfoService") @Resource(name = "dataInfoService")
private DataInfoService dfs; private DataInfoService dfs;
@Resource(name = "gfsService") @Resource(name = "gfsService")
private IGfsService gfsService; private IGfsService gfsService;
@Resource(name = "mySqlService") @Resource(name = "mySqlService")
private IMySqlService mySqlService; private IMySqlService mySqlService;
@Resource(name = "OracleExtract") @Resource(name = "OracleExtract")
private IOracleExtractService OracleExtract; private IOracleExtractService OracleExtract;
public void setDfsImp(DataInfoService dfs) { public void setDfsImp(DataInfoService dfs) {
this.dfs = dfs; this.dfs = dfs;
} }
@RequestMapping("/data.json") @RequestMapping("/data.json")
@ResponseBody @ResponseBody
public ModelMap getAllDataToJson(HttpServletRequest res, public ModelMap getAllDataToJson(HttpServletRequest res,
HttpServletResponse req) { HttpServletResponse req) {
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
Set<String> keySet = paramMap.keySet(); Set<String> keySet = paramMap.keySet();
Map<String, String> params = new HashMap<String, String>(); Map<String, String> params = new HashMap<String, String>();
StringBuffer sb = new StringBuffer().append("<22><>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>:{"); StringBuffer sb = new StringBuffer().append("<22><>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>:{");
for (String str : keySet) { for (String str : keySet) {
String value = paramMap.get(str)[0]; String value = paramMap.get(str)[0];
if (StringUtils.isNotEmpty(value)) { if (StringUtils.isNotEmpty(value)) {
params.put(str, value); params.put(str, value);
sb.append(str).append(":").append(value).append(","); sb.append(str).append(":").append(value).append(",");
} else { } else {
sb.append(str).append(":").append("null").append(","); sb.append(str).append(":").append("null").append(",");
} }
} }
Configs.CONSOLE_LOGGER.info(sb.deleteCharAt(sb.length() - 1) Configs.CONSOLE_LOGGER.info(sb.deleteCharAt(sb.length() - 1)
.append("}").toString()); .append("}").toString());
PagerOptions pagerOptions = (PagerOptions) UtilsHelper PagerOptions pagerOptions = (PagerOptions) UtilsHelper
.newObjAndSetAttrsByClass(PagerOptions.class, params); .newObjAndSetAttrsByClass(PagerOptions.class, params);
return dfs.getPagerTableData(pagerOptions); return dfs.getPagerTableData(pagerOptions);
} }
@RequestMapping("/delete/data") @RequestMapping("/delete/data")
public void deleteData(HttpServletRequest res, HttpServletResponse req) { public void deleteData(HttpServletRequest res, HttpServletResponse req) {
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
String[] data = paramMap.get("data"); String[] data = paramMap.get("data");
dfs.deleteData(data); dfs.deleteData(data);
} }
@RequestMapping("/connectOracle") @RequestMapping("/connectOracle")
public void connectOracle(HttpServletRequest res, HttpServletResponse req) { public void connectOracle(HttpServletRequest res, HttpServletResponse req) {
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
String[] oraclesName = paramMap.get("oracleName"); String[] oraclesName = paramMap.get("oracleName");
if (oraclesName != null) if (oraclesName != null)
for (String rcName : oraclesName) { for (String rcName : oraclesName) {
Configs.CONSOLE_LOGGER.info("连接成功\t" + rcName); Configs.CONSOLE_LOGGER.info("连接成功\t" + rcName);
new OracleStatusService().connectToOracle(rcName); new OracleStatusService().connectToOracle(rcName);
} }
} }
@RequestMapping("/cancelOracleConection") @RequestMapping("/cancelOracleConection")
public void cancelOracleConnection(HttpServletRequest res, public void cancelOracleConnection(HttpServletRequest res,
HttpServletResponse req) { HttpServletResponse req) {
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
String[] oraclesName = paramMap.get("oracleName"); String[] oraclesName = paramMap.get("oracleName");
String operate = paramMap.get("operation")[0]; String operate = paramMap.get("operation")[0];
if (null != oraclesName) { if (null != oraclesName) {
for (String rcName : oraclesName) { for (String rcName : oraclesName) {
Configs.CONSOLE_LOGGER.info("连接成功:\t" + rcName); Configs.CONSOLE_LOGGER.info("连接成功:\t" + rcName);
new OracleStatusService().cancelToOracle(rcName, operate); new OracleStatusService().cancelToOracle(rcName, operate);
} }
} }
} }
@RequestMapping("/oracle/{name}/extract") @RequestMapping("/oracle/{name}/extract")
public void extractOracleData(HttpServletRequest res, public void extractOracleData(HttpServletRequest res,
HttpServletResponse req, String name) throws Exception { HttpServletResponse req, String name) throws Exception {
System.out.println("------extract-------"); System.out.println("------extract-------");
System.out.println(name); System.out.println(name);
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
//汇总库 对象信息--带有tableName- //汇总库 对象信息--带有tableName-
String[] nodes = paramMap.get("target"); String[] nodes = paramMap.get("target");
Map map = null; Map map = null;
for (String string : nodes) { for (String string : nodes) {
JSONObject jsonobject = JSONObject.fromObject(string); JSONObject jsonobject = JSONObject.fromObject(string);
map = jsonobject; map = jsonobject;
System.out.println(map); System.out.println(map);
} }
// 采集库对象--(多个采集库抽取到1个汇总库的1个tableName下) // 采集库对象--(多个采集库抽取到1个汇总库的1个tableName下)
String[] inneed = paramMap.get("inneed"); String[] inneed = paramMap.get("inneed");
List<Map<String, String>> colleclist = new ArrayList<Map<String,String>>(); List<Map<String, String>> colleclist = new ArrayList<Map<String,String>>();
for (String string : nodes) { for (String string : nodes) {
JSONObject jsonobject = JSONObject.fromObject(string); JSONObject jsonobject = JSONObject.fromObject(string);
Map inneedMap = jsonobject; Map inneedMap = jsonobject;
colleclist.add(inneedMap); colleclist.add(inneedMap);
} }
OracleExtract.extractOracle(name, colleclist, map); OracleExtract.extractOracle(name, colleclist, map);
} }
@RequestMapping("/volume/list") @RequestMapping("/volume/list")
@ResponseBody @ResponseBody
public List<VolumeEntity> getFolder(HttpServletRequest res, HttpServletResponse req) throws Exception { public List<VolumeEntity> getFolder(HttpServletRequest res, HttpServletResponse req) throws Exception {
System.out.println("get Request"); System.out.println("get Request");
// Brick brick1 = new Brick("192.168.0.101", "D:/bootstrap"); // Brick brick1 = new Brick("192.168.0.101", "D:/bootstrap");
// Brick brick2 = new Brick("192.168.0.103", "D:\book"); // Brick brick2 = new Brick("192.168.0.103", "D:\book");
// List<Brick> bricks = new ArrayList<Brick>(); // List<Brick> bricks = new ArrayList<Brick>();
// bricks.add(brick1); // bricks.add(brick1);
// bricks.add(brick2); // bricks.add(brick2);
List<VolumeEntity> result = gfsService.getAllVolumes(); List<VolumeEntity> result = gfsService.getAllVolumes();
return result; return result;
} }
@RequestMapping(value = "/volume/{name}/move", method= RequestMethod.POST) @RequestMapping(value = "/volume/{name}/move", method= RequestMethod.POST)
@ResponseBody @ResponseBody
public Object move(HttpServletRequest res, HttpServletResponse req, String name, public Object move(HttpServletRequest res, HttpServletResponse req, String name,
FolderNode selectNode, DataInfoEntity selectItems) throws Exception { FolderNode selectNode, DataInfoEntity selectItems) throws Exception {
System.out.println("get Request"); System.out.println("get Request");
Map<String, String[]> paramMap = res.getParameterMap(); Map<String, String[]> paramMap = res.getParameterMap();
// System.out.println(paramMap); // System.out.println(paramMap);
String[] nodes = paramMap.get("selectNode"); String[] nodes = paramMap.get("selectNode");
Map map = null; Map map = null;
for (String string : nodes) { for (String string : nodes) {
System.out.println(string); System.out.println(string);
JSONObject jsonobject = JSONObject.fromObject(string); JSONObject jsonobject = JSONObject.fromObject(string);
map = jsonobject; map = jsonobject;
} }
List<String> listItemPath = new ArrayList<String>(); List<String> listItemPath = new ArrayList<String>();
String[] items = paramMap.get("selectItems"); String[] items = paramMap.get("selectItems");
System.out.println("selectItems"); System.out.println("selectItems");
for (String string : items) { for (String string : items) {
System.out.println(string); System.out.println(string);
JSONObject jsobj = JSONObject.fromObject(string); JSONObject jsobj = JSONObject.fromObject(string);
Map itemmap = jsobj; Map itemmap = jsobj;
listItemPath.add((String)itemmap.get("dataPath")); listItemPath.add((String)itemmap.get("dataPath"));
} }
System.out.println(name); System.out.println(name);
System.out.println(nodes); System.out.println(nodes);
System.out.println(selectItems); System.out.println(selectItems);
System.out.println("--------------"); System.out.println("--------------");
int result = gfsService.copyFolder(listItemPath, (String)map.get("path"), "app"); int result = gfsService.copyFolder(listItemPath, (String)map.get("path"), "app");
return result; return result;
} }
@RequestMapping("/oracle/list") @RequestMapping("/oracle/list")
@ResponseBody @ResponseBody
public List<GatherOracleInfo> getOracleInfo(HttpServletRequest res, public List<GatherOracleInfo> getOracleInfo(HttpServletRequest res,
HttpServletResponse req) throws Exception { HttpServletResponse req) throws Exception {
List<GatherOracleInfo> result = mySqlService.findAllMySql(); List<GatherOracleInfo> result = mySqlService.findAllMySql();
System.out.println("----------getOracleInfo-----------------------"); System.out.println("----------getOracleInfo-----------------------");
return result; return result;
} }
@RequestMapping("/oracle/{id}/delete") @RequestMapping("/oracle/{id}/delete")
@ResponseBody @ResponseBody
public void deleteOracleInfo(HttpServletRequest res, public void deleteOracleInfo(HttpServletRequest res,
HttpServletResponse req, int id) throws Exception { HttpServletResponse req, int id) throws Exception {
mySqlService.deleteMySql(id); mySqlService.deleteMySql(id);
System.out.println("----------deleteOracleInfo-----------------------"); System.out.println("----------deleteOracleInfo-----------------------");
} }
@RequestMapping("/oracle/{id}/insert") @RequestMapping("/oracle/{id}/insert")
@ResponseBody @ResponseBody
public void insertOracleInfo(HttpServletRequest res, public void insertOracleInfo(HttpServletRequest res,
HttpServletResponse req, GatherOracleInfo oracle) throws Exception { HttpServletResponse req, GatherOracleInfo oracle) throws Exception {
mySqlService.insertOracle(oracle); mySqlService.insertOracle(oracle);
System.out.println("----------insertOracleInfo-----------------------"); System.out.println("----------insertOracleInfo-----------------------");
} }
@RequestMapping("/oracle/{id}/update") @RequestMapping("/oracle/{id}/update")
@ResponseBody @ResponseBody
public void updateOracleInfo(HttpServletRequest res, public void updateOracleInfo(HttpServletRequest res,
HttpServletResponse req, GatherOracleInfo oracle) throws Exception { HttpServletResponse req, GatherOracleInfo oracle) throws Exception {
mySqlService.updateOracle(oracle); mySqlService.updateOracle(oracle);
System.out.println("----------updateOracleInfo-----------------------"); System.out.println("----------updateOracleInfo-----------------------");
} }
} }

@ -1,91 +1,93 @@
/** /**
* : Brick.java * : Brick.java
* : </> * : </>
* : <> * : <>
* @author chen * @author chen
* : <> * : <>
* 201699 * 201699
* <> * <>
*/ */
package com.platform.entities; package com.platform.entities;
/** /**
* <> volume * <> volume
* <> * <>
* @author chen * @author chen
* @version [201699] * @version [201699]
* @see [/] * @see [/]
* @since [/] * @since [/]
*/ */
public class Brick { public class Brick {
/** volume总大小 */ /** volume总大小 */
private double availableSize; private double availableSize;
/** volume已使用大小 */ /** volume已使用大小 */
private double usedSize; private double usedSize;
/** ip */
private String ip; /** ip */
private String ip;
/** 路径 */
private String path; /** 路径 */
private String path;
/**
* @return the availableSize /**
*/ * @return the availableSize
public double getAvailableSize() { */
return availableSize; public double getAvailableSize() {
} return availableSize;
}
/**
* @param availableSize the availableSize to set /**
*/ * @param availableSize the availableSize to set
public void setAvailableSize(double availableSize) { */
this.availableSize = availableSize; public void setAvailableSize(double availableSize) {
} this.availableSize = availableSize;
}
/**
* @return the usedSize /**
*/ * @return the usedSize
public double getUsedSize() { */
return usedSize; public double getUsedSize() {
} return usedSize;
}
/**
* @param usedSize the usedSize to set /**
*/ * @param usedSize the usedSize to set
public void setUsedSize(double usedSize) { */
this.usedSize = usedSize; public void setUsedSize(double usedSize) {
} this.usedSize = usedSize;
}
/**
* @return the ip /**
*/ * @return the ip
public String getIp() { */
return ip; public String getIp() {
} return ip;
}
/**
* @param ip the ip to set /**
*/ * @param ip the ip to set
public void setIp(String ip) { */
this.ip = ip; public void setIp(String ip) {
} this.ip = ip;
}
/**
* @return the path /**
*/ * @return the path
public String getPath() { */
return path; public String getPath() {
} return path;
}
/**
* @param path the path to set /**
*/ * @param path the path to set
public void setPath(String path) { */
this.path = path; public void setPath(String path) {
} this.path = path;
}
}
}

@ -1,110 +1,110 @@
package com.platform.glusterfs; package com.platform.glusterfs;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.PropertyConfigurator;
import com.platform.utils.Constant; import com.platform.utils.Constant;
/** /**
* *
* nullmapipip * nullmapipip
* ipPeerinCluster(Connected) * ipPeerinCluster(Connected)
* ipPeerinCluster(Disconnected) * ipPeerinCluster(Disconnected)
* @author liliy * @author liliy
* @version [2016912] * @version [2016912]
* @see [/] * @see [/]
* @since [/] * @since [/]
*/ */
public class ClusterInfo { public class ClusterInfo {
public static Logger log = Logger.getLogger(ClusterInfo.class); public static Logger log = Logger.getLogger(ClusterInfo.class);
public Map<String, String> showClusterInfo() { public Map<String, String> showClusterInfo() {
log.info("get cluster info"); log.info("get cluster info");
Map<String, String> peerIps = new HashMap<String, String>(); Map<String, String> peerIps = new HashMap<String, String>();
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, Constant.port, Constant.glusterPeerStatus); List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, Constant.port, Constant.glusterPeerStatus);
if (reStrings == null) { if (reStrings == null) {
log.error("1101 command get result is null"); log.error("1101 command get result is null");
return null; return null;
} }
if (reStrings.size() == 0) { if (reStrings.size() == 0) {
log.error("1102 command get result is nothing"); log.error("1102 command get result is nothing");
return null; return null;
} }
if (!(reStrings.get(0).split(":")[0].contains("Number of Peers"))) { if (!(reStrings.get(0).split(":")[0].contains("Number of Peers"))) {
log.error("1103 get result string wrong"); log.error("1103 get result string wrong");
return null; return null;
} }
// System.out.print(reStrings.get(0)); // System.out.print(reStrings.get(0));
int flag = 0; int flag = 0;
String ipString = ""; String ipString = "";
String state = ""; String state = "";
for (Iterator it2 = reStrings.iterator(); it2.hasNext();) { for (Iterator it2 = reStrings.iterator(); it2.hasNext();) {
String line = (String) it2.next(); String line = (String) it2.next();
line=line.replaceAll(" +", " "); line=line.replaceAll(" +", " ");
String keyValue[] = line.split(":"); String keyValue[] = line.split(":");
if (keyValue[0].equals("Hostname")) { if (keyValue[0].equals("Hostname")) {
if (keyValue.length < 2) { if (keyValue.length < 2) {
log.error("1105 command get result is wrong"); log.error("1105 command get result is wrong");
continue; continue;
} }
ipString = keyValue[1].replaceAll(" ", ""); ipString = keyValue[1].replaceAll(" ", "");
flag = 1; flag = 1;
} else if (flag == 1 && keyValue[0].equals("State")) { } else if (flag == 1 && keyValue[0].equals("State")) {
if (keyValue.length < 2) { if (keyValue.length < 2) {
log.error("1106 command get result is wrong"); log.error("1106 command get result is wrong");
continue; continue;
} }
state = keyValue[1].replaceAll(" ", ""); state = keyValue[1].replaceAll(" ", "");
flag = 0; flag = 0;
peerIps.put(ipString, state); peerIps.put(ipString, state);
} }
} }
return peerIps; return peerIps;
} }
/** /**
* ipip * ipip
* ipnull * ipnull
* ipPeerinCluster(Connected) * ipPeerinCluster(Connected)
* ipPeerinCluster(Disconnected) * ipPeerinCluster(Disconnected)
* @param peerip * @param peerip
* @return * @return
* @see [##] * @see [##]
*/ */
public String getPeerStatus(String peerip){ public String getPeerStatus(String peerip){
Map<String, String> peerIps=showClusterInfo(); Map<String, String> peerIps=showClusterInfo();
if(peerIps==null || peerIps.size()==0){ if(peerIps==null || peerIps.size()==0){
return null; return null;
} }
if(!peerIps.containsKey(peerip)){ if(!peerIps.containsKey(peerip)){
return Constant.peerincluster_disconnected; return Constant.peerincluster_disconnected;
} }
return peerIps.get(peerip); return peerIps.get(peerip);
} }
public static void main(String[] args) { public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties"); PropertyConfigurator.configure("log4j.properties");
System.out.println(new ClusterInfo().showClusterInfo()); System.out.println(new ClusterInfo().showClusterInfo());
} }
} }

@ -1,122 +1,120 @@
package com.platform.glusterfs;
package com.platform.glusterfs;
import java.util.ArrayList;
import java.util.ArrayList; import java.util.List;
import java.util.List; import java.util.Map;
import java.util.Map;
import org.junit.Test;
import org.junit.Test;
import com.platform.entities.FolderNode; import com.platform.entities.FolderNode;
import com.platform.utils.Constant; import com.platform.utils.Constant;
import com.platform.utils.FileOperateHelper; import com.platform.utils.FileOperateHelper;
import com.platform.utils.GanymedSSH;
/**
/** * <> GFS
* <> GFS * <>
* <> * @author chen
* @author chen * @version [201698]
* @version [201698] * @see [/]
* @see [/] * @since [/]
* @since [/] */
*/ public class GetTreeData {
public class GetTreeData { ShowData showData = new ShowData();
ShowData showData = new ShowData();
/**
/** * <>
* <> * <>
* <> * @param name
* @param name * @return
* @return * @see [##]
* @see [##] */
*/ public FolderNode getDatas(String name) {
public FolderNode getDatas(String name) { String names[]=name.split("/");
String names[]=name.split("/"); String only_name=names[names.length-1];
String only_name=names[names.length-1]; FolderNode fileNode = new FolderNode(only_name);
FolderNode fileNode = new FolderNode(only_name); fileNode.setPath(name);
fileNode.setPath(name); Map<String, String> files = showData.showFolderData(name);
Map<String, String> files = showData.showFolderData(name); if(files==null || files.size()==0){
if(files==null || files.size()==0){ return fileNode;
return fileNode; }
} fileNode.setIsFolder(files.size());
fileNode.setIsFolder(files.size()); List<FolderNode> list = new ArrayList<FolderNode>();
List<FolderNode> list = new ArrayList<FolderNode>(); fileNode.setChildNodes(list);
fileNode.setChildNodes(list); for (Map.Entry<String, String> entry : files.entrySet()) {
for (Map.Entry<String, String> entry : files.entrySet()) { if(entry.getKey().equals("app")){
if(entry.getKey().equals("app")){ continue;
continue; }
} int number = Integer.parseInt(entry.getValue());
int number = Integer.parseInt(entry.getValue()); if (number == 1) {
if (number == 1) { fileNode.getChildNodes().add(new FolderNode(entry.getKey(), number));
fileNode.getChildNodes().add(new FolderNode(entry.getKey(), number)); }
} if (number > 1) {
if (number > 1) { FolderNode temp=getDatas(name+"/"+entry.getKey());
FolderNode temp=getDatas(name+"/"+entry.getKey()); fileNode.getChildNodes().add(temp);
fileNode.getChildNodes().add(temp); }
} }
}
return fileNode;
return fileNode; }
}
/**
* <>
/** * <>
* <> * @param name
* <> * @return
* @param name * @see [##]
* @return */
* @see [##] public FolderNode getDatasWithShell(String name) {
*/ if(name.endsWith("/")){
public FolderNode getDatasWithShell(String name) { name=name.substring(0, name.length());
if(name.endsWith("/")){ }
name=name.substring(0, name.length()); String names[]=name.split("/");
} String only_name=names[names.length-1];
String names[]=name.split("/"); FolderNode fileNode = new FolderNode(name);
String only_name=names[names.length-1]; fileNode.setPath(name);
FolderNode fileNode = new FolderNode(name);
fileNode.setPath(name); String shellComment=new FileOperateHelper().fileReaderAndendline(Constant.fileGetTreeData);
String sh_path="/getTreedata.sh";
String shellComment=new FileOperateHelper().fileReaderAndendline(Constant.fileGetTreeData); String cmd="echo -e "+shellComment+" > "+sh_path+" & chmod +x "+sh_path;
String sh_path="/getTreedata.sh"; Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
String cmd="echo -e "+shellComment+" > "+sh_path+" & chmod +x "+sh_path; // Map<String, String> files = showData.showFolderData(name);
Constant.ganymedSSH.execCmdWaitAcquiescent(cmd); List<String> files=Constant.ganymedSSH.execCmdWaitAcquiescent(sh_path+" "+name);
// Map<String, String> files = showData.showFolderData(name); if(files==null){
List<String> files=Constant.ganymedSSH.execCmdWaitAcquiescent(sh_path+" "+name); return null;
if(files==null){ }
return null; if(files.size()==0){
} return fileNode;
if(files.size()==0){ }
return fileNode; for(String file:files){
}
for(String file:files){ }
} return fileNode;
}
return fileNode; @Test
} public void test_getTreeData() {
@Test
public void test_getTreeData() { GetTreeData getTreeData=new GetTreeData();
FolderNode fileOrFolder=getTreeData.getDatas("/home");
GetTreeData getTreeData=new GetTreeData(); System.out.println(fileOrFolder);
FolderNode fileOrFolder=getTreeData.getDatas("/home"); }
System.out.println(fileOrFolder); }
} /*
} class FileOrFolder {
/* String name;
class FileOrFolder { int isFolder; // 1 is file and other integer is folder show children number
String name; List<FileOrFolder> children;
int isFolder; // 1 is file and other integer is folder show children number
List<FileOrFolder> children; public FileOrFolder(String name) {
// TODO Auto-generated constructor stub
public FileOrFolder(String name) { this.name = name;
// TODO Auto-generated constructor stub }
this.name = name;
} public FileOrFolder(String name, int isFolder) {
// TODO Auto-generated constructor stub
public FileOrFolder(String name, int isFolder) { this.name = name;
// TODO Auto-generated constructor stub this.isFolder = isFolder;
this.name = name; }
this.isFolder = isFolder; }
}
} */
*/

@ -1,11 +1,11 @@
package com.platform.glusterfs; package com.platform.glusterfs;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
public class SetCluster { public class SetCluster {
public static Logger log = Logger.getLogger ( SetCluster.class); public static Logger log = Logger.getLogger ( SetCluster.class);
public int addPeer(String peerip){ public int addPeer(String peerip){
return 0; return 0;
} }
} }

@ -1,495 +1,498 @@
/** /**
* @author * @author
* volumevolumevolumebrick * volumevolumevolumebrick
*/ */
package com.platform.glusterfs; package com.platform.glusterfs;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.PropertyConfigurator;
import com.platform.utils.Constant; import com.platform.utils.Constant;
public class SetVolume { public class SetVolume {
public static Logger log = Logger.getLogger(SetVolume.class); public static Logger log = Logger.getLogger(SetVolume.class);
/* /*
* volume 1 * volume 1
* *
*/ */
public int createVolume(String volumeName, int count, String type, List bricks, String mountPoint) { public int createVolume(String volumeName, int count, String type, List bricks, String mountPoint) {
log.info("Creat new volume"); log.info("Creat new volume");
// 判断创建volume的条件是否满足 // 判断创建volume的条件是否满足
int able = isAbleCreateVolume(volumeName, count, type, bricks, mountPoint); int able = isAbleCreateVolume(volumeName, count, type, bricks, mountPoint);
if (able == 1) { if (able == 1) {
String command = null; String command = null;
// 将brics从List变量中提取出来并连接成可以在命令行中使用的格式 // 将brics从List变量中提取出来并连接成可以在命令行中使用的格式
String commandarg = concat(bricks); String commandarg = concat(bricks);
/* /*
* verify the type * verify the type
*/ */
if (type.equals(Constant.distributed)) { if (type.equals(Constant.distributed)) {
command = "gluster volume create " + volumeName + " " + commandarg + "force"; command = "gluster volume create " + volumeName + " " + commandarg + "force";
} else if (type.equals(Constant.replica) || type.equals(Constant.stripe)) { } else if (type.equals(Constant.replica) || type.equals(Constant.stripe)) {
command = "gluster volume create " + volumeName + " " + type + " " + count + " " + commandarg + "force"; command = "gluster volume create " + volumeName + " " + type + " " + count + " " + commandarg + "force";
} }
// 执行命令 // 执行命令
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
Constant.port, command); Constant.port, command);
// 创建成功时返回信息格式volume create: volumename success: // 创建成功时返回信息格式volume create: volumename success:
if (reStrings == null || reStrings.size() == 0) { if (reStrings == null || reStrings.size() == 0) {
log.error("3106 " + command + " run return error"); log.error("3106 " + command + " run return error");
return -7; return -7;
} }
if (reStrings.get(0).contains("volume create: " + volumeName + ": " + "success:")) { if (reStrings.get(0).contains("volume create: " + volumeName + ": " + "success:")) {
log.info("create volume "+volumeName+" successed!"); log.info("create volume "+volumeName+" successed!");
// 创建成功则启动并进行挂载 // 创建成功则启动并进行挂载
if (startVolume(volumeName) == 0) { if (startVolume(volumeName) == 0) {
log.info("start volume "+volumeName+" successed!"); log.info("start volume "+volumeName+" successed!");
if ((new ShowData().showFolderData(mountPoint)) == null) { if ((new ShowData().showFolderData(mountPoint)) == null) {
Constant.ganymedSSH.execCmdWaitAcquiescent("mkdir " + mountPoint); Constant.ganymedSSH.execCmdWaitAcquiescent("mkdir " + mountPoint);
} }
// 进行挂载 // 进行挂载
String command3 = "mount -t glusterfs " + Constant.hostIp + ":/" + volumeName + " " + mountPoint; String command3 = "mount -t glusterfs " + Constant.hostIp + ":/" + volumeName + " " + mountPoint;
List<String> reStrings3 = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, List<String> reStrings3 = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser,
Constant.rootPasswd, Constant.port, command3); Constant.rootPasswd, Constant.port, command3);
// 这里需要添加解析挂载命令返回字符串的语句由于我的系统有问题导致挂载成功后返回WARNING: getfattr // 这里需要添加解析挂载命令返回字符串的语句由于我的系统有问题导致挂载成功后返回WARNING: getfattr
// not found, certain checks will be skipped.. // not found, certain checks will be skipped..
// 所以这句代码未经测试 // 所以这句代码未经测试
// 成功挂载时没有任何返回信息 // 成功挂载时没有任何返回信息
if (reStrings3.size() == 0 || reStrings.get(0).contains("GlusterFS is already mounted")) if (reStrings3.size() == 0 || reStrings.get(0).contains("GlusterFS is already mounted"))
{ {
log.info("mount point successed!"); log.info("mount point successed!");
return 1; return 1;
} }
} }
} else { } else {
log.error("3104 volume create failed with error" + reStrings.get(0)); log.error("3104 volume create failed with error" + reStrings.get(0));
// System.out.println(reStrings.get(0)); // System.out.println(reStrings.get(0));
return -7; return -7;
} }
return 1; return 1;
} else { } else {
log.error("给出的参数不满足创建条件"); log.error("给出的参数不满足创建条件");
// System.out.println("给出的参数不满足创建条件"); // System.out.println("给出的参数不满足创建条件");
return able; return able;
} }
} }
/** /**
* volume * volume
* *
* @param volumeName * @param volumeName
* @return 1 -1volume name-2volume * @return 1 -1volume name-2volume
*/ */
public int deleteVolume(String volumeName) { public int deleteVolume(String volumeName) {
int status = 0; int status = 0;
List<String> volumeNames = new VolumeInfo().showAllVolumeName(); List<String> volumeNames = new VolumeInfo().showAllVolumeName();
if (!volumeNames.contains(volumeName)) { if (!volumeNames.contains(volumeName)) {
log.error("3801 " + volumeName + " is not exists !"); log.error("3801 " + volumeName + " is not exists !");
return -1; return -1;
} }
List<String> mountPoints = new VolumeInfo().getVolumeMountPoint(volumeName); List<String> mountPoints = new VolumeInfo().getVolumeMountPoint(volumeName);
if (stopVolume(volumeName) != 0) { if (stopVolume(volumeName) != 0) {
log.error("3802 " + volumeName + " stop failed !"); log.error("3802 " + volumeName + " stop failed !");
return -2; return -2;
} }
log.info("stop "+volumeName+" successed!"); log.info("stop "+volumeName+" successed!");
for(String mountPoint:mountPoints){ if (null == mountPoints) {
if (mountPoint != null) { return -2;
String command = "umount -l " + mountPoint; }
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command); for(String mountPoint:mountPoints){
log.info("umount "+mountPoint+" successed!"); if (mountPoint != null) {
} String command = "umount -l " + mountPoint;
} Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
String command="echo -e \"y\"| gluster volume delete "+volumeName; log.info("umount "+mountPoint+" successed!");
List<String> reStrings=Constant.ganymedSSH.execCmdWaitAcquiescent(command); }
if(reStrings==null || reStrings.size()>0 || !(reStrings.get(0).contains("volume delete: "+volumeName+": success"))){ }
log.error("3803 : delete volume "+volumeName+" failed !"); String command="echo -e \"y\"| gluster volume delete "+volumeName;
return -3; List<String> reStrings=Constant.ganymedSSH.execCmdWaitAcquiescent(command);
} if(reStrings==null || reStrings.size()>0 || !(reStrings.get(0).contains("volume delete: "+volumeName+": success"))){
log.info("delete "+volumeName+" successed!"); log.error("3803 : delete volume "+volumeName+" failed !");
return 1; return -3;
} }
log.info("delete "+volumeName+" successed!");
/* return 1;
* volumebrick, 1 ; }
* volumebrickcount
*/ /*
public int addBrickVolume(String volumeName, List<String> brickName, int count, String type) { * volumebrick, 1 ;
// 检查是否满足添加bricks的条件 * volumebrickcount
int able = isAble(volumeName, count, type, brickName); */
if (able != 1) { public int addBrickVolume(String volumeName, List<String> brickName, int count, String type) {
return able; // 检查是否满足添加bricks的条件
} int able = isAble(volumeName, count, type, brickName);
if (able != 1) {
String command = ""; return able;
log.info("add brick to the specified volume"); }
String brick = concat(brickName); String command = "";
log.info("add brick to the specified volume");
if (type.equals(Constant.distributed))
command = "gluster volume add-brick " + volumeName + " " + brick + "force"; String brick = concat(brickName);
else if (type.equals(Constant.replica))
command = "gluster volume add-brick " + volumeName + " " + "replica " + count + " " + brick + "force"; if (type.equals(Constant.distributed))
else if (type.equals(Constant.stripe)) command = "gluster volume add-brick " + volumeName + " " + brick + "force";
command = "gluster volume add-brick " + volumeName + " " + "stripe " + count + " " + brick + "force"; else if (type.equals(Constant.replica))
command = "gluster volume add-brick " + volumeName + " " + "replica " + count + " " + brick + "force";
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, else if (type.equals(Constant.stripe))
Constant.port, command); command = "gluster volume add-brick " + volumeName + " " + "stripe " + count + " " + brick + "force";
// 添加成功的返回信息是volume add-brick: success List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
if (reStrings != null && reStrings.size() > 0 && reStrings.get(0).contains("volume add-brick: success")) { Constant.port, command);
log.info("添加brick成功");
return 1; // 添加成功的返回信息是volume add-brick: success
} else { if (reStrings != null && reStrings.size() > 0 && reStrings.get(0).contains("volume add-brick: success")) {
log.error("3205 add brick failed,please check the system"); log.info("添加brick成功");
// System.out.println("3202 add brick failed,please check the system"); return 1;
return -5; } else {
} log.error("3205 add brick failed,please check the system");
} // System.out.println("3202 add brick failed,please check the system");
return -5;
/* }
* volumebrick, 1 ; }
* volumebrickcount
*/ /*
public int deleteBrickVolume(String volumeName, List<String> brickName, int count, String type) { * volumebrick, 1 ;
int able = isAble(volumeName, count, type, brickName); * volumebrickcount
*/
if (able != 1) { public int deleteBrickVolume(String volumeName, List<String> brickName, int count, String type) {
return able; int able = isAble(volumeName, count, type, brickName);
}
String command = null; if (able != 1) {
return able;
log.info("delete brick of the specified volume"); }
String command = null;
String brick = concat(brickName);
log.info("delete brick of the specified volume");
if (type.equals(Constant.distributed)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " " + brick + " force"; String brick = concat(brickName);
} else if (type.equals(Constant.replica)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " repli " + count + " " + brick if (type.equals(Constant.distributed)) {
+ " force"; command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " " + brick + " force";
} else if (type.equals(Constant.stripe)) { } else if (type.equals(Constant.replica)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " stripe " + count + " " + brick command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " repli " + count + " " + brick
+ " force"; + " force";
} } else if (type.equals(Constant.stripe)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " stripe " + count + " " + brick
if (command == null) { + " force";
log.error("3305 remove brick failed,please check the system"); }
return -5;
} if (command == null) {
log.info("即将执行删除命令"); log.error("3305 remove brick failed,please check the system");
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, return -5;
Constant.port, command); }
// System.out.println(reStrings); log.info("即将执行删除命令");
log.info("删除命令执行完毕"); List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
Constant.port, command);
// 删除成功的返回信息是“volume remove-brick: success” // System.out.println(reStrings);
if (reStrings.get(0).contains("volume remove-brick: success")) { log.info("删除命令执行完毕");
{
log.info("删除brick成功"); // 删除成功的返回信息是“volume remove-brick: success”
return 1; if (reStrings.get(0).contains("volume remove-brick: success")) {
} {
} else { log.info("删除brick成功");
log.error("3305 remove brick failed,please check the system"); return 1;
}
return -5; } else {
} log.error("3305 remove brick failed,please check the system");
} return -5;
}
/*
* volume volume 0 -1 }
* volumevolume
*/ /*
public int stopVolume(String volumeName) { * volume volume 0 -1
log.info("stop volume"); * volumevolume
*/
// 首先需要判断volume是否存在调用其他函数返回所有volume的名字 public int stopVolume(String volumeName) {
boolean volumeExist = false; log.info("stop volume");
List<String> volume = new VolumeInfo().showAllVolumeName(); // 首先需要判断volume是否存在调用其他函数返回所有volume的名字
for (String temp : volume) { boolean volumeExist = false;
if (temp.equals(volumeName)) {
volumeExist = true; List<String> volume = new VolumeInfo().showAllVolumeName();
break; for (String temp : volume) {
} if (temp.equals(volumeName)) {
} volumeExist = true;
break;
if (!volumeExist) { }
// volume不存在 }
log.error("3501 the volume doesnot exist");
System.out.println("3501 the volume doesnot exist"); if (!volumeExist) {
return -1; // volume不存在
} else { log.error("3501 the volume doesnot exist");
// volume存在则需判断volume的状态是否已经为“stop” System.out.println("3501 the volume doesnot exist");
if (new VolumeInfo().getVolumeStatus(volumeName).equals("Stopped")) { return -1;
log.error("3502 the volume is already stoped"); } else {
System.out.println("3502 the volume is already stoped"); // volume存在则需判断volume的状态是否已经为“stop”
return -1; if (new VolumeInfo().getVolumeStatus(volumeName).equals("Stopped")) {
} else { log.error("3502 the volume is already stoped");
String command = "echo -e \"y\"| gluster volume stop " + volumeName; System.out.println("3502 the volume is already stoped");
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, return -1;
Constant.port, command); } else {
String command = "echo -e \"y\"| gluster volume stop " + volumeName;
// 标记操作结果operation = 1 操作成功 List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
// operation = 0 操作失败 Constant.port, command);
int operation = 0;
for (String temp2 : reStrings) { // 标记操作结果operation = 1 操作成功
if (temp2.contains("volume stop: " + volumeName + ": " + "success")) { // operation = 0 操作失败
operation = 1; int operation = 0;
break; for (String temp2 : reStrings) {
} if (temp2.contains("volume stop: " + volumeName + ": " + "success")) {
System.out.println("operation: " + operation); operation = 1;
} break;
}
if (operation == 1) { System.out.println("operation: " + operation);
return 0; }
} else {
log.error("3503 stop " + volumeName + " failed"); if (operation == 1) {
System.out.println("3503 stop " + volumeName + " failed"); return 0;
return -1; } else {
} log.error("3503 stop " + volumeName + " failed");
System.out.println("3503 stop " + volumeName + " failed");
} return -1;
} }
}
}
/* }
* volume volume 0 -1 }
* volumevolume
*/ /*
public int startVolume(String volumeName) { * volume volume 0 -1
log.info("start volume"); * volumevolume
boolean volumeExist = false; */
List<String> volume = new VolumeInfo().showAllVolumeName(); public int startVolume(String volumeName) {
log.info("start volume");
for (String temp : volume) { boolean volumeExist = false;
if (temp.equals(volumeName)) { List<String> volume = new VolumeInfo().showAllVolumeName();
volumeExist = true;
break; for (String temp : volume) {
} if (temp.equals(volumeName)) {
} volumeExist = true;
break;
if (volumeExist) { }
if (!(new VolumeInfo().getVolumeStatus(volumeName).equals("Started"))) { }
String command = "gluster volume start " + volumeName;
if (volumeExist) {
int operation = 0; if (!(new VolumeInfo().getVolumeStatus(volumeName).equals("Started"))) {
String command = "gluster volume start " + volumeName;
// 执行命令
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, int operation = 0;
Constant.port, command);
for (String temp2 : reStrings) { // 执行命令
if (temp2.equals("volume start: " + volumeName + ": " + "success")) { List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
operation = 1; Constant.port, command);
} for (String temp2 : reStrings) {
} if (temp2.equals("volume start: " + volumeName + ": " + "success")) {
operation = 1;
if (operation == 1) { }
return 0; }
} else {
log.error("3602 start volume failed"); if (operation == 1) {
System.out.println("3602 start volume failed"); return 0;
return -1; } else {
} log.error("3602 start volume failed");
} else { System.out.println("3602 start volume failed");
log.error("volume已经开启"); return -1;
System.out.println("volume已经开启"); }
return -1; } else {
} log.error("volume已经开启");
} else { System.out.println("volume已经开启");
log.error("3601 the volume does not exist"); return -1;
// System.out.println("3601 the volume does not exist"); }
return -1; } else {
} log.error("3601 the volume does not exist");
} // System.out.println("3601 the volume does not exist");
return -1;
// 需要将存于List变量中的brick的位置组装成可以在glusterfs命令行中直接使用的格式 }
public String concat(List<String> brickName) { }
StringBuffer result = new StringBuffer();
int len = brickName.size(); // 需要将存于List变量中的brick的位置组装成可以在glusterfs命令行中直接使用的格式
for (int i = 0; i < len; i++) { public String concat(List<String> brickName) {
result.append(brickName.get(i)); StringBuffer result = new StringBuffer();
result.append(" "); int len = brickName.size();
} for (int i = 0; i < len; i++) {
return result.toString(); result.append(brickName.get(i));
} result.append(" ");
}
/* return result.toString();
* volume使 volumebrickcount }
* 1: ;-1brickip; -2 -3
* -4 :brick ; -5 :volumeName -6 -7 /*
*/ * volume使 volumebrickcount
public int isAbleCreateVolume(String volumeName, int count, String type, List<String> bricks, String mountPoint) { * 1: ;-1brickip; -2 -3
int status = 0; * -4 :brick ; -5 :volumeName -6 -7
*/
int length = bricks.size(); public int isAbleCreateVolume(String volumeName, int count, String type, List<String> bricks, String mountPoint) {
int status = 0;
if (type.equals(Constant.distributed)) {
if (count != 0) { int length = bricks.size();
log.error("3101 the kind of distributed requires the arg of count to be 0");
return -2; if (type.equals(Constant.distributed)) {
} if (count != 0) {
} log.error("3101 the kind of distributed requires the arg of count to be 0");
if (type.equals(Constant.stripe)) { return -2;
if (length % count != 0) { }
log.error("3102 the number of bricks should be the same as or the times of the stripe count"); }
return -3; if (type.equals(Constant.stripe)) {
} if (length % count != 0) {
} log.error("3102 the number of bricks should be the same as or the times of the stripe count");
if (type.equals(Constant.replica)) { return -3;
if ((length % count) != 0) { }
log.error( }
"3103 the number of bricks should be the same as the replicate count or the times of replicate count"); if (type.equals(Constant.replica)) {
return -4; if ((length % count) != 0) {
} log.error(
} "3103 the number of bricks should be the same as the replicate count or the times of replicate count");
return -4;
Map peer_status = new ClusterInfo().showClusterInfo(); }
peer_status.put(Constant.hostIp, Constant.peerincluster_connected); }
for (String brick : bricks) {
brick = brick.split(":")[0]; Map peer_status = new ClusterInfo().showClusterInfo();
if (!(peer_status.containsKey(brick) && peer_status.get(brick).equals(Constant.peerincluster_connected))) { peer_status.put(Constant.hostIp, Constant.peerincluster_connected);
log.error("3105 birck " + brick + " ip is not in cluster"); for (String brick : bricks) {
return -1; brick = brick.split(":")[0];
} if (!(peer_status.containsKey(brick) && peer_status.get(brick).equals(Constant.peerincluster_connected))) {
log.error("3105 birck " + brick + " ip is not in cluster");
} return -1;
}
List<String> volumeNames = new VolumeInfo().showAllVolumeName();
if(volumeNames==null){ }
log.error("3108 showAllVolumeName return error");
return -7; List<String> volumeNames = new VolumeInfo().showAllVolumeName();
} if(volumeNames==null){
if (volumeNames.contains(volumeName)) { log.error("3108 showAllVolumeName return error");
log.error("3106 " + volumeName + " is already exists! "); return -7;
return -5; }
} if (volumeNames.contains(volumeName)) {
log.error("3106 " + volumeName + " is already exists! ");
Map datas = new ShowData().showFolderData(mountPoint); return -5;
if (datas != null && datas.size() > 0) { }
log.error("3107 " + mountPoint + " is not exists or not empty ! ");
return -6; Map datas = new ShowData().showFolderData(mountPoint);
} if (datas != null && datas.size() > 0) {
return 1; log.error("3107 " + mountPoint + " is not exists or not empty ! ");
} return -6;
}
/** return 1;
* volumebrickvolumevolumecountbrick }
*
* @param volumeName /**
* @param count * volumebrickvolumevolumecountbrick
* @param type *
* @param bricks * @param volumeName
* @return 1 ;-1 :volume name is not exists;-2,-3,-4 brick * @param count
*/ * @param type
public int isAble(String volumeName, int count, String type, List bricks) { * @param bricks
List<String> volumeNames = new VolumeInfo().showAllVolumeName(); * @return 1 ;-1 :volume name is not exists;-2,-3,-4 brick
*/
if (!volumeNames.contains(volumeName)) { public int isAble(String volumeName, int count, String type, List bricks) {
log.error("3201" + volumeName + " is not exists! "); List<String> volumeNames = new VolumeInfo().showAllVolumeName();
return -1;
} if (!volumeNames.contains(volumeName)) {
log.error("3201" + volumeName + " is not exists! ");
int length = bricks.size(); return -1;
if (type.equals("distribute")) { }
if (count == 0)
return 1; int length = bricks.size();
else { if (type.equals("distribute")) {
log.error("3202 the kind of distributed requires the arg of count to be 0"); if (count == 0)
// System.out.println(" the kind of distributed requires the return 1;
// arg of count to be 0"); else {
return -2; log.error("3202 the kind of distributed requires the arg of count to be 0");
} // System.out.println(" the kind of distributed requires the
} // arg of count to be 0");
return -2;
if (type.equals("stripe")) { }
if (length % count == 0) }
return 1;
else { if (type.equals("stripe")) {
log.error("3203 the number of bricks should be the same as or the times of the stripe count"); if (length % count == 0)
// System.out.println(" the number of bricks should be the return 1;
// same as or the times of the stripe count"); else {
return -3; log.error("3203 the number of bricks should be the same as or the times of the stripe count");
// System.out.println(" the number of bricks should be the
} // same as or the times of the stripe count");
} return -3;
if (type.equals("replicate")) {
if ((length % count) == 0) }
return 1; }
else { if (type.equals("replicate")) {
log.error( if ((length % count) == 0)
"3204 the number of bricks should be the same as the replicate count or the times of replicate count"); return 1;
else {
return -4; log.error(
} "3204 the number of bricks should be the same as the replicate count or the times of replicate count");
}
return -4;
return 1; }
} }
public static void main(String[] args) { return 1;
SetVolume setVolume = new SetVolume(); }
int operation = 0;
PropertyConfigurator.configure("log4j.properties"); public static void main(String[] args) {
// TODO Auto-generated method stub SetVolume setVolume = new SetVolume();
// 测试创建volume的代码 int operation = 0;
PropertyConfigurator.configure("log4j.properties");
List<String> bricksToCreate = new ArrayList<String>(); // TODO Auto-generated method stub
bricksToCreate.add("192.168.0.110:/v1"); // 测试创建volume的代码
bricksToCreate.add("192.168.0.116:/v1");
operation = setVolume.createVolume("v1", 0, "distributed", bricksToCreate, "/home/v1_point"); List<String> bricksToCreate = new ArrayList<String>();
// operation = setVolume.deleteVolume("v3"); bricksToCreate.add("192.168.0.110:/v1");
// bricksToCreate.add("192.168.0.116:/v1");
// // 以下是测试添加brick的代码 operation = setVolume.createVolume("v1", 0, "distributed", bricksToCreate, "/home/v1_point");
// // operation = setVolume.deleteVolume("v3");
// List<String> bricksToAdd = new ArrayList<String>(); //
// bricksToAdd.add("192.168.191.23:/v3"); // // 以下是测试添加brick的代码
// operation = setVolume.addBrickVolume("v3", bricksToAdd, 0, //
// "distribute"); // List<String> bricksToAdd = new ArrayList<String>();
// System.out.println(operation); // bricksToAdd.add("192.168.191.23:/v3");
// operation = setVolume.addBrickVolume("v3", bricksToAdd, 0,
// 以下代码是测试删除brick的代码 // "distribute");
// List<String> bricksToAdd= new ArrayList<String>(); // System.out.println(operation);
// bricksToAdd.add("192.168.191.23:/v3");
// operation = // 以下代码是测试删除brick的代码
// setVolume.deleteBrickVolume("v3",bricksToAdd,0,"distribute"); // List<String> bricksToAdd= new ArrayList<String>();
// System.out.println(operation); // bricksToAdd.add("192.168.191.23:/v3");
// 以下是测试start volume的代码 // operation =
// String volumeToStart = "testcreate" ; // setVolume.deleteBrickVolume("v3",bricksToAdd,0,"distribute");
// int startOperation = startVolume(volumeToStart); // System.out.println(operation);
// System.out.println(startOperation); // 以下是测试start volume的代码
// 以下是测试stop volume // String volumeToStart = "testcreate" ;
String volumeToStop = "v3"; // int startOperation = startVolume(volumeToStart);
// int startOperation = setVolume.stopVolume(volumeToStop); // System.out.println(startOperation);
// 以下是测试创建volume并完成挂载的代码 // 以下是测试stop volume
// List<String> bricksToCreate= new ArrayList<String>(); String volumeToStop = "v3";
// bricksToCreate.add("192.168.214.135:/home/create"); // int startOperation = setVolume.stopVolume(volumeToStop);
// bricksToCreate.add("192.168.214.138:/home/create"); // 以下是测试创建volume并完成挂载的代码
// // List<String> bricksToCreate= new ArrayList<String>();
// int operation = // bricksToCreate.add("192.168.214.135:/home/create");
// createVolume("createAndmount",0,"distribute",bricksToCreate,"/mnt/create"); // bricksToCreate.add("192.168.214.138:/home/create");
// System.out.println(operation); //
} // int operation =
} // createVolume("createAndmount",0,"distribute",bricksToCreate,"/mnt/create");
// System.out.println(operation);
}
}

@ -1,105 +1,105 @@
package com.platform.glusterfs; package com.platform.glusterfs;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.PropertyConfigurator;
import org.junit.Test; import org.junit.Test;
import com.platform.utils.Constant; import com.platform.utils.Constant;
public class ShowData { public class ShowData {
public static Logger log = Logger.getLogger ( ShowData.class); public static Logger log = Logger.getLogger ( ShowData.class);
/** /**
* get the data of volumeName Map<string s1,string s2> s1 is data name and s2 is type file or folder * get the data of volumeName Map<string s1,string s2> s1 is data name and s2 is type file or folder
* <> * <>
* @param volumeName * @param volumeName
* @return * @return
* @see [##] * @see [##]
*/ */
public Map<String,String> showVolumeFiles(String volumeName){ public Map<String,String> showVolumeFiles(String volumeName){
log.info("start show the data"); log.info("start show the data");
Map<String,String> data_type=new HashMap<String, String>(); Map<String,String> data_type=new HashMap<String, String>();
/** /**
* get mount point of volumeName * get mount point of volumeName
*/ */
String folderName=volumeName; String folderName=volumeName;
data_type=showFolderData(volumeName); data_type=showFolderData(volumeName);
return data_type; return data_type;
} }
/** /**
* get the data of folder name * get the data of folder name
* Map<String,String> is folder name and type 1 is file and others is folder * Map<String,String> is folder name and type 1 is file and others is folder
* @param FolderName * @param FolderName
* @return * @return
*/ */
public Map<String,String> showFolderData(String folderName){ public Map<String,String> showFolderData(String folderName){
log.info(" start get "+folderName+" data"); log.info(" start get "+folderName+" data");
Map<String,String> data_type=new HashMap<String, String>(); Map<String,String> data_type=new HashMap<String, String>();
String command="ls -l "+folderName; String command="ls -l "+folderName;
/* /*
RunCommand runCommand=new RunCommand(); RunCommand runCommand=new RunCommand();
List<String> reStrings=runCommand.runCommandWait(command); List<String> reStrings=runCommand.runCommandWait(command);
*/ */
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, Constant.port, command); List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, Constant.port, command);
if(reStrings==null){ if(reStrings==null){
log.error("2101 command get result is null"); log.error("2101 command get result is null");
return null; return null;
} }
if(reStrings.size()==0){ if(reStrings.size()==0){
log.info("2102 the folder is empty"); log.info("2102 the folder is empty");
return data_type; return data_type;
} }
if(reStrings.get(0).contains("No such file or directory")){ if(reStrings.get(0).contains("No such file or directory")){
log.info("2103 the "+folderName+" is not exists"); log.info("2103 the "+folderName+" is not exists");
return null; return null;
} }
/** /**
* remove first line total number * remove first line total number
*/ */
reStrings.remove(0); reStrings.remove(0);
for(Iterator it2 = reStrings.iterator();it2.hasNext();){ for(Iterator it2 = reStrings.iterator();it2.hasNext();){
String line=(String)it2.next(); String line=(String)it2.next();
line=line.replaceAll(" +", " "); line=line.replaceAll(" +", " ");
String keyValue[]=line.split(" "); String keyValue[]=line.split(" ");
if(keyValue.length<9){ if(keyValue.length<9){
log.error("2104 "+line+" length is short"); log.error("2104 "+line+" length is short");
continue; continue;
} }
data_type.put(keyValue[8], keyValue[1]); data_type.put(keyValue[8], keyValue[1]);
} }
log.info(" get "+folderName+" data successed"); log.info(" get "+folderName+" data successed");
return data_type; return data_type;
} }
/** /**
* *
* <> * <>
* <> * <>
* @see [##] * @see [##]
*/ */
@Test @Test
public void testShowData(){ public void testShowData(){
System.out.println(showFolderData("/home")); System.out.println(showFolderData("/home"));
} }
} }

@ -1,325 +1,334 @@
package com.platform.glusterfs; package com.platform.glusterfs;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.PropertyConfigurator;
import org.junit.Test; import org.junit.Test;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper; import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import com.platform.utils.Constant; import com.platform.utils.Constant;
import com.platform.utils.GanymedSSH; import com.platform.utils.GanymedSSH;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class VolumeInfo { public class VolumeInfo {
public static Logger log = Logger.getLogger(VolumeInfo.class); public static Logger log = Logger.getLogger(VolumeInfo.class);
/** /**
* volume * volume
* <> * <>
* @return * @return
* @see [##] * @see [##]
*/ */
public List<String> showAllVolumeName() { public List<String> showAllVolumeName() {
log.info("get volume name"); log.info("get volume name");
List<String> volNames = new ArrayList<String>(); List<String> volNames = new ArrayList<String>();
/* /*
* String command = "echo \"" + Constant.rootPasswd + * String command = "echo \"" + Constant.rootPasswd +
* "\" |sudo -S gluster volume info|grep ^Volume.Name"; RunCommand * "\" |sudo -S gluster volume info|grep ^Volume.Name"; RunCommand
* runCommand = new RunCommand(); List<String> reStrings = * runCommand = new RunCommand(); List<String> reStrings =
* runCommand.runCommandWait(command); * runCommand.runCommandWait(command);
*/ */
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser,
Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + "|grep ^Volume.Name"); Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + "|grep ^Volume.Name");
// System.out.println(reStrings); // System.out.println(reStrings);
if (reStrings == null) { if (reStrings == null) {
log.error("1401 get result is null"); log.error("1401 get result is null");
return null; return null;
} }
if (reStrings.size() == 0) { if (reStrings.size() == 0) {
log.error("1402 get result is nothing"); log.error("1402 get result is nothing");
return null; return null;
} }
if (reStrings.get(0).contains(Constant.noVolume)) { if (reStrings.get(0).contains(Constant.noVolume)) {
reStrings.clear(); reStrings.clear();
return reStrings; return reStrings;
} }
if (!(reStrings.get(0).split(":")[0].contains("Volume Name"))) { if (!(reStrings.get(0).split(":")[0].contains("Volume Name"))) {
log.error("1403 get result string wrong"); log.error("1403 get result string wrong");
return null; return null;
} }
String nameInfo = ""; String nameInfo = "";
for (Iterator it = reStrings.iterator(); it.hasNext();) { for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next(); String line = (String) it.next();
String str[] = line.split(":"); String str[] = line.split(":");
volNames.add(str[1].replaceAll(" ", "")); volNames.add(str[1].replaceAll(" ", ""));
} }
return volNames; return volNames;
} }
/** /**
* volumevolume * volumevolume
* <> * <>
* @param volumeName * @param volumeName
* @return * @return
* @see [##] * @see [##]
*/ */
public String getVolumeType(String volumeName) { public String getVolumeType(String volumeName) {
log.info("get volume type"); log.info("get volume type");
String volType = ""; String volType = "";
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser,
Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + volumeName + "|grep ^Type"); Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + volumeName + "|grep ^Type");
// System.out.println(reStrings); // System.out.println(reStrings);
if (reStrings == null) { if (reStrings == null) {
log.error("1501 get result is null"); log.error("1501 get result is null");
return null; return null;
} }
if (reStrings.size() == 0) { if (reStrings.size() == 0) {
log.error("1502 get result is nothing"); log.error("1502 get result is nothing");
return null; return null;
} }
if (!(reStrings.get(0).split(":")[0].contains("Type"))) { if (!(reStrings.get(0).split(":")[0].contains("Type"))) {
log.error("1503 get result string wrong"); log.error("1503 get result string wrong");
return null; return null;
} }
// System.out.println(reStrings); // System.out.println(reStrings);
for (Iterator it = reStrings.iterator(); it.hasNext();) { for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next(); String line = (String) it.next();
String str[] = line.split(":"); String str[] = line.split(":");
volType = str[1]; volType = str[1];
} }
volType = volType.replaceAll(" ", ""); volType = volType.replaceAll(" ", "");
return volType; return volType;
} }
public String getVolumeStatus(String volumeName) { public String getVolumeStatus(String volumeName) {
log.info("get volume status"); log.info("get volume status");
String volStatus = ""; String volStatus = "";
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser,
Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + "|grep ^Status"); Constant.rootPasswd, Constant.port, Constant.glusterVolumeInfo + "|grep ^Status");
// System.out.println(reStrings); // System.out.println(reStrings);
if (reStrings == null) { if (reStrings == null) {
log.error("1701 get result is null"); log.error("1701 get result is null");
return null; return null;
} }
if (reStrings.size() == 0) { if (reStrings.size() == 0) {
log.error("1702 get result is nothing"); log.error("1702 get result is nothing");
return null; return null;
} }
if (!(reStrings.get(0).split(":")[0].contains("Status"))) { if (!(reStrings.get(0).split(":")[0].contains("Status"))) {
log.error("1703 get result string wrong"); log.error("1703 get result string wrong");
return null; return null;
} }
for (Iterator it = reStrings.iterator(); it.hasNext();) { for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next(); String line = (String) it.next();
String str[] = line.split(":"); String str[] = line.split(":");
volStatus = str[1].replaceAll(" ", ""); volStatus = str[1].replaceAll(" ", "");
} }
return volStatus;
return volStatus; }
}
public Double getVolumeAllSize(String volumeName) {
public Double getVolumeAllSize(String volumeName) { log.info("get volume allSize");
log.info("get volume allSize"); Double allSize = null;
Double allSize = null; /*
* ======= // waiting for testing... public Double
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, * getVolumeAllSize(String volumeName) { log.info("get volume allSize");
Constant.rootPasswd, Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $2}'"); * Double allSize = null;
// System.out.println(reStrings); *
if (reStrings == null) { * >>>>>>> origin/AlexKie String command = "echo \"" +
log.error("1801 get result is null"); * Constant.rootPasswd + "\" |sudo -S df -h|grep " + volumeName +
return null; * "|awk '{print $2}'"; RunCommand runCommand = new RunCommand();
} * List<String> reStrings = runCommand.runCommandWait(command); <<<<<<<
if (reStrings.size() == 0) { * HEAD
log.error("1802 get result is nothing"); */
return null; List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
} Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $2}'");
/* // System.out.println(reStrings);
* char flag = reStrings.get(0).trim().toCharArray()[0]; if (flag < 48 if(reStrings==null){
* || flag > 57) { log.error("1803 get result string wrong"); return log.error("1801 get result is null");
* null; } return null;
*/ }
for (Iterator it = reStrings.iterator(); it.hasNext();) { if(reStrings.size()==0){
String line = (String) it.next(); log.error("1802 get result is nothing");
String str[] = line.split("[^0-9]"); return null;
allSize = Double.parseDouble(str[0]); }
} char flag = reStrings.get(0).trim().toCharArray()[0];
if (flag < 48 || flag > 57) {
return allSize; log.error("1803 get result string wrong");
} return null;
}
public Double getVolumeUseSize(String volumeName) {
log.info("get volume used size"); for (Iterator it = reStrings.iterator(); it.hasNext();) {
Double usedSize = null; String line = (String) it.next();
String str[] = line.split("[^0-9]");
allSize = Double.parseDouble(str[0]);
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, }
Constant.rootPasswd, Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $3}'");
// System.out.println(reStrings); return allSize;
if (reStrings == null) { }
log.error("1901 get result is null");
return null; public Double getVolumeUseSize(String volumeName) {
} log.info("get volume used size");
if (reStrings.size() == 0) { Double usedSize = null;
log.error("1902 get result is nothing");
return null; List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser,
} Constant.rootPasswd, Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $3}'");
char flag = reStrings.get(0).trim().toCharArray()[0]; // System.out.println(reStrings);
if (flag < 48 || flag > 57) { if (reStrings == null) {
log.error("1903 get result string wrong"); log.error("1901 get result is null");
return null; return null;
} }
if (reStrings.size() == 0) {
for (Iterator it = reStrings.iterator(); it.hasNext();) { log.error("1902 get result is nothing");
String line = (String) it.next(); return null;
String str[] = line.split("[^0-9]"); }
char flag = reStrings.get(0).trim().toCharArray()[0];
usedSize = Double.parseDouble(str[0]); if (flag < 48 || flag > 57) {
} log.error("1903 get result string wrong");
return null;
return usedSize; }
}
for (Iterator it = reStrings.iterator(); it.hasNext();) {
/** String line = (String) it.next();
* @param volumeName String str[] = line.split("[^0-9]");
* @return String ipAndpath[] = brick.split(":");
String ip = ipAndpath[0]; usedSize = Double.parseDouble(str[0]);
String path = ipAndpath[1]; }
*/
public List<String> getVolumeBricks(String volumeName) { return usedSize;
log.info("get volume bricks"); }
String cmd = "gluster volume info " + volumeName + " |grep ^Brick'[0-9]\\+' |awk '{print $2}'"; /**
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd); * @param volumeName
// System.out.println(reStrings); * @return String ipAndpath[] = brick.split(":");
if (reStrings == null) { String ip = ipAndpath[0];
log.error("1601 get volume bricks wrong"); String path = ipAndpath[1];
return null; */
} public List<String> getVolumeBricks(String volumeName) {
log.info("get volume bricks");
return reStrings;
} String cmd = "gluster volume info " + volumeName + " |grep ^Brick'[0-9]\\+' |awk '{print $2}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
public List<String> getVolumeMountPoint(String volumeName) { // System.out.println(reStrings);
log.info("get volume MountPoint"); if (reStrings == null) {
log.error("1601 get volume bricks wrong");
List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, return null;
Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $6}'"); }
// System.out.println(reStrings);
if(reStrings==null){ return reStrings;
log.error("11001 get result string wrong"); }
return null;
} public List<String> getVolumeMountPoint(String volumeName) {
if(reStrings.size()==0){ log.info("get volume MountPoint");
log.error("11002 "+volumeName+" is no mountpoint");
return null; List<String> reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
} Constant.port, Constant.df + "|grep " + volumeName + "|awk '{print $6}'");
// System.out.println(reStrings);
char flag = reStrings.get(0).trim().toCharArray()[0]; if(reStrings==null){
if (flag != '/') { log.error("11001 get result string wrong");
log.error("11003 get result string wrong"); return null;
return null; }
} if(reStrings.size()==0){
List<String> mountPoints = new ArrayList<>(); log.error("11002 "+volumeName+" is no mountpoint");
for(String mountPoint:reStrings){ return null;
mountPoint=mountPoint.replaceAll(" ", ""); }
mountPoints.add(mountPoint);
} char flag = reStrings.get(0).trim().toCharArray()[0];
return mountPoints; if (flag != '/') {
} log.error("11003 get result string wrong");
return null;
public Map<String, Double> getVolumebricksDataSize(String volumeName) { }
List<String> bricks = getVolumeBricks(volumeName); List<String> mountPoints = new ArrayList<>();
Map<String, Double> brick_size = new HashMap<>(); for(String mountPoint:reStrings){
if (bricks == null) { mountPoint=mountPoint.replaceAll(" ", "");
return null; mountPoints.add(mountPoint);
} }
for (String brick : bricks) { return mountPoints;
String ipAndpath[] = brick.split(":"); }
String ip = ipAndpath[0];
String path = ipAndpath[1]; public Map<String, Double> getVolumebricksDataSize(String volumeName) {
String cmd = "du -d 0 " + path + "|awk '{print $1}'"; List<String> bricks = getVolumeBricks(volumeName);
List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd, Map<String, Double> brick_size = new HashMap<>();
Constant.port, cmd); if (bricks == null) {
// System.out.println(reStrings); return null;
if (reStrings == null) { }
log.error("1901 get result is null"); for (String brick : bricks) {
return null; String ipAndpath[] = brick.split(":");
} String ip = ipAndpath[0];
if (reStrings.size() == 0) { String path = ipAndpath[1];
log.error("1902 get result is nothing"); String cmd = "du -d 0 " + path + "|awk '{print $1}'";
return null; List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd,
} Constant.port, cmd);
Pattern pattern = Pattern.compile("[0-9]*"); // System.out.println(reStrings);
Matcher isNum = pattern.matcher(reStrings.get(0)); if (reStrings == null) {
if (!isNum.matches()) { log.error("1901 get result is null");
log.error("1903 " + reStrings.get(0) + " is unexpect"); return null;
return null; }
} if (reStrings.size() == 0) {
brick_size.put(brick, Double.parseDouble(reStrings.get(0))); log.error("1902 get result is nothing");
} return null;
return brick_size; }
} Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(reStrings.get(0));
public Map<String, Double> getVolumebricksAvailableSize(String volumeName) { if (!isNum.matches()) {
List<String> bricks = getVolumeBricks(volumeName); log.error("1903 " + reStrings.get(0) + " is unexpect");
Map<String, Double> brick_size = new HashMap<>(); return null;
if (bricks == null) { }
return null; brick_size.put(brick, Double.parseDouble(reStrings.get(0)));
} }
for (String brick : bricks) { return brick_size;
String ipAndpath[] = brick.split(":"); }
String ip = ipAndpath[0];
String path = ipAndpath[1]; public Map<String, Double> getVolumebricksAvailableSize(String volumeName) {
String cmd = "df " + path + "|awk '{print $4}'"; List<String> bricks = getVolumeBricks(volumeName);
List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd, Map<String, Double> brick_size = new HashMap<>();
Constant.port, cmd); if (bricks == null) {
// System.out.println(reStrings); return null;
if (reStrings == null) { }
log.error("1901 get result is null"); for (String brick : bricks) {
return null; String ipAndpath[] = brick.split(":");
} String ip = ipAndpath[0];
if (reStrings.size() == 0) { String path = ipAndpath[1];
log.error("1902 get result is nothing"); String cmd = "df " + path + "|awk '{print $4}'";
return null; List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd,
} Constant.port, cmd);
Pattern pattern = Pattern.compile("[0-9]*"); // System.out.println(reStrings);
Matcher isNum = pattern.matcher(reStrings.get(1)); if (reStrings == null) {
if (!isNum.matches()) { log.error("1901 get result is null");
log.error("1903 " + reStrings.get(1) + " is unexpect"); return null;
return null; }
} if (reStrings.size() == 0) {
brick_size.put(brick, Double.parseDouble(reStrings.get(1))); log.error("1902 get result is nothing");
} return null;
return brick_size; }
} Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(reStrings.get(1));
@Test if (!isNum.matches()) {
public void test_getVolumebricksDataSize() { log.error("1903 " + reStrings.get(1) + " is unexpect");
System.out.println(getVolumebricksDataSize("gfs_ftp")); return null;
} }
brick_size.put(brick, Double.parseDouble(reStrings.get(1)));
@Test }
public void test_getVolumebricksAvailableSize() { return brick_size;
System.out.println(getVolumebricksAvailableSize("gfs_ftp")); }
}
@Test
// @Test public void test_getVolumebricksDataSize() {
public void test_getVolumeBricks() { System.out.println(getVolumebricksDataSize("gfs_ftp"));
getVolumeBricks("gfs_ftp"); }
}
} @Test
public void test_getVolumebricksAvailableSize() {
System.out.println(getVolumebricksAvailableSize("gfs_ftp"));
}
// @Test
public void test_getVolumeBricks() {
getVolumeBricks("gfs_ftp");
}
}

@ -1,149 +1,149 @@
/** /**
* : GfsServiceImpl.java * : GfsServiceImpl.java
* : </> * : </>
* : <> * : <>
* @author chen * @author chen
* : <> * : <>
* 201698 * 201698
* <> * <>
*/ */
package com.platform.service.impl; package com.platform.service.impl;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.platform.entities.Brick; import com.platform.entities.Brick;
import com.platform.entities.FolderNode; import com.platform.entities.FolderNode;
import com.platform.entities.VolumeEntity; import com.platform.entities.VolumeEntity;
import com.platform.glusterfs.CopyData; import com.platform.glusterfs.CopyData;
import com.platform.glusterfs.GetTreeData; import com.platform.glusterfs.GetTreeData;
import com.platform.glusterfs.VolumeInfo; import com.platform.glusterfs.VolumeInfo;
import com.platform.service.IGfsService; import com.platform.service.IGfsService;
import com.platform.utils.CacheTreeData; import com.platform.utils.CacheTreeData;
import com.platform.utils.ThreadVolume; import com.platform.utils.ThreadVolume;
import com.platform.utils.getTreeDataByPath; import com.platform.utils.getTreeDataByPath;
/** /**
* <> gfs * <> gfs
* <> * <>
* @author chen * @author chen
* @version [201698] * @version [201698]
* @see [/] * @see [/]
* @since [/] * @since [/]
*/ */
@Service(value = "gfsService") @Service(value = "gfsService")
public class GfsServiceImpl implements IGfsService { public class GfsServiceImpl implements IGfsService {
/** gfs目录树形查询 */ /** gfs目录树形查询 */
private getTreeDataByPath getFolder = new getTreeDataByPath(); private getTreeDataByPath getFolder = new getTreeDataByPath();
/** 数据迁移实现 */ /** 数据迁移实现 */
private CopyData copydata = new CopyData(); private CopyData copydata = new CopyData();
/** Volume信息查询 */ /** Volume信息查询 */
private VolumeInfo volumeInfo = new VolumeInfo(); private VolumeInfo volumeInfo = new VolumeInfo();
@Override @Override
public FolderNode getFolder(String path) { public FolderNode getFolder(String path) {
FolderNode result = getFolder.findByPath(path); FolderNode result = getFolder.findByPath(path);
return result; return result;
} }
@Override @Override
public int copyFolder(List<String> srcFolders, String dstFolder, String name) public int copyFolder(List<String> srcFolders, String dstFolder, String name)
throws Exception { throws Exception {
int status = 0 ; int status = 0 ;
if (null != srcFolders) { if (null != srcFolders) {
for (String string : srcFolders) { for (String string : srcFolders) {
status = copydata.copyFolderFiles(string, dstFolder, name); status = copydata.copyFolderFiles(string, dstFolder, name);
} }
} }
return status; return status;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see com.platform.service.IGfsService#getAllVolume() * @see com.platform.service.IGfsService#getAllVolume()
*/ */
@Override @Override
public List<VolumeEntity> getAllVolumes() throws Exception { public List<VolumeEntity> getAllVolumes() throws Exception {
List<VolumeEntity> volumeList = new ArrayList<>(); List<VolumeEntity> volumeList = new ArrayList<>();
List<String> volumeNameList = volumeInfo.showAllVolumeName(); List<String> volumeNameList = volumeInfo.showAllVolumeName();
if (null == volumeNameList) { if (null == volumeNameList) {
return null; return null;
} }
for (String volumeName : volumeNameList) { for (String volumeName : volumeNameList) {
VolumeEntity volume = new VolumeEntity(); VolumeEntity volume = new VolumeEntity();
volume.setName(volumeName); volume.setName(volumeName);
List<String> path = volumeInfo.getVolumeMountPoint(volumeName); List<String> path = volumeInfo.getVolumeMountPoint(volumeName);
//默认加载第一个路径 //默认加载第一个路径
if (null != path && path.size() > 0) { if (null != path && path.size() > 0) {
volume.setPath(path.get(0)); volume.setPath(path.get(0));
} }
volume.setAllSize(volumeInfo.getVolumeAllSize(volumeName)); volume.setAllSize(volumeInfo.getVolumeAllSize(volumeName));
volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName)); volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName));
//TODO 查询brick-- //TODO 查询brick--
//返回 ip:path //返回 ip:path
List<String> brickStrs = volumeInfo.getVolumeBricks(volumeName); List<String> brickStrs = volumeInfo.getVolumeBricks(volumeName);
//brick已用大小 //brick已用大小
Map<String, Double> usedSize = volumeInfo.getVolumebricksDataSize(volumeName); Map<String, Double> usedSize = volumeInfo.getVolumebricksDataSize(volumeName);
Map<String, Double> availableSize = volumeInfo.getVolumebricksAvailableSize(volumeName); Map<String, Double> availableSize = volumeInfo.getVolumebricksAvailableSize(volumeName);
List<Brick> brickList = new ArrayList<Brick>(); List<Brick> brickList = new ArrayList<Brick>();
for (String brickIpPath : brickStrs) { for (String brickIpPath : brickStrs) {
Brick b = new Brick(); Brick b = new Brick();
String ipAndpath[] = brickIpPath.split(":"); String ipAndpath[] = brickIpPath.split(":");
String brickip = ipAndpath[0]; String brickip = ipAndpath[0];
String brickpath = ipAndpath[1]; String brickpath = ipAndpath[1];
//iP , path , //iP , path ,
b.setIp(brickip); b.setIp(brickip);
b.setPath(brickpath); b.setPath(brickpath);
b.setAvailableSize(availableSize.get(brickIpPath)); b.setAvailableSize(availableSize.get(brickIpPath));
b.setUsedSize(usedSize.get(brickIpPath)); b.setUsedSize(usedSize.get(brickIpPath));
brickList.add(b); brickList.add(b);
} }
volume.setBrick(brickList); volume.setBrick(brickList);
if (null != volume.getPath()) { if (null != volume.getPath()) {
// 获得 folder 目录 // 获得 folder 目录
volume.setFolder(getFolder(volume.getPath())); volume.setFolder(getFolder(volume.getPath()));
} }
volumeList.add(volume); volumeList.add(volume);
} }
return volumeList; return volumeList;
} }
@Override @Override
public VolumeEntity getOneVolume(String volumeName) throws Exception { public VolumeEntity getOneVolume(String volumeName) throws Exception {
VolumeEntity volume = new VolumeEntity(); VolumeEntity volume = new VolumeEntity();
volume.setName(volumeName); volume.setName(volumeName);
List<String> path = volumeInfo.getVolumeMountPoint(volumeName); List<String> path = volumeInfo.getVolumeMountPoint(volumeName);
if (null != path && path.size() > 0) { if (null != path && path.size() > 0) {
volume.setPath(path.get(0)); volume.setPath(path.get(0));
} }
volume.setAllSize(volumeInfo.getVolumeAllSize(volumeName)); volume.setAllSize(volumeInfo.getVolumeAllSize(volumeName));
volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName)); volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName));
// volume.setBrick(brick); // volume.setBrick(brick);
if (null != volume.getPath()) { if (null != volume.getPath()) {
volume.setFolder(getFolder(path.get(0))); volume.setFolder(getFolder(path.get(0)));
} }
return volume; return volume;
} }
@Override @Override
public int moveData(String volumeName, String srcPath, String dstPath) public int moveData(String volumeName, String srcPath, String dstPath)
throws Exception { throws Exception {
int result = copydata.copyFolderFiles(srcPath, dstPath, "app"); int result = copydata.copyFolderFiles(srcPath, dstPath, "app");
return result; return result;
} }
@Override @Override
public int deleteData(String volumeName, String srcPath) throws Exception { public int deleteData(String volumeName, String srcPath) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 0; return 0;
} }
} }

@ -1,19 +1,19 @@
package com.platform.utils; package com.platform.utils;
import java.util.List; import java.util.List;
import com.platform.entities.FolderNode; import com.platform.entities.FolderNode;
public class CacheTreeData { public class CacheTreeData {
private static List<FolderNode> folders = null; private static List<FolderNode> folders = null;
public static List<FolderNode> getFolders() { public static List<FolderNode> getFolders() {
return folders; return folders;
} }
public static void setFolders(List<FolderNode> folders) { public static void setFolders(List<FolderNode> folders) {
CacheTreeData.folders = folders; CacheTreeData.folders = folders;
} }
} }

@ -1,74 +1,74 @@
package com.platform.utils; package com.platform.utils;
import java.util.Properties; import java.util.Properties;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
public class ConfigsLoader implements ServletContextListener { public class ConfigsLoader implements ServletContextListener {
private static ConfigPropertyReader cReader = null; private static ConfigPropertyReader cReader = null;
@Override @Override
public void contextDestroyed(ServletContextEvent sEvent) { public void contextDestroyed(ServletContextEvent sEvent) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
Configs.CONSOLE_LOGGER.info("系统停止.."); Configs.CONSOLE_LOGGER.info("系统停止..");
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
@Override @Override
public void contextInitialized(ServletContextEvent sEvent) { public void contextInitialized(ServletContextEvent sEvent) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
Configs.CONSOLE_LOGGER.info("系统初始化.."); Configs.CONSOLE_LOGGER.info("系统初始化..");
String contextPath = sEvent.getServletContext().getRealPath("/") String contextPath = sEvent.getServletContext().getRealPath("/")
+ "WEB-INF/config/config.properties"; + "WEB-INF/config/config.properties";
this.cReader = ConfigPropertyReader.Builder(contextPath); this.cReader = ConfigPropertyReader.Builder(contextPath);
init(); init();
new ThreadVolume("").start(); new ThreadVolume("").start();
} }
public static void init() { public static void init() {
Properties properties = cReader.getProperties(); Properties properties = cReader.getProperties();
Configs.KUBE_MASTER_URL = properties.getProperty("kubeMasterUrl"); Configs.KUBE_MASTER_URL = properties.getProperty("kubeMasterUrl");
Configs.COLLECT_USER_NAME = properties.getProperty("collect-user-name"); Configs.COLLECT_USER_NAME = properties.getProperty("collect-user-name");
Configs.COLLECT_PASSWORD = properties.getProperty("collect-password"); Configs.COLLECT_PASSWORD = properties.getProperty("collect-password");
Configs.COLLECT_SERVICE_NAME = properties Configs.COLLECT_SERVICE_NAME = properties
.getProperty("collect-service-name"); .getProperty("collect-service-name");
Configs.GATHER_USER_NAME = properties.getProperty("gather-user-name"); Configs.GATHER_USER_NAME = properties.getProperty("gather-user-name");
Configs.GATHER_USER_PASSWORD = properties Configs.GATHER_USER_PASSWORD = properties
.getProperty("gather-user-password"); .getProperty("gather-user-password");
Configs.GATHER_PORT = properties.getProperty("gather-port"); Configs.GATHER_PORT = properties.getProperty("gather-port");
Configs.GATHER_SERVICE_NAME = properties Configs.GATHER_SERVICE_NAME = properties
.getProperty("gather-service-name"); .getProperty("gather-service-name");
Configs.TABLE_SUFFIX = properties.getProperty("table-suffix"); Configs.TABLE_SUFFIX = properties.getProperty("table-suffix");
Configs.EXTRACT_LOG_LOCALTION = properties Configs.EXTRACT_LOG_LOCALTION = properties
.getProperty("extract-log-localtion"); .getProperty("extract-log-localtion");
Configs.GATHER_TABLESPACE_NAME = properties Configs.GATHER_TABLESPACE_NAME = properties
.getProperty("gather-tablespace-name"); .getProperty("gather-tablespace-name");
Configs.GATHER_TABLESPACE_PATH = properties Configs.GATHER_TABLESPACE_PATH = properties
.getProperty("gather-tablespace-path"); .getProperty("gather-tablespace-path");
Configs.GATHER_TABLE_PASSWORD=properties.getProperty("gather-table-user-password"); Configs.GATHER_TABLE_PASSWORD=properties.getProperty("gather-table-user-password");
} }
public ConfigPropertyReader getcReader() { public ConfigPropertyReader getcReader() {
return cReader; return cReader;
} }
@SuppressWarnings("static-access") @SuppressWarnings("static-access")
public void setcReader(ConfigPropertyReader cReader) { public void setcReader(ConfigPropertyReader cReader) {
this.cReader = cReader; this.cReader = cReader;
} }
} }

@ -1,32 +1,33 @@
package com.platform.utils; package com.platform.utils;
import java.util.List; import java.util.List;
public class Constant { public class Constant {
public static String rootUser = "root"; public static String rootUser = "root";
public static String rootPasswd = "root"; public static String rootPasswd = "root";
public static String hostIp = "192.168.0.116"; public static String hostIp = "192.168.0.116";
// public static String hostIp = "192.168.1.105"; // public static String hostIp = "192.168.1.105";
public static int port = 22; public static int port = 22;
public static String glusterPeerStatus = "gluster peer status"; public static String glusterPeerStatus = "gluster peer status";
public static String glusterVolumeInfo = "gluster volume info "; public static String glusterVolumeInfo = "gluster volume info ";
public static String df = "df -k "; public static String df = "df -k ";
public static String peerincluster_connected="PeerinCluster(Connected)"; public static String peerincluster_connected="PeerinCluster(Connected)";
public static String peerincluster_disconnected="PeerinCluster(Disconnected)"; public static String peerincluster_disconnected="PeerinCluster(Disconnected)";
public static String distributed="distributed"; public static String distributed="distributed";
public static String replica="replica"; public static String replica="replica";
public static String stripe="stripe"; public static String stripe="stripe";
public static String noVolume="No volumes present"; public static String noVolume="No volumes present";
public static GanymedSSH ganymedSSH=new GanymedSSH(hostIp, rootUser, rootPasswd, port); public static GanymedSSH ganymedSSH=new GanymedSSH(hostIp, rootUser, rootPasswd, port);
public static String fileGetTreeData="./WEB-INF/config/getTreedata.sh"; public static String fileGetTreeData="./WEB-INF/config/getTreedata.sh";
/** /**
* volume 线 * volume 线
*/ */
public final static int get_volume_sleep_time = 300000; public final static int get_volume_sleep_time = 300000;
/** /**
* volume 线 * volume 线
*/ */
public final static int update_dataInfo_sleep_time = 3000; public final static int update_dataInfo_sleep_time = 3000;
}
}

@ -1,267 +1,267 @@
package com.platform.utils; package com.platform.utils;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.PropertyConfigurator;
import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session; import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler; import ch.ethz.ssh2.StreamGobbler;
import ch.ethz.ssh2.*; import ch.ethz.ssh2.*;
public class GanymedSSH { public class GanymedSSH {
public static Logger log = Logger.getLogger(GanymedSSH.class); public static Logger log = Logger.getLogger(GanymedSSH.class);
Connection conn; Connection conn;
public boolean status = true;// 锟角凤拷锟斤拷锟街达拷锟斤拷锟斤拷锟阶刺<E998B6> public boolean status = true;// 锟角凤拷锟斤拷锟街达拷锟斤拷锟斤拷锟阶刺<E998B6>
public GanymedSSH() { public GanymedSSH() {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public GanymedSSH(String host, String username, String password, int port) { public GanymedSSH(String host, String username, String password, int port) {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
try { try {
conn = getOpenedConnection(host, username, password, port); conn = getOpenedConnection(host, username, password, port);
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
public Connection getOpenedConnection(String host, String username, String password, int port) public Connection getOpenedConnection(String host, String username, String password, int port)
throws IOException { throws IOException {
conn = new Connection(host, port); conn = new Connection(host, port);
conn.connect(); // make sure the connection is opened conn.connect(); // make sure the connection is opened
boolean isAuthenticated = conn.authenticateWithPassword(username, password); boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) if (isAuthenticated == false)
throw new IOException("Authentication failed."); throw new IOException("Authentication failed.");
return conn; return conn;
} }
public void execCmdNoWaitAcquiescent(String cmd) { public void execCmdNoWaitAcquiescent(String cmd) {
String host=Constant.hostIp; String host=Constant.hostIp;
String username=Constant.rootUser; String username=Constant.rootUser;
String password=Constant.rootPasswd; String password=Constant.rootPasswd;
int port=Constant.port; int port=Constant.port;
Session sess = null; Session sess = null;
try { try {
conn = getOpenedConnection(host, username, password, port);
sess = conn.openSession(); sess = conn.openSession();
// 执锟斤拷cmd // 执锟斤拷cmd
sess.execCommand(cmd); sess.execCommand(cmd);
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
} }
public void execCmdNoWait(String host, String username, String password, int port, String cmd) { public void execCmdNoWait(String host, String username, String password, int port, String cmd) {
Session sess = null; Session sess = null;
try { try {
conn = getOpenedConnection(host, username, password, port); conn = getOpenedConnection(host, username, password, port);
sess = conn.openSession(); sess = conn.openSession();
// 执锟斤拷cmd // 执锟斤拷cmd
sess.execCommand(cmd); sess.execCommand(cmd);
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
} }
public List<String> execCmdWaitAcquiescent(String cmd) { public List<String> execCmdWaitAcquiescent(String cmd) {
String host=Constant.hostIp; String host=Constant.hostIp;
String username=Constant.rootUser; String username=Constant.rootUser;
String password=Constant.rootPasswd; String password=Constant.rootPasswd;
int port=Constant.port; int port=Constant.port;
List<String> reStrings = new ArrayList<String>(); List<String> reStrings = new ArrayList<String>();
Session sess = null; Session sess = null;
try { try {
sess = conn.openSession(); sess = conn.openSession();
// 执锟斤拷cmd // 执锟斤拷cmd
sess.execCommand(cmd); sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr()); InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout)); BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr)); BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
while (true) { while (true) {
String line = stdoutReader.readLine(); String line = stdoutReader.readLine();
if (line != null) { if (line != null) {
// System.out.println(line); // System.out.println(line);
reStrings.add(line); reStrings.add(line);
} else { } else {
break; break;
} }
} }
if(reStrings.size()==0){ if(reStrings.size()==0){
while (true) { while (true) {
String line = stderrReader.readLine(); String line = stderrReader.readLine();
if (line != null) { if (line != null) {
// System.out.println(line); // System.out.println(line);
reStrings.add(line); reStrings.add(line);
} else { } else {
break; break;
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
return reStrings; return reStrings;
} }
public List<String> execCmdWait(String host, String username, String password, int port, String cmd) { public List<String> execCmdWait(String host, String username, String password, int port, String cmd) {
List<String> reStrings = new ArrayList<String>(); List<String> reStrings = new ArrayList<String>();
Session sess = null; Session sess = null;
try { try {
sess = conn.openSession(); sess = conn.openSession();
// 执锟斤拷cmd // 执锟斤拷cmd
sess.execCommand(cmd); sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr()); InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout)); BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr)); BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
while (true) { while (true) {
String line = stdoutReader.readLine(); String line = stdoutReader.readLine();
if (line != null) { if (line != null) {
// System.out.println(line); // System.out.println(line);
reStrings.add(line); reStrings.add(line);
} else { } else {
break; break;
} }
} }
if(reStrings.size()==0){ if(reStrings.size()==0){
while (true) { while (true) {
String line = stderrReader.readLine(); String line = stderrReader.readLine();
if (line != null) { if (line != null) {
// System.out.println(line); // System.out.println(line);
reStrings.add(line); reStrings.add(line);
} else { } else {
break; break;
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
return reStrings; return reStrings;
} }
public Map<String, String> execMD5cmd(String host, String username, String password, int port, String cmd, public Map<String, String> execMD5cmd(String host, String username, String password, int port, String cmd,
String prefix) { String prefix) {
Map<String, String> md5 = new HashMap<String, String>(); Map<String, String> md5 = new HashMap<String, String>();
Session sess = null; Session sess = null;
try { try {
sess = conn.openSession(); sess = conn.openSession();
// 执锟斤拷cmd // 执锟斤拷cmd
sess.execCommand(cmd); sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stdout = new StreamGobbler(sess.getStdout());
@SuppressWarnings("resource") @SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) { while (true) {
String line = br.readLine(); String line = br.readLine();
if (line != null) { if (line != null) {
String[] lines = line.split(" "); String[] lines = line.split(" ");
String key = lines[1].replace(prefix, ""); String key = lines[1].replace(prefix, "");
String value = lines[0]; String value = lines[0];
md5.put(key, value); md5.put(key, value);
// System.out.println(key+"\t"+value); // System.out.println(key+"\t"+value);
} else { } else {
break; break;
} }
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
return md5; return md5;
} }
public String execGetSize(String cmd) { public String execGetSize(String cmd) {
status = false; status = false;
String str_size = "0"; String str_size = "0";
Session sess = null; Session sess = null;
try { try {
// 执锟斤拷cmd // 执锟斤拷cmd
sess = conn.openSession(); sess = conn.openSession();
sess.execCommand(cmd); sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stdout = new StreamGobbler(sess.getStdout());
@SuppressWarnings("resource") @SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) { while (true) {
String line = br.readLine(); String line = br.readLine();
if (line != null) { if (line != null) {
// String[] lines=line.split(" "); // String[] lines=line.split(" ");
// str_size=lines[0]; // str_size=lines[0];
str_size = line; str_size = line;
} else { } else {
break; break;
} }
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
sess.close(); sess.close();
} }
status = true; status = true;
return str_size; return str_size;
} }
public static void main(String[] args) { public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties"); PropertyConfigurator.configure("log4j.properties");
} }
} }

@ -1,48 +1,48 @@
package com.platform.utils; package com.platform.utils;
import java.util.List; import java.util.List;
import com.platform.entities.FolderNode; import com.platform.entities.FolderNode;
public class getTreeDataByPath { public class getTreeDataByPath {
/** /**
* @param path * @param path
* @return * @return
*/ */
public FolderNode findByPath(String path) { public FolderNode findByPath(String path) {
List<FolderNode> folderNodelist = CacheTreeData.getFolders(); List<FolderNode> folderNodelist = CacheTreeData.getFolders();
if (null == folderNodelist) { if (null == folderNodelist) {
return null; return null;
} }
FolderNode folder = null; FolderNode folder = null;
for (FolderNode folderNode : folderNodelist) { for (FolderNode folderNode : folderNodelist) {
folder = getFolder(folderNode, path); folder = getFolder(folderNode, path);
if (null != folder) { if (null != folder) {
break; break;
} }
} }
return folder; return folder;
} }
/** /**
* @param f * @param f
* @return * @return
*/ */
private FolderNode getFolder(FolderNode f, String path){ private FolderNode getFolder(FolderNode f, String path){
FolderNode result = null; FolderNode result = null;
if(path.equals(f.getPath())){ if(path.equals(f.getPath())){
return f; return f;
} }
List<FolderNode> folds = f.getChildNodes(); List<FolderNode> folds = f.getChildNodes();
if (null != folds) { if (null != folds) {
for (FolderNode folderNode : folds) { for (FolderNode folderNode : folds) {
result = getFolder(folderNode, path); result = getFolder(folderNode, path);
if (null != result) { if (null != result) {
break; break;
} }
} }
} }
return result; return result;
} }
} }

Loading…
Cancel
Save