web_gfs
chenlw 9 years ago
commit 4b91e41581

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="output" path="WebRoot/WEB-INF/classes"/>
</classpath>

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>jfinal-demo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>jfinal-demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 添加至 web.xml 1.4 添加 java文件 在项目 src 目录下创建 com.platform.config 包,并在 包下创建 JfinalConfig
文件, -->
<filter>
<filter-name>jfinalF</filter-name>
<filter-class>com.jfinal.core.JFinalFilter</filter-class>
<init-param>
<param-name>configClass</param-name>
<param-value>com.platform.config.JfinalConfig</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jfinalF</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

@ -0,0 +1,37 @@
package com.platform.config;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.platform.controller.GfsController;
import com.platform.controller.HelloController;
public class JfinalConfig extends JFinalConfig {
@Override
public void configConstant(Constants me) {
me.setDevMode(true);
}
@Override
public void configHandler(Handlers me) {
}
@Override
public void configInterceptor(Interceptors me) {
}
@Override
public void configPlugin(Plugins me) {
}
@Override
public void configRoute(Routes me) {
me.add("/hello", HelloController.class);
me.add("/gfs", GfsController.class);
}
}

@ -0,0 +1,53 @@
package com.platform.controller;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import com.jfinal.core.Controller;
import com.platform.entities.FolderNode;
import com.platform.entities.VolumeEntity;
import com.platform.utils.CacheTreeData;
import com.platform.utils.getTreeDataByPath;
public class GfsController extends Controller {
/** gfs目录树形查询 */
private getTreeDataByPath getFolder = new getTreeDataByPath();
/**
* -"/gfs"
*/
public void index() {
renderText("hello gfs !");
}
public void getAllvolume(){
List<VolumeEntity> volumeList = CacheTreeData.getVolumeList();
if (null == volumeList) {
JSONObject jsondata = JSONObject.fromObject(new ArrayList<VolumeEntity>());
renderJson(jsondata.toString());
}
for (VolumeEntity volume : volumeList) {
if (null != volume.getPath()) {
// 获得 folder 目录
List<FolderNode> list = new ArrayList<FolderNode>();
FolderNode currNode = getFolder(volume.getPath());
if (null != currNode && null != currNode.getChildNodes()) {
list.addAll(currNode.getChildNodes());
}
volume.setFolder(list);
}
}
JSONObject jsondata = JSONObject.fromObject(volumeList);
renderJson(jsondata.toString());
}
public FolderNode getFolder(String path) {
FolderNode result = getFolder.findByPath(path);
return result;
}
}

@ -0,0 +1,48 @@
package com.platform.controller;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import com.jfinal.core.Controller;
import com.platform.entities.FolderNode;
import com.platform.form.baseForm;
public class HelloController extends Controller {
public void index() {
renderText("hello jfinal index !");
}
public void tojson() {
renderText("hello jfinal tojson !");
}
public void gain() {
baseForm form = new baseForm();
form.setId("12");
form.setName("n3");
String base = getPara("jsondata");
System.err.println(base);
if (null != base) {
FolderNode f = new FolderNode();
f.setIsFolder(2);
f.setName("1");
f.setPath("/da");
FolderNode f1 = new FolderNode();
f1.setIsFolder(2);
f1.setName("1");
f1.setPath("/da");
List<FolderNode> lis = new ArrayList<FolderNode>();
lis.add(f1);
f.setChildNodes(lis);
JSONObject jsondata = JSONObject.fromObject(f);
renderJson(jsondata.toString());
}
else {
renderText("hello jfinal gaindata ! ");
}
}
}

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

@ -0,0 +1,65 @@
package com.platform.entities;
import java.util.ArrayList;
import java.util.List;
public class FolderNode {
private String name;
private int isFolder; // 1 is file and other integer is folder show children number
private String path;
private List<FolderNode> childNodes = new ArrayList<FolderNode>();
public FolderNode() {
// TODO Auto-generated constructor stub
}
public FolderNode(String name) {
this.name = name;
}
public FolderNode(String name, int isFolder) {
this.name = name;
this.isFolder = isFolder;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return the isFolder
*/
public int getIsFolder() {
return isFolder;
}
/**
* @param isFolder the isFolder to set
*/
public void setIsFolder(int isFolder) {
this.isFolder = isFolder;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<FolderNode> getChildNodes() {
return childNodes;
}
public void setChildNodes(List<FolderNode> childNodes) {
this.childNodes = childNodes;
}
}

@ -0,0 +1,164 @@
/**
* : VolumeEntity.java
* : </>
* : <>
* @author chen
* : <>
* 201699
* <>
*/
package com.platform.entities;
import java.util.ArrayList;
import java.util.List;
/**
* <> gfs volume
* <>
* @author chen
* @version [201699]
* @see [/]
* @since [/]
*/
public class VolumeEntity {
/** volume总大小 */
private double allSize;
/** volume已使用大小 */
private double usedSize;
/** volume名称 */
private String name;
/** 挂载点 */
private String path;
/** * exist正常返回状态Started,Stopped,Created */
private boolean status;
private String type;
/** volume树形目录 */
private List<FolderNode> folder = new ArrayList<FolderNode>();
/** volume的 块 */
private List<Brick> brick = new ArrayList<Brick>();
/**
* @return the allSize
*/
public double getAllSize() {
return allSize;
}
/**
* @param allSize the allSize to set
*/
public void setAllSize(double allSize) {
this.allSize = allSize;
}
/**
* @return the usedSize
*/
public double getUsedSize() {
return usedSize;
}
/**
* @param usedSize the usedSize to set
*/
public void setUsedSize(double usedSize) {
this.usedSize = usedSize;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the status
*/
public boolean isStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(boolean status) {
this.status = status;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the folder
*/
public List<FolderNode> getFolder() {
return folder;
}
/**
* @param folder the folder to set
*/
public void setFolder(List<FolderNode> folder) {
this.folder = folder;
}
/**
* @return the brick
*/
public List<Brick> getBrick() {
return brick;
}
/**
* @param brick the brick to set
*/
public void setBrick(List<Brick> brick) {
this.brick = brick;
}
}

@ -0,0 +1,87 @@
package com.platform.form;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Bean2MapUtils {
/**
* Map JavaBean
* @param type
* @param map map
* @return JavaBean
* @throws IntrospectionException
*
* @throws IllegalAccessException
* JavaBean
* @throws InstantiationException
* JavaBean
* @throws InvocationTargetException
* setter
*/
public static Object convertMap(Class type, Map map)
throws IntrospectionException, IllegalAccessException,
InstantiationException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
Object obj = type.newInstance(); // 创建 JavaBean 对象
// 给 JavaBean 对象的属性赋值
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
try{
if (map.containsKey(propertyName)) {
// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
Object value = map.get(propertyName);
Object[] args = new Object[1];
args[0] = value;
descriptor.getWriteMethod().invoke(obj, args);
}
}
catch(Exception e){
}
}
return obj;
}
/**
* JavaBean Map
* @param bean JavaBean
* @return Map
* @throws IntrospectionException
* @throws IllegalAccessException JavaBean
* @throws InvocationTargetException setter
*/
public static Map convertBean(Object bean)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null) {
returnMap.put(propertyName, result);
} else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}
}

