org.dlut.mycloudserver.service.storemanage.impl.DiskManageServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.dlut.mycloudserver.service.storemanage.impl.DiskManageServiceImpl.java

Source

/*
 * Copyright 2014 etao.com All right reserved. This software is the
 * confidential and proprietary information of etao.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with etao.com .
 */
package org.dlut.mycloudserver.service.storemanage.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.dlut.mycloudserver.client.common.ErrorEnum;
import org.dlut.mycloudserver.client.common.MyCloudResult;
import org.dlut.mycloudserver.client.common.Pagination;
import org.dlut.mycloudserver.client.common.storemanage.DiskDTO;
import org.dlut.mycloudserver.client.common.storemanage.QueryDiskCondition;
import org.dlut.mycloudserver.client.common.storemanage.StoreFormat;
import org.dlut.mycloudserver.client.service.storemanage.IDiskManageService;
import org.dlut.mycloudserver.dal.dataobject.DiskDO;
import org.dlut.mycloudserver.service.connpool.Connection;
import org.dlut.mycloudserver.service.connpool.IMutilHostConnPool;
import org.dlut.mycloudserver.service.storemanage.DiskManage;
import org.dlut.mycloudserver.service.storemanage.convent.DiskConvent;
import org.libvirt.LibvirtException;
import org.libvirt.StoragePool;
import org.libvirt.StorageVol;
import org.mycloudserver.common.constants.StoreConstants;
import org.mycloudserver.common.util.CommonUtil;
import org.mycloudserver.common.util.TemplateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * DiskManageServiceImpl.java??TODO ??
 * 
 * @author luojie 20141216 ?9:06:56
 */
@Service("diskManageService")
public class DiskManageServiceImpl implements IDiskManageService {

    private static Logger log = LoggerFactory.getLogger(DiskManageServiceImpl.class);

    @Resource
    private DiskManage diskManage;

    @Resource(name = "mutilHostConnPool")
    private IMutilHostConnPool mutilHostConnPool;

