
package com.platform.glusterfs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.platform.utils.Constant;

/**
 * 获取volume信息 <功能详细描述>
 * 
 * @author liliy
 * @version [版本号，2016年9月13日]
 * @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;

	}

	/**
	 * 给定参数volume的名称获得volume的类型 
	 * 
	 * @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的状态 如果出错返回null，如果volumeName不存在则返回Volume volumeName does not
	 * exist，正常返回状态Started,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;
	}

	/**
	 * 获取volumeName的bricks
	 * 返回一个bircks的list ip:path,如果volumeName不存在返回null
	 * @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>();
		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;
	}

	/**
	 * 获取volumeName的所有brick中数据占用空间的大小
	 * 返回一个map表示bricks和数据大小 <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<String, Double>();
		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;
	}

	/**
	  * 获取volumeName的所有brick中可用空间大小
	 * 返回一个map表示bricks和可用空间大小 <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<String, Double>();
		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;
	}

	/**
	 * 判断volumeName是否存在，存在返回true，不存在返回false 
	 * 
	 * @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"));
	}
}