@ -0,0 +1,55 @@
package com.platform.form;
public class baseForm {
private String id;
private String name;
private baseForm base;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the base
*/
public baseForm getBase() {
return base;
}
/**
* @param base the base to set
*/
public void setBase(baseForm base) {
this.base = base;
}
}

@ -0,0 +1,103 @@
package com.platform.glusterfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.platform.utils.Constant;
public class CheckoutMD5 {
public static Logger log = Logger.getLogger(CheckoutMD5.class);
String sourcePath;
String destPath;
String dataName;
// String cmd_crateSourceMD5File="find "+sourcePath+dataName+"/app/ -type f
// -print0 | xargs -0 md5sum | sort >"+deskPath+dataName+"_md5.txt";
String cmd_getSourceMD5File;
// String cmd_crateDestMD5File="find "+destPath+dataName+"/app/ -type f
// -print0 | xargs -0 md5sum | sort >"+deskPath+dataName+"_md5.txt";
String cmd_getDestMD5File;
Map<String, String> source_md5 = new HashMap<String, String>();
Map<String, String> dest_md5 = new HashMap<String, String>();
public CheckoutMD5() {
// TODO Auto-generated constructor stub
}
public CheckoutMD5(String sourcePath, String destPath, String dataName) {
// TODO Auto-generated constructor stub
this.sourcePath = sourcePath;
this.destPath = destPath;
this.dataName = dataName;
cmd_getSourceMD5File = "find " + sourcePath + dataName + "/app/ -type f -print0 | xargs -0 md5sum | sort ";
cmd_getDestMD5File = "find " + destPath + dataName + "/app/ -type f -print0 | xargs -0 md5sum | sort ";
}
/**
* sourcePathdestPath1
* 0MD5-1-2-3
*
* @param sourcePath
* @param destPath
* @return
* @see [##]
*/
public int checkoutMD5Folder(String sourcePath, String destPath) {
log.info("start checkout md5 "+sourcePath+" and "+ destPath);
List<String> wrong_files = new ArrayList<String>();
String source_cmd = "find " + sourcePath + " -type f -print0 | xargs -0 md5sum";
String dest_cmd = "find " + destPath + " -type f -print0 | xargs -0 md5sum";
List<String> sourceReStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(source_cmd);
if (sourceReStrings == null || sourceReStrings.size() == 0) {
log.error("get " + sourcePath + " MD5 error!");
return -1;
}
if(sourceReStrings.get(0).contains(Constant.noSuchFile)){
log.error(sourcePath+" is not exist!");
return -2;
}
List<String> destReStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(dest_cmd);
if (destReStrings == null || destReStrings.size() == 0) {
log.error("get " + destReStrings + " MD5 error!");
return -1;
}
if(destReStrings.get(0).contains(Constant.noSuchFile)){
log.error(destPath+" is not exist!");
return -3;
}
Map<String, String> source_md5 = new HashMap<String, String>();
Map<String, String> dest_md5 = new HashMap<String, String>();
for (String line : sourceReStrings) {
String[] lines = line.split(" ");
String key = lines[1].replace(sourcePath, "").trim();
String value = lines[0].trim();
source_md5.put(key, value);
}
for (String line : destReStrings) {
String[] lines = line.split(" ");
String key = lines[1].replace(destPath, "").trim();
String value = lines[0].trim();
dest_md5.put(key, value);
}
for (Map.Entry<String, String> mapEntry : source_md5.entrySet()) {
if (!(dest_md5.containsKey(mapEntry.getKey())
&& dest_md5.get(mapEntry.getKey()).equals(mapEntry.getValue()))) {
log.info(sourcePath + " and " + destPath + " is not same!");
return 0;
// System.out.println(mapEntry.getKey());
}
}
log.info(sourcePath + " and " + destPath + " is same!");
return 1;
}
public static void main(String[] args) {
CheckoutMD5 checkoutMD5 = new CheckoutMD5();
System.out.println(checkoutMD5.checkoutMD5Folder("/home/v1_copy","/home/ubuntu"));
}
}

@ -0,0 +1,153 @@
package com.platform.glusterfs;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.platform.utils.Constant;
import ch.ethz.ssh2.Connection;
/**
*
* @author liliy
* @version [2016912]
* @see [/]
* @since [/]
*/
public class ClusterInfo {
public static Logger log = Logger.getLogger(ClusterInfo.class);
/**
*
* nullmapipip
* ipPeerinCluster(Connected)
* ipPeerinCluster(Disconnected)
* @return
* @throws IOException
* @see [##]
*/
public Map<String, String> showClusterInfo() {
// log.info("get cluster info");
Map<String, String> peerIps = new HashMap<String, String>();
peerIps.put(Constant.hostIp, Constant.peerincluster_connected);
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(Constant.glusterPeerStatus);
if (reStrings == null) {
log.error("1101 command get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1102 command get result is nothing");
return null;
}
if (reStrings.get(0).contains("No peers present")) {
return peerIps;
}
if (!(reStrings.get(0).split(":")[0].contains("Number of Peers"))) {
log.error("1103 get result string wrong");
return null;
}
// System.out.print(reStrings.get(0));
int flag = 0;
String ipString = "";
String state = "";
for (Iterator it2 = reStrings.iterator(); it2.hasNext();) {
String line = (String) it2.next();
line=line.replaceAll(" +", " ");
String keyValue[] = line.split(":");
if (keyValue[0].equals("Hostname")) {
if (keyValue.length < 2) {
log.error("1105 command get result is wrong");
continue;
}
ipString = keyValue[1].replaceAll(" ", "");
flag = 1;
} else if (flag == 1 && keyValue[0].equals("State")) {
if (keyValue.length < 2) {
log.error("1106 command get result is wrong");
continue;
}
state = keyValue[1].replaceAll(" ", "");
flag = 0;
peerIps.put(ipString, state);
}
}
// for (Map.Entry<String, String> entry:peerIps.entrySet()){
// String key=entry.getKey();
// if(key.equals(Constant.hostIp)){
// continue;
// }
// String value=entry.getValue();
// if(Constant.ganymedSSH.otherConns==null){
// Constant.ganymedSSH.otherConns=new HashMap<String,Connection>();
// }
// if(!Constant.ganymedSSH.otherConns.containsKey(key)){
// Connection connection=null;
// try {
// connection = Constant.ganymedSSH.getOpenedConnection(key, Constant.rootUser, Constant.rootPasswd, Constant.port);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// Constant.ganymedSSH.otherConns.put(key,connection);
// }
// }
return peerIps;
}
/**
* ipip
* ipnull
* ipPeerinCluster(Connected)
* ipPeerinCluster(Disconnected)
* @param peerip
* @return
* @see [##]
*/
public String getPeerStatus(String peerip){
Map<String, String> peerIps=showClusterInfo();
if(peerIps==null || peerIps.size()==0){
return null;
}
if(peerip.equals(Constant.hostIp)){
return Constant.peerincluster_connected;
}
if(!peerIps.containsKey(peerip)){
return Constant.peerNotinCluster;
}
return peerIps.get(peerip);
}
public static void main(String[] args) {
// PropertyConfigurator.configure("log4j.properties");
System.out.println(new ClusterInfo().showClusterInfo());
System.out.println(new ClusterInfo().getPeerStatus("192.168.0.116"));
}
}