    @Override
    public MyCloudResult<DiskDTO> getDiskByUuid(String diskUuid) {
        if (StringUtils.isBlank(diskUuid)) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_NULL);
        }
        DiskDO diskDO = diskManage.getDiskByUuid(diskUuid);
        DiskDTO diskDTO = DiskConvent.conventToDiskDTO(diskDO);
        if (diskDTO == null) {
            return MyCloudResult.failedResult(ErrorEnum.DISK_NOT_EXIST);
        }
        return MyCloudResult.successResult(diskDTO);
    }

    @Override
    public MyCloudResult<String> createDisk(DiskDTO diskDTO) {
        if (diskDTO == null || StringUtils.isBlank(diskDTO.getDiskName())
                || StringUtils.isBlank(diskDTO.getUserAccount()) || diskDTO.getDiskTotalSize() == null
                || diskDTO.getDiskBusType() == null) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_IS_INVAILD);
        }
        String diskUuid = CommonUtil.createUuid();
        // libvirt??ntfs
        if (!physicalCreateDisk(diskUuid, diskDTO.getDiskTotalSize())) {
            return MyCloudResult.failedResult(ErrorEnum.DISK_PHYSICAL_CREATE_FAIL);
        }
        diskDTO.setDiskUuid(diskUuid);
        diskDTO.setDiskPath(StoreConstants.DISK_POOL_PATH + diskUuid);
        // ?qcow2
        diskDTO.setDiskFormat(StoreFormat.QCOW2);
        if (StringUtils.isBlank(diskDTO.getAttachVmUuid())) {
            diskDTO.setAttachVmUuid("");
        }
        DiskDO diskDO = DiskConvent.conventToDiskDO(diskDTO);
        // ?
        if (!diskManage.createDisk(diskDO)) {
            // ?
            if (!physicalDeleteDisk(diskUuid)) {
                log.error("?" + diskUuid + "");
            }
            return MyCloudResult.failedResult(ErrorEnum.DISK_DB_CREATE_FAIL);
        }
        return MyCloudResult.successResult(diskUuid);
    }

    /**
     * libvirt???ntfs
     * 
     * @param diskUuid
     * @param diskTotalSize
     * @return
     */
    private boolean physicalCreateDisk(String diskUuid, long diskTotalSize) {
        Connection conn = mutilHostConnPool.getLocalConn();
        if (conn == null) {
            log.error("?libvirt");
            return false;
        }
        try {
            StoragePool diskPool = conn.getStoragePoolByName(StoreConstants.DISK_POOL_NAME);
            Map<String, Object> context = new HashMap<String, Object>();
            context.put("name", diskUuid);
            context.put("uuid", diskUuid);
            context.put("diskSize", diskTotalSize);
            String diskPath = StoreConstants.DISK_POOL_PATH + diskUuid;
            context.put("newDiskPath", diskPath);
            String xmlDesc = TemplateUtil.renderTemplate(StoreConstants.DISK_VOLUME_TEMPLATE_PATH, context);
            diskPool.storageVolCreateXML(xmlDesc, 0);
            // ?ntfs?
            if (!formatDiskToNtfs(diskPath)) {
                log.error("?");
                return false;
            }
        } catch (LibvirtException e) {
            log.error("", e);
            return false;
        } finally {
            try {
                conn.close();
            } catch (LibvirtException e) {
                log.error("error message", e);
            }
        }
        return true;
    }

    /**
     * ntfs?
     * 
     * @param diskPath
     * @return
     */
    private boolean formatDiskToNtfs(String diskPath) {
        try {
            //sudo????????
            String command = "sudo  virt-format   -a   " + diskPath + "   --filesystem=ntfs  ";
            log.info("" + command);
            Process process = Runtime.getRuntime().exec(command);
            InputStream stderr = process.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            log.info("formating disk  " + diskPath + " ...");
            while ((line = br.readLine()) != null) {
                log.info("error message " + line);
            }
            int exitVal = process.waitFor();
            if (exitVal != 0) {
                return false;
            }
            log.info("success to format disk" + diskPath);
            return true;
        } catch (Exception e) {
            log.info("error message " + e.toString());
            return false;
        }
        //        Process process;
        //        try {
        //            process = Runtime.getRuntime().exec(command);//?linux
        //            process.waitFor();
        //            if (process.exitValue() == 0) {
        //                return true;
        //            }
        //        } catch (IOException e) {
        //            log.error("error message", e);
        //        } catch (InterruptedException e) {
        //            // TODO Auto-generated catch block
        //            log.error("error message", e);
        //        }
        //        return false;
    }

    private boolean physicalDeleteDisk(String diskUuid) {
        Connection conn = mutilHostConnPool.getLocalConn();
        if (conn == null) {
            log.error("?libvirt");
            return false;
        }
        try {
            StoragePool pool = conn.getStoragePoolByName(StoreConstants.DISK_POOL_NAME);
            pool.refresh(0);
            StorageVol vol = pool.storageVolLookupByName(diskUuid);
            if (vol == null) {
                log.warn("? " + diskUuid + "??");
                return false;
            }
            vol.delete(0);
            return true;
        } catch (LibvirtException e) {
            log.error("?", e);
            return false;
        } finally {
            try {
                conn.close();
            } catch (LibvirtException e) {
                log.error("error message", e);
            }
        }
    }

    @Override
    public MyCloudResult<Boolean> updateDisk(DiskDTO diskDTO) {
        if (diskDTO == null) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_NULL);
        }
        DiskDO diskDO = DiskConvent.conventToDiskDO(diskDTO);
        if (!diskManage.updateDisk(diskDO)) {
            return MyCloudResult.failedResult(ErrorEnum.DISK_UPDATE_FAIL);
        }
        return MyCloudResult.successResult(Boolean.TRUE);
    }

    @Override
    public MyCloudResult<Boolean> deleteDiskByUuid(String diskUuid) {
        if (StringUtils.isBlank(diskUuid)) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_NULL);
        }
        if (!diskManage.deleteDiskByUuid(diskUuid)) {
            log.error("" + diskUuid + "");
            return MyCloudResult.failedResult(ErrorEnum.DISK_DB_DELETE_FAIL);
        }
        if (!physicalDeleteDisk(diskUuid)) {
            log.error("?" + diskUuid + "");
            return MyCloudResult.failedResult(ErrorEnum.DISK_PHYSICAL_DELETE_FAIL);
        }
        return MyCloudResult.successResult(Boolean.TRUE);
    }

    @Override
    public MyCloudResult<Integer> countQuery(QueryDiskCondition queryDiskCondition) {
        if (queryDiskCondition == null) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_NULL);
        }
        int count = diskManage.countQuery(queryDiskCondition);
        return MyCloudResult.successResult(count);
    }

    @Override
    public MyCloudResult<Pagination<DiskDTO>> query(QueryDiskCondition queryDiskCondition) {
        if (queryDiskCondition == null) {
            return MyCloudResult.failedResult(ErrorEnum.PARAM_NULL);
        }
        int totalCount = diskManage.countQuery(queryDiskCondition);
        List<DiskDO> diskDOList = diskManage.query(queryDiskCondition);
        List<DiskDTO> diskDTOList = DiskConvent.conventToDiskDTOList(diskDOList);
        Pagination<DiskDTO> pagination = new Pagination<DiskDTO>(queryDiskCondition.getOffset(),
                queryDiskCondition.getLimit(), totalCount, diskDTOList);
        return MyCloudResult.successResult(pagination);
    }
}