@ -0,0 +1,143 @@
package com.platform.glusterfs;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import com.platform.utils.Constant;
/**
* <>
* <>
* @author chen
* @version [201698]
* @see [/]
* @since [/]
*/
public class CopyData {
public static Logger log = Logger.getLogger(CopyData.class);
public int copyVolumeFiles(String sourceVolumeName, String destVolumeName, String fileName) {
log.info("start copy " + fileName + " from " + sourceVolumeName + " to " + destVolumeName);
int status = -1;
/**
* get mount point of volumeName
*/
String sourceFolderName = sourceVolumeName;
String destFolderName = destVolumeName;
status = copyFolderFilesAnyway(sourceFolderName, destFolderName, fileName);
return status;
}
/**
* sourceFolderNamedestFolderName
* 1sourceFolderName-2 destFolderName-3
* @param sourceFolderName
* @param destFolderName
* @return
* @see [##]
*/
public int copyFolder(String sourceFolderName, String destFolderName) {
createFolders(destFolderName);
int progress=0;
log.info("start copy " + sourceFolderName + " to " + destFolderName);
ShowData showData=new ShowData();
Map<String,String> reStrings=showData.showFolderData(destFolderName);
if(reStrings==null){
log.info("3201 "+destFolderName+" is not exists");
return -3;
}
reStrings=showData.showFolderData(sourceFolderName);
if(reStrings==null){
log.info("3202 "+sourceFolderName+" is not exists");
return -2;
}
String command = "cp -rp " + sourceFolderName+" "+destFolderName;
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
log.info("copy " + sourceFolderName + " to " + destFolderName + " running");
return 1;
}
/**
* -1 :error; -2: the filename is not exists ;-3 :destFolderName ; 1: right
* not exists
*
* @param folderName
* @param fileName
* @return
*/
public int copyFolderFiles(String sourceFolderName, String destFolderName, String fileName) {
int progress=0;
log.info("start copy " + fileName + " from " + sourceFolderName + " to " + destFolderName);
ShowData showData=new ShowData();
Map<String,String> reStrings=showData.showFolderData(destFolderName);
if(reStrings==null){
log.info("3201 "+destFolderName+" is not exists");
return -3;
}
reStrings=showData.showFolderData(sourceFolderName+"/"+fileName);
if(reStrings==null){
log.info("3202 "+sourceFolderName+"/"+fileName+" is not exists");
return -2;
}
String command = "cp -rp " + sourceFolderName + "/" + fileName+" "+destFolderName;
/*
* RunCommand runCommand = new RunCommand();
List<String> reStrings = runCommand.runCommandWait(command);
*/
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
log.info("copy " + sourceFolderName +"/" + fileName+ " to " + destFolderName + " running");
return 1;
}
/**
* @param sourceFolderName
* @param destFolderName
* @param fileName
* @return
*/
public int copyFolderFilesAnyway(String sourceFolderName, String destFolderName, String fileName) {
createFolders(destFolderName);
int result = copyFolderFiles(sourceFolderName, destFolderName, fileName);
return result;
}
public int createFolders(String folder){
log.info("create "+folder);
String splitFolder[]=folder.substring(1).split("/");
String cmd="mkdir ";
for(String one:splitFolder){
cmd+="/"+one.replaceAll(" ", "");
Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
}
return 1;
}
@Test
public void testcreateFolders() {
createFolders("/aaa/vvv/ddd/www/rrrr");
}
//@Test
public void testCopyFolderFiles() {
copyFolderFiles("/home", "/home/ubuntu", "system_data");
}
}

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

@ -0,0 +1,56 @@
package com.platform.glusterfs;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import com.platform.utils.Constant;
public class RemoveData {
public static Logger log = Logger.getLogger ( RemoveData.class);
/**
* -1 :error; 0: the filename is not exists ; 1: right
* @param folderName
* @param fileName
* @return
*/
public int deleteFolder(String folderName){
log.info("start delete "+folderName);
ShowData showData=new ShowData();
Map<String,String> reStrings=showData.showFolderData(folderName);
if(reStrings==null){
log.error("3301 "+folderName+" is not exists");
return -1;
}
String command="rm -r "+folderName;
// int status=runCommand.runCommand(command);
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
log.info("delete "+folderName+" running");
return 1;
}
@Test
public void testDeleteFolderFiles() {
PropertyConfigurator.configure("log4j.properties");
deleteFolder("/home/ubuntu");
}
}

@ -0,0 +1,67 @@
package com.platform.glusterfs;
import java.util.List;
import org.apache.log4j.Logger;
import org.hamcrest.core.Is;
import com.platform.utils.Constant;
import com.platform.utils.Support;
public class SetCluster {
public static Logger log = Logger.getLogger ( SetCluster.class);
/**
*
* 1-1ip-2 0
* @param peerip
* @return
* @see [##]
*/
public int probePeer(String peerip){
if(!Support.checkIP(peerip)){
log.error(peerip +"is illegal!" );
return -1;
}
String cmd="gluster peer probe "+peerip;
List<String> reStrings=Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
if(reStrings==null || reStrings.size()==0){
log.error("detach error! ");
return -2;
}
if(reStrings.contains(Constant.success)){
log.info("probe success!");
return 1;
}
log.info("probe failed!");
return 0;
}
/**
*
* 1-1ip-2 0
* @param peerip
* @return
* @see [##]
*/
public int detachPeer(String peerip){
if(!Support.checkIP(peerip)){
log.error(peerip +"is illegal!" );
return -1;
}
String cmd="gluster peer detach "+peerip;
List<String> reStrings=Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
if(reStrings==null || reStrings.size()==0){
log.error("detach error! ");
return -2;
}
if(reStrings.contains(Constant.success)){
log.info("detach success!");
return 1;
}
log.info("detach failed!");
return 0;
}
}

@ -0,0 +1,540 @@
/**
* @author
* volumevolumevolumebrick
*/
package com.platform.glusterfs;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import com.platform.utils.Constant;
public class SetVolume {
public static Logger log = Logger.getLogger(SetVolume.class);
/**
* volume 1 1: ;-1brickip; -2 -3
* -4:brick ; -5 :volumeName -6 -7
*
* @param volumeName
* @param count
* @param type
* @param bricks
* @param mountPoint
* @return
* @see [##]
*/
public int createVolume(String volumeName, int count, String type, List bricks, String mountPoint) {
log.info("Creat new volume");
// 判断创建volume的条件是否满足
int able = isAbleCreateVolume(volumeName, count, type, bricks, mountPoint);
if (able == 1) {
String command = null;
// 将brics从List变量中提取出来并连接成可以在命令行中使用的格式
String commandarg = concat(bricks);
/*
* verify the type
*/
if (type.equals(Constant.distributed)) {
command = "gluster volume create " + volumeName + " " + commandarg + "force";
} else if (type.equals(Constant.replica) || type.equals(Constant.stripe)) {
command = "gluster volume create " + volumeName + " " + type + " " + count + " " + commandarg + "force";
}
// 执行命令
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
// 创建成功时返回信息格式volume create: volumename success:
if (reStrings == null || reStrings.size() == 0) {
log.error("3106 " + command + " run return error");
return -7;
}
if (reStrings.get(0).contains("volume create: " + volumeName + ": " + "success:")) {
log.info("create volume " + volumeName + " successed!");
// 创建成功则启动并进行挂载
if (startVolume(volumeName) == 0) {
log.info("start volume " + volumeName + " successed!");
log.info("create "+mountPoint);
new CopyData().createFolders(mountPoint);
// 进行挂载
String command3 = "mount -t glusterfs " + Constant.hostIp + ":" + volumeName + " " + mountPoint;
List<String> reStrings3 = Constant.ganymedSSH.execCmdWaitAcquiescent(command3);
if (reStrings3.size() == 0 || reStrings.get(0).contains("GlusterFS is already mounted")) {
log.info("mount point successed!");
String addRecord = "echo \"" + volumeName + ":" + mountPoint + "\" >> " + Constant.MountRecord;
Constant.ganymedSSH.execCmdNoWaitAcquiescent(addRecord);
return 1;
}
}
} else {
log.error("3104 volume create failed with error" + reStrings.get(0));
// System.out.println(reStrings.get(0));
return -7;
}
return 1;
} else {
log.error("给出的参数不满足创建条件");
// System.out.println("给出的参数不满足创建条件");
return able;
}
}
/**
* volume 1 -1volume name-2volume
* -3-4/gfsAutoMount/mountPoint.record
* @param volumeName
* @return
* @see [##]
*/
public int deleteVolume(String volumeName) {
int status = 0;
VolumeInfo volumeInfo = new VolumeInfo();
List<String> volumeNames = volumeInfo.showAllVolumeName();
if (!volumeNames.contains(volumeName)) {
log.error("3801 " + volumeName + " is not exists !");
return -1;
}
List<String> mountPoints = volumeInfo.getVolumeMountPoint(volumeName);
String cmd = "cat " + Constant.MountRecord;
List<String> mountRecord = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
if (stopVolume(volumeName) != 0) {
return -2;
}
String command = "echo -e \"y\"| gluster volume delete " + volumeName;
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 !");
return -3;
}
log.info("delete " + volumeName + " successed!");
if (mountRecord.size() != 0 && mountPoints.get(0).contains(Constant.noSuchFile)) {
log.error("3804 : " + Constant.MountRecord + " is not exits");
return -4;
}
for (String mountPoint : mountPoints) {
command = "umount -l " + mountPoint;
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
log.info("umount " + mountPoint + " successed!");
String oneRecord=volumeName+":"+mountPoint;
if (mountRecord.contains(oneRecord)) {
mountRecord.remove(oneRecord);
}
}
String newRecords="";
for(String one:mountRecord){
newRecords+=one+"\n";
}
command="echo -ne \""+newRecords+"\" > "+Constant.MountRecord;
Constant.ganymedSSH.execCmdNoWaitAcquiescent(command);
return 1;
}
/**
* volumebrick, 1 ;
* volumebrickcount
*
* @param volumeName
* @param brickName
* @param count
* @param type
* @return
* @see [##]
*/
public int addBrickVolume(String volumeName, List<String> brickName, int count, String type) {
// 检查是否满足添加bricks的条件
int able = isAble(volumeName, count, type, brickName);
if (able != 1) {
return able;
}
String command = "";
log.info("add brick to the specified volume");
String brick = concat(brickName);
if (type.equals(Constant.distributed))
command = "gluster volume add-brick " + volumeName + " " + brick + "force";
else if (type.equals(Constant.replica))
command = "gluster volume add-brick " + volumeName + " " + "replica " + count + " " + brick + "force";
else if (type.equals(Constant.stripe))
command = "gluster volume add-brick " + volumeName + " " + "stripe " + count + " " + brick + "force";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
// 添加成功的返回信息是volume add-brick: success
if (reStrings != null && reStrings.size() > 0 && reStrings.get(0).contains("volume add-brick: success")) {
log.info("添加brick成功");
return 1;
} 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
*
* @param volumeName
* @param brickName
* @param count
* @param type
* @return
* @see [##]
*/
public int deleteBrickVolume(String volumeName, List<String> brickName, int count, String type) {
int able = isAble(volumeName, count, type, brickName);
if (able != 1) {
return able;
}
String command = null;
log.info("delete brick of the specified volume");
String brick = concat(brickName);
if (type.equals(Constant.distributed)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " " + brick + " force";
} else if (type.equals(Constant.replica)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " repli " + count + " " + brick
+ " force";
} else if (type.equals(Constant.stripe)) {
command = "echo -e \"y\" | gluster volume remove-brick " + volumeName + " stripe " + count + " " + brick
+ " force";
}
if (command == null) {
log.error("3305 remove brick failed,please check the system");
return -5;
}
log.info("即将执行删除命令");
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
// System.out.println(reStrings);
log.info("删除命令执行完毕");
// 删除成功的返回信息是“volume remove-brick: success”
if (reStrings.get(0).contains("volume remove-brick: success")) {
{
log.info("删除brick成功");
return 1;
}
} else {
log.error("3305 remove brick failed,please check the system");
return -5;
}
}
/*
* volume volume 0 -1
* volumevolume
*/
public int stopVolume(String volumeName) {
log.info("stop volume");
// 首先需要判断volume是否存在调用其他函数返回所有volume的名字
boolean volumeExist = false;
List<String> volume = new VolumeInfo().showAllVolumeName();
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");
return -1;
} else {
// volume存在则需判断volume的状态是否已经为“stop”
if (new VolumeInfo().getVolumeStatus(volumeName).equals("Stopped")) {
log.error("3502 the volume is already stoped");
System.out.println("3502 the volume is already stoped");
return 0;
} else {
String command = "echo -e \"y\"| gluster volume stop " + volumeName;
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
// 标记操作结果operation = 1 操作成功
// operation = 0 操作失败
int operation = 0;
for (String temp2 : reStrings) {
if (temp2.contains("volume stop: " + volumeName + ": " + "success")) {
operation = 1;
break;
}
System.out.println("operation: " + operation);
}
if (operation == 1) {
return 0;
} 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) {
log.info("start volume");
boolean volumeExist = false;
List<String> volume = new VolumeInfo().showAllVolumeName();
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;
int operation = 0;
// 执行命令
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(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");
System.out.println("3602 start volume failed");
return -1;
}
} else {
log.error("volume已经开启");
System.out.println("volume已经开启");
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();
for (int i = 0; i < len; i++) {
result.append(brickName.get(i));
result.append(" ");
}
return result.toString();
}
/*
* volume使 volumebrickcount
* 1: ;-1brickip; -2 -3
* -4 :brick ; -5 :volumeName -6 -7
*/
public int isAbleCreateVolume(String volumeName, int count, String type, List<String> bricks, String mountPoint) {
int status = 0;
int length = bricks.size();
if (type.equals(Constant.distributed)) {
if (count != 0) {
log.error("3101 the kind of distributed requires the arg of count to be 0");
return -2;
}
}
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");
return -3;
}
}
if (type.equals(Constant.replica)) {
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];
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;
}
if (volumeNames.contains(volumeName)) {
log.error("3106 " + volumeName + " is already exists! ");
return -5;
}
/*
Map datas = new ShowData().showFolderData(mountPoint);
if (datas != null && datas.size() > 0) {
log.error("3107 " + mountPoint + " is not exists or not empty ! ");
return -6;
}
*/
return 1;
}
/**
* volumebrickvolumevolumecountbrick
*
* @param volumeName
* @param count
* @param type
* @param bricks
* @return 1 ;-1 :volume name is not exists;-2,-3,-4 brick
*/
public int isAble(String volumeName, int count, String type, List bricks) {
List<String> volumeNames = new VolumeInfo().showAllVolumeName();
if (!volumeNames.contains(volumeName)) {
log.error("3201" + volumeName + " is not exists! ");
return -1;
}
int length = bricks.size();
if (type.equals("distribute")) {
if (count == 0)
return 1;
else {
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 {
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 {
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;
}
@Test
public void test_deleteVolume(){
System.out.println(deleteVolume("lili_test1"));
}
// @Test
public void test_createVolume(){
List<String> bricksToCreate = new ArrayList<String>();
bricksToCreate.add("192.168.0.110:/lili_test1");
bricksToCreate.add("192.168.0.116:/lili_test1");
System.out.println(createVolume("lili_test1", 0, "distributed", bricksToCreate, "/home/lili_test1_point"));
}
public static void main(String[] args) {
SetVolume setVolume = new SetVolume();
int operation = 0;
// PropertyConfigurator.configure("log4j.properties");
// TODO Auto-generated method stub
// 测试创建volume的代码
// List<String> bricksToCreate = new ArrayList<String>();
// bricksToCreate.add("192.168.0.110:/v2");
// bricksToCreate.add("192.168.0.116:/v2");
// operation = setVolume.createVolume("v2", 0, "distributed", bricksToCreate, "/home/v2_point");
// operation = setVolume.deleteVolume("v3");
//
// // 以下是测试添加brick的代码
//
// List<String> bricksToAdd = new ArrayList<String>();
// bricksToAdd.add("192.168.191.23:/v3");
// operation = setVolume.addBrickVolume("v3", bricksToAdd, 0,
// "distribute");
// System.out.println(operation);
// 以下代码是测试删除brick的代码
// List<String> bricksToAdd= new ArrayList<String>();
// bricksToAdd.add("192.168.191.23:/v3");
// operation =
// setVolume.deleteBrickVolume("v3",bricksToAdd,0,"distribute");
// System.out.println(operation);
// 以下是测试start volume的代码
// String volumeToStart = "testcreate" ;
// int startOperation = startVolume(volumeToStart);
// System.out.println(startOperation);
// 以下是测试stop volume
String volumeToStop = "v3";
// int startOperation = setVolume.stopVolume(volumeToStop);
// 以下是测试创建volume并完成挂载的代码
// List<String> bricksToCreate= new ArrayList<String>();
// bricksToCreate.add("192.168.214.135:/home/create");
// bricksToCreate.add("192.168.214.138:/home/create");
//
// int operation =
// createVolume("createAndmount",0,"distribute",bricksToCreate,"/mnt/create");
// System.out.println(operation);
}
}

@ -0,0 +1,129 @@
package com.platform.glusterfs;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import com.platform.utils.Constant;
public class ShowData {
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
* <>
* @param volumeName
* @return
* @see [##]
*/
public Map<String,String> showVolumeFiles(String volumeName){
// log.info("start show the data");
Map<String,String> data_type=new HashMap<String, String>();
/**
* get mount point of volumeName
*/
String folderName=volumeName;
data_type=showFolderData(volumeName);
return data_type;
}
/**
* get the data of folder name
* Map<String,String> is folder name and type 1 is file and others is folder
* @param FolderName
* @return
*/
public Map<String,String> showFolderData(String folderName){
// log.info(" start get "+folderName+" data");
Map<String,String> data_type=new HashMap<String, String>();
String command="ls -l "+folderName;
/*
* RunCommand runCommand=new RunCommand(); List<String>
* reStrings=runCommand.runCommandWait(command);
*/
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
if (reStrings == null) {
log.error("2101 command get result is null");
return null;
}
if(reStrings.size()==0){
log.info("2102 the folder is empty");
return data_type;
}
if(reStrings.get(0).contains("No such file or directory")){
log.info("2103 the "+folderName+" is not exists");
return null;
}
/**
* remove first line total number
*/
reStrings.remove(0);
for(Iterator it2 = reStrings.iterator();it2.hasNext();){
String line=(String)it2.next();
line=line.replaceAll(" +", " ");
String keyValue[]=line.split(" ");
if(keyValue.length<9){
log.error("2104 "+line+" length is short");
continue;
}
data_type.put(keyValue[8], keyValue[1]);
}
// log.info(" get "+folderName+" data successed");
return data_type;
}
/**
* folder
* -2-1folderfolder
* @param folderPath
* @return
* @see [##]
*/
public long getFolderSize(String folderPath) {
// log.info("get " + folderPath + " Size ");
String command = "du -k -d 0 "+folderPath+" | grep " + folderPath + "|awk \'{print $1}\'";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(command);
if(reStrings==null || reStrings.size()==0){
log.error("get " + folderPath + " Size error!");
return -2;
}
if (reStrings.get(0).contains(Constant.noSuchFile)) {
log.error(folderPath+" is not exists");
return -1;
}
long size = Long.valueOf(reStrings.get(0));
return size;
}
/**
*
* <>
* <>
* @see [##]
*/
@Test
public void testShowData(){
System.out.println(showFolderData("/home"));
}
}

@ -0,0 +1,93 @@
package com.platform.glusterfs;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.platform.utils.Constant;
public class SizeInfo {
public static Logger log = Logger.getLogger(ClusterInfo.class);
VolumeInfo volumeInfo = new VolumeInfo();
/**
* <EFBFBD>?<EFBFBD><EFBFBD>volume size
* -1<EFBFBD>? 0volume longsize
* @return
*/
public long showAllSize() {
// log.info("get AllSize ");
List<String> volumeNames = volumeInfo.showAllVolumeName();
if (volumeNames == null) {
log.error("1201 showAllVolumeName error");
return -1;
}
if (volumeNames.size() == 0) {
log.error("1202 It is not exist any volume");
return 0;
}
List<String> reStrings = null;
long size = 0L;
for (String str : volumeNames) {
String command = "df |grep " + str + "|awk \'{print $2}\'";
reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd, Constant.port,
command);
if (reStrings.isEmpty()) {
log.error("1203 The brick is unmount");
} else {
size += Long.parseLong(reStrings.get(0));
}
}
return size;
}
/**
*
* @return
* -1<EFBFBD>? 0volume longsize
*/
public long showUseSize() {
log.info("get UseSize ");
List<String> volumeNames = volumeInfo.showAllVolumeName();
List<String> reStrings = null;
long size = 0L;
if (volumeNames == null) {
log.error("1201 showAllVolumeName error");
return -1;
}
if (volumeNames.size() == 0) {
log.error("1202 It is not exist any volume");
return 0;
}
for (String str : volumeNames) {
String command = "df |grep " + str + "|awk \'{print $3}\'";
reStrings = Constant.ganymedSSH.execCmdWait(Constant.hostIp, Constant.rootUser, Constant.rootPasswd,
Constant.port, command);
if (reStrings.isEmpty()) {
log.error("1202 The brick is unmount");
} else {
size += Integer.valueOf(reStrings.get(0));
}
}
return size;
}
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
System.out.println(new SizeInfo().showAllSize());
System.out.println(new SizeInfo().showUseSize());
}
}

@ -0,0 +1,417 @@
package com.platform.glusterfs;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper;
import com.platform.utils.Constant;
import com.platform.utils.GanymedSSH;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* volume <>
*
* @author liliy
* @version [2016913]
* @see [/]
* @since [/]
*/
public class VolumeInfo {
public static Logger log = Logger.getLogger(VolumeInfo.class);
/**
* volume <>
*
* @return
* @see [##]
*/
public List<String> showAllVolumeName() {
// log.info(Constant.ganymedSSH+"get volume name");
List<String> volNames = new ArrayList<String>();
/*
* String command = "echo \"" + Constant.rootPasswd +
* "\" |sudo -S gluster volume info|grep ^Volume.Name"; RunCommand
* runCommand = new RunCommand(); List<String> reStrings =
* runCommand.runCommandWait(command);
*/
List<String> reStrings = Constant.ganymedSSH
.execCmdWaitAcquiescent(Constant.glusterVolumeInfo + "|grep ^Volume.Name");
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1401 get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1402 get result is nothing");
return null;
}
if (reStrings.get(0).contains(Constant.noVolume)) {
reStrings.clear();
return reStrings;
}
if (!(reStrings.get(0).split(":")[0].contains("Volume Name"))) {
log.error("1403 get result string wrong");
return null;
}
String nameInfo = "";
for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next();
String str[] = line.split(":");
volNames.add(str[1].replaceAll(" ", ""));
}
return volNames;
}
/**
* volumevolume
*
* @param volumeName
* @return
* @see [##]
*/
public String getVolumeType(String volumeName) {
// log.info("get volume type");
String volType = "";
List<String> reStrings = Constant.ganymedSSH
.execCmdWaitAcquiescent(Constant.glusterVolumeInfo + volumeName + "|grep ^Type");
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1501 get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1502 get result is nothing");
return null;
}
if (!(reStrings.get(0).split(":")[0].contains("Type"))) {
log.error("1503 get result string wrong");
return null;
}
// System.out.println(reStrings);
for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next();
String str[] = line.split(":");
volType = str[1];
}
volType = volType.replaceAll(" ", "");
return volType;
}
/**
* volumeName nullvolumeNameVolume volumeName does not
* existStarted,Stopped,Created
*
* @param volumeName
* @return
* @see [##]
*/
public String getVolumeStatus(String volumeName) {
// log.info("get volume status");
String volStatus = "";
String cmd = Constant.glusterVolumeInfo + " " + volumeName + " |grep ^Status";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1701 get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1702 get result is nothing");
return null;
}
if (reStrings.get(0).contains("does not exist")) {
log.error("1703 " + reStrings.get(0));
return reStrings.get(0);
}
if (!(reStrings.get(0).split(":")[0].contains("Status"))) {
log.error("1704 get result string wrong");
return null;
}
for (Iterator it = reStrings.iterator(); it.hasNext();) {
String line = (String) it.next();
String str[] = line.split(":");
volStatus = str[1].replaceAll(" ", "");
}
return volStatus;
}
/**
* volumeName
* volumeName-1-2 volumeName
* @param volumeName
* @return
* @see [##]
*/
public Long getVolumeAvailableSize(String volumeName) throws Exception{
// log.info("get volume availableSize");
Long allSize = 0L;
String cmd = Constant.df + " | grep " + volumeName + "|awk '{print $4}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1802 get result is error");
return -2L;
}
if (reStrings.size() == 0) {
log.error("1801 " + volumeName + " is not exists!");
return -1L;
}
Pattern pattern2 = Pattern.compile("^\\d+$");
Matcher matcher2 = pattern2.matcher(reStrings.get(0));
// 如果是数字
if (matcher2.find()) {
allSize = Long.parseLong(reStrings.get(0));
}
return allSize;
}
/**
* volumeName
* volumeName-1-2 volumeName
* @param volumeName
* @return
* @see [##]
*/
public Long getVolumeUseSize(String volumeName) throws Exception{
// log.info("get volume used size");
Long usedSize = 0L;
if (volumeIsExists(volumeName) == false) {
log.error("1901 " + volumeName + " is not exists!");
return -1L;
}
String cmd = "df | grep " + volumeName + "|awk '{print $3}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1901 get result is null");
return -2L;
}
if (reStrings.size() == 0) {
log.error("1902 " + volumeName + " is not exists!");
return -1L;
}
Pattern pattern2 = Pattern.compile("^\\d+$");
Matcher matcher2 = pattern2.matcher(reStrings.get(0));
// 如果是数字
if (matcher2.find()) {
usedSize = Long.parseLong(reStrings.get(0));
}
return usedSize;
}
/**
* volumeNamebricks
* birckslist ip:path,volumeNamenull
* @param volumeName
* @return
* @see [##]
*/
public List<String> getVolumeBricks(String volumeName) {
// 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);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1601 get volume bricks wrong");
return null;
}
if (reStrings.size()==0) {
log.error("1602 "+volumeName+" is not exists!");
return null;
}
return reStrings;
}
/**
* volumeName
* <>
* @param volumeName
* @return
* @see [##]
*/
public List<String> getVolumeMountPoint(String volumeName) {
// log.info("get volume MountPoint");
List<String> mountPoints = new ArrayList<>();
String cmd=Constant.df + "|grep " + volumeName + "|awk '{print $6}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWaitAcquiescent(cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("11001 get result string wrong");
return null;
}
if (reStrings.size() == 0) {
log.error("11002 " + volumeName + " is not exists or no mountpoint");
return null;
}
for (String mountPoint : reStrings) {
mountPoint = mountPoint.replaceAll(" ", "");
mountPoints.add(mountPoint);
}
return mountPoints;
}
public String getOneVolumeMountPoint(String volumeName) {
// log.info("get one volume MountPoint");
String mountPoint=null;
List<String> mountpoints = getVolumeMountPoint(volumeName);
// System.out.println(reStrings);
if (mountpoints == null || mountpoints.size() == 0) {
log.error("11001 get result string wrong");
return null;
}
mountPoint=mountpoints.get(0);
return mountPoint;
}
/**
* volumeNamebrick
* mapbricks <ip:path,data_size>
* @param volumeName
* @return
* @see [##]
*/
public Map<String, Double> getVolumebricksDataSize(String volumeName) {
List<String> bricks = getVolumeBricks(volumeName);
Map<String, Double> brick_size = new HashMap<>();
if (bricks == null) {
return null;
}
for (String brick : bricks) {
String ipAndpath[] = brick.split(":");
String ip = ipAndpath[0];
String path = ipAndpath[1];
String cmd = "du -d 0 " + path + "|awk '{print $1}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd,
Constant.port, cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1901 get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1902 "+brick+" is not exits!");
return null;
}
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(reStrings.get(0));
if (!isNum.matches()) {
log.error("1903 " + reStrings.get(0) + " is unexpect");
return null;
}
brick_size.put(brick, Double.parseDouble(reStrings.get(0)));
}
return brick_size;
}
/**
* volumeNamebrick
* mapbricks <ip:path,available_size>
* @param volumeName
* @return
* @see [##]
*/
public Map<String, Double> getVolumebricksAvailableSize(String volumeName) {
List<String> bricks = getVolumeBricks(volumeName);
Map<String, Double> brick_size = new HashMap<>();
if (bricks == null) {
return null;
}
for (String brick : bricks) {
String ipAndpath[] = brick.split(":");
String ip = ipAndpath[0];
String path = ipAndpath[1];
String cmd = "df " + path + "|awk '{print $4}'";
List<String> reStrings = Constant.ganymedSSH.execCmdWait(ip, Constant.rootUser, Constant.rootPasswd,
Constant.port, cmd);
// System.out.println(reStrings);
if (reStrings == null) {
log.error("1901 get result is null");
return null;
}
if (reStrings.size() == 0) {
log.error("1902 get result is nothing");
return null;
}
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(reStrings.get(1));
if (!isNum.matches()) {
log.error("1903 " + reStrings.get(1) + " is unexpect");
return null;
}
brick_size.put(brick, Double.parseDouble(reStrings.get(1)));
}
return brick_size;
}
/**
* volumeNametruefalse
*
* @param volumeName
* @return
* @see [##]
*/
public boolean volumeIsExists(String volumeName) {
List<String> volumes = showAllVolumeName();
if (volumes == null) {
return false;
}
if (volumes.contains(volumeName)) {
return true;
}
return false;
}
// @Test
public void test_getVolumebricksDataSize() {
System.out.println(getVolumebricksDataSize("gfs_ftp"));
}
// @Test
public void test_getVolumebricksAvailableSize() {
System.out.println(getVolumebricksAvailableSize("gfs_ftp"));
}
// @Test
public void test_getVolumeBricks() {
getVolumeBricks("gfs_ftp");
}
@Test
public void test_getVolumeStatus() {
System.out.println(getVolumeStatus("gs_fp"));
}
// @Test
public void test_getVolumeMountPoint() {
System.out.println(getVolumeMountPoint("gfs_ftp"));
System.out.println(getVolumeMountPoint("v1"));
}
}

@ -0,0 +1,119 @@
package com.platform.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.platform.entities.Brick;
import com.platform.entities.FolderNode;
import com.platform.entities.VolumeEntity;
import com.platform.glusterfs.CheckoutMD5;
import com.platform.glusterfs.ClusterInfo;
import com.platform.glusterfs.GetTreeData;
import com.platform.glusterfs.VolumeInfo;
import com.platform.utils.CacheTreeData;
public class VolumeService {
public static Logger log = Logger.getLogger(VolumeService.class);
/** Volume信息查询 */
private VolumeInfo volumeInfo = new VolumeInfo();
private ClusterInfo cluster = new ClusterInfo();
/** gfs目录树形展示 */
private GetTreeData gfsTree = new GetTreeData();
public void getVolumeMsg() {
List<FolderNode> folderlist = new ArrayList<FolderNode>();
List<VolumeEntity> volumeList = new ArrayList<VolumeEntity>();
// brick状态 map集合
Map<String, String> brickStatusMap = cluster.showClusterInfo();
// 查询 volume name
List<String> volumeNameList = volumeInfo.showAllVolumeName();
if (null != volumeNameList) {
for (String volumeName : volumeNameList) {
try {
VolumeEntity volume = new VolumeEntity();
volume.setName(volumeName);
List<String> path = volumeInfo
.getVolumeMountPoint(volumeName);
// 默认加载第一个路径
if (null != path) {
for (String one : path) {
if (!one.contains("df")) {
volume.setPath(one);
}
}
}
if (null == volume.getPath()) {
volume.setPath("");
}
volume.setAllSize(volumeInfo
.getVolumeAvailableSize(volumeName)
+ volumeInfo.getVolumeUseSize(volumeName));
// 状态Started,Stopped,Created
String status = volumeInfo.getVolumeStatus(volumeName);
if ("Started".equals(status)) {
volume.setStatus(true);
} else {
volume.setStatus(false);
}
volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName));
volume.setType(volumeInfo.getVolumeType(volumeName));
// TODO 查询brick--
// 返回 ip:path
List<String> brickStrs = volumeInfo
.getVolumeBricks(volumeName);
// brick已用大小
Map<String, Double> usedSize = volumeInfo
.getVolumebricksDataSize(volumeName);
Map<String, Double> availableSize = volumeInfo
.getVolumebricksAvailableSize(volumeName);
List<Brick> brickList = new ArrayList<Brick>();
for (String brickIpPath : brickStrs) {
Brick b = new Brick();
String ipAndpath[] = brickIpPath.split(":");
String brickip = ipAndpath[0];
String brickpath = ipAndpath[1];
// iP , path ,
b.setIp(brickip);
if (brickStatusMap == null
|| brickStatusMap.size() == 0) {
b.setStatus(false);
} else if (brickStatusMap.containsKey(brickip)) {
b.setStatus(true);
} else {
b.setStatus(false);
}
b.setPath(brickpath);
b.setAvailableSize(availableSize.get(brickIpPath));
b.setUsedSize(usedSize.get(brickIpPath));
brickList.add(b);
}
volume.setBrick(brickList);
// 默认加载第一个路径
if (null != path && path.size() > 0) {
// 装入 folder
// 查询 每个 volume 下的 folder
FolderNode foldertmp = gfsTree.getDatas(path.get(0));
folderlist.add(foldertmp);
}
volumeList.add(volume);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
// 更新folder 目录
CacheTreeData.setFolders(folderlist);
CacheTreeData.setVolumeList(volumeList);
}
}

@ -0,0 +1,39 @@
package com.platform.utils;
import java.util.List;
import java.util.Map;
import com.platform.entities.FolderNode;
import com.platform.entities.VolumeEntity;
public class CacheTreeData {
private static List<FolderNode> folders = null;
private static List<VolumeEntity> volumeList = null;
public static List<FolderNode> getFolders() {
return folders;
}
public synchronized static void setFolders(List<FolderNode> folders) {
CacheTreeData.folders = folders;
}
/**
* @return the volumeList
*/
public static List<VolumeEntity> getVolumeList() {
return volumeList;
}
/**
* @param volumeList the volumeList to set
*/
public synchronized static void setVolumeList(List<VolumeEntity> volumeList) {
CacheTreeData.volumeList = volumeList;
}
}

@ -0,0 +1,50 @@
package com.platform.utils;
import java.util.HashMap;
public class Constant {
public static String rootUser = "root";
public static String rootPasswd = "root";
// public static String hostIp = "192.168.191.23";
public static String hostIp = "";
public static int port = 22;
public static String glusterPeerStatus = "gluster peer status";
public static String glusterVolumeInfo = "gluster volume info ";
public static String df = "df -k ";
public static String peerincluster_connected = "PeerinCluster(Connected)";
public static String peerincluster_disconnected = "PeerinCluster(Disconnected)";
public static String peerNotinCluster = "PeerNotinCluster";
public static String distributed = "distributed";
public static String replica = "replica";
public static String stripe = "stripe";
public static String noVolume = "No volumes present";
public static String success = "success";
public static String failed = "failed";
public static String noSuchFile = "No such file or directory";
public static GanymedSSH ganymedSSH = null;
public static String fileGetTreeData = "WebContent\\WEB-INF\\config\\getTreedata.sh";
public static String AutoMountfile="/gfsAutoMount/AutoRun.sh";
public static String MountRecord="/gfsAutoMount/mountPoint.record";
public static String strGetTreeData = "function ergodic(){\n "
+ "for file in \\`ls \\$1\\`\n do\n if [ \"\\$file\" != \"app\" -a -d \\$1\\\"/\\\"\\$file ]\n "
+ "then\n ergodic \\$1\"/\"\\$file\n else\n local path=\\$1\"/\"\\$file\n "
+ "echo \\$path \n fi\n done\n}\n\nIFS=\\$\\'\\n\\' "
+ "#这个必须要,否则会在文件名中有空格时出错\nINIT_PATH=\".\";\nergodic \\$1\n";
/**
* volume 线
*/
public final static int moveFileMaxNum = 1;
/**
* volume 线
*/
public final static int get_volume_sleep_time = 10000;
/**
* volume 线
*/
public final static int update_dataInfo_sleep_time = 1500;
}

@ -0,0 +1,99 @@
package com.platform.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
/**
*
*
* @author wuming
*
*/
public class FileOperateHelper {
/**
*
*
* @param path
* @param message
*/
@SuppressWarnings("resource")
public static void fileWrite(String path, String message) {
if (null == path || "".equals(path)) {
return;
}
try {
path = path+".log";
File file = new File(path);
if (file.exists())
file.createNewFile();
FileOutputStream out = new FileOutputStream(file, true); // 如果追加方式用true
StringBuffer sb = new StringBuffer();
sb.append(message);
out.write(sb.toString().getBytes("utf-8"));
} catch (IOException e) {
// TODO: handle exception
}
}
/**
*
* @param path
* @return
*/
@SuppressWarnings("resource")
public static String fileReader(String path) {
StringBuffer sb = new StringBuffer();
String tempString = "";
try {
File file = new File(path);
if (!file.exists())
return "当前没有日志信息!";
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
while ((tempString = br.readLine()) != null) {
sb.append(tempString).append("\r\n");
}
} catch (Exception e) {
// Configs.CONSOLE_LOGGER.info(e.getMessage());
}
return sb.toString();
}
/**
*
* @param path
* @return
*/
@SuppressWarnings("resource")
public static String fileReaderAndendline(String path) {
StringBuffer sb = new StringBuffer();
String tempString = "";
try {
File file = new File(path);
if (!file.exists())
return "";
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((tempString = br.readLine()) != null) {
sb.append(tempString+"\n");
}
} catch (Exception e) {
// TODO: handle exception
}
return sb.toString();
}
}

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

@ -0,0 +1,31 @@
/**
* : Support.java
* : </>
* : <>
* @author liliy
* : <>
* 2016912
* <>
*/
package com.platform.utils;
import java.util.regex.Pattern;
/**
* <>
* <>
* @author liliy
* @version [2016912]
* @see [/]
* @since [/]
*/
public class Support {
public static boolean checkIP(String str) {
Pattern pattern = Pattern
.compile("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]"
+ "|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$");
return pattern.matcher(str).matches();
}
}

@ -0,0 +1,161 @@
package com.platform.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.platform.entities.Brick;
import com.platform.entities.FolderNode;
import com.platform.entities.VolumeEntity;
import com.platform.glusterfs.ClusterInfo;
import com.platform.glusterfs.GetTreeData;
import com.platform.glusterfs.VolumeInfo;
import com.platform.service.VolumeService;
public class ThreadVolume extends Thread {
public static Logger log = Logger.getLogger(ThreadVolume.class);
/**
* --
*/
private static String pointPath = "/home";
/** Volume信息查询 */
private VolumeInfo volumeInfo = new VolumeInfo();
private ClusterInfo cluster = new ClusterInfo();
/** gfs目录树形展示 */
private GetTreeData gfsTree = new GetTreeData();
public ThreadVolume() {
// TODO Auto-generated constructor stub
}
public ThreadVolume(String name) {
setName(name);
}
public ThreadVolume(String name, String path) {
if (null != path && !"".equals(path.trim())) {
ThreadVolume.pointPath = path;
}
}
@Override
public void run() {
super.run();
while (true) {
try {
getVolumeMsg();
Thread.sleep(Constant.get_volume_sleep_time);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
}
}
public static String getPointPath() {
return pointPath;
}
public static void setPointPath(String pointPath) {
ThreadVolume.pointPath = pointPath;
}
public void getVolumeMsg() {
List<FolderNode> folderlist = new ArrayList<FolderNode>();
List<VolumeEntity> volumeList = new ArrayList<VolumeEntity>();
// brick状态 map集合
Map<String, String> brickStatusMap = cluster.showClusterInfo();
// 查询 volume name
List<String> volumeNameList = volumeInfo.showAllVolumeName();
if (null != volumeNameList) {
for (String volumeName : volumeNameList) {
try {
VolumeEntity volume = new VolumeEntity();
volume.setName(volumeName);
List<String> path = volumeInfo
.getVolumeMountPoint(volumeName);
// 默认加载第一个路径
if (null != path) {
for (String one : path) {
if (!one.contains("df")) {
volume.setPath(one);
}
}
}
if (null == volume.getPath()) {
volume.setPath("");
}
volume.setAllSize(volumeInfo
.getVolumeAvailableSize(volumeName)
+ volumeInfo.getVolumeUseSize(volumeName));
// 状态Started,Stopped,Created
String status = volumeInfo.getVolumeStatus(volumeName);
if ("Started".equals(status)) {
volume.setStatus(true);
} else {
volume.setStatus(false);
}
volume.setUsedSize(volumeInfo.getVolumeUseSize(volumeName));
volume.setType(volumeInfo.getVolumeType(volumeName));
// TODO 查询brick--
// 返回 ip:path
List<String> brickStrs = volumeInfo
.getVolumeBricks(volumeName);
// brick已用大小
Map<String, Double> usedSize = volumeInfo
.getVolumebricksDataSize(volumeName);
Map<String, Double> availableSize = volumeInfo
.getVolumebricksAvailableSize(volumeName);
List<Brick> brickList = new ArrayList<Brick>();
for (String brickIpPath : brickStrs) {
Brick b = new Brick();
String ipAndpath[] = brickIpPath.split(":");
String brickip = ipAndpath[0];
String brickpath = ipAndpath[1];
// iP , path ,
b.setIp(brickip);
if (brickStatusMap == null
|| brickStatusMap.size() == 0) {
b.setStatus(false);
} else if (brickStatusMap.containsKey(brickip)) {
b.setStatus(true);
} else {
b.setStatus(false);
}
b.setPath(brickpath);
b.setAvailableSize(availableSize.get(brickIpPath));
b.setUsedSize(usedSize.get(brickIpPath));
brickList.add(b);
}
volume.setBrick(brickList);
// 默认加载第一个路径
if (null != path && path.size() > 0) {
// 装入 folder
// 查询 每个 volume 下的 folder
FolderNode foldertmp = gfsTree.getDatas(path.get(0));
folderlist.add(foldertmp);
}
volumeList.add(volume);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
// 更新folder 目录
CacheTreeData.setFolders(folderlist);
CacheTreeData.setVolumeList(volumeList);
}
}

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