com.sjc.cc.instance.service.impl.VmServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.sjc.cc.instance.service.impl.VmServiceImpl.java

Source

package com.sjc.cc.instance.service.impl;

import gua.com.Utils.XmlUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.sjc.cc.base.BusinessEnvironment;
import com.sjc.cc.base.LoginUserInfoHolder;
import com.sjc.cc.base.TccCloudPlatUitls;
import com.sjc.cc.base.entity.ParametersType;
import com.sjc.cc.base.entity.ParametersValue;
import com.sjc.cc.base.service.AbstractBusinessService;
import com.sjc.cc.base.service.ApplicationCacheService;
import com.sjc.cc.base.util.DateUtil;
import com.sjc.cc.base.vo.LoginUserInfo;
import com.sjc.cc.capacity.service.CapacityMgmtService;
import com.sjc.cc.capacity.vo.ip.IpZoneEnum;
import com.sjc.cc.entity.TccApplyedHostResource;
import com.sjc.cc.entity.TccApplyedHostinfo;
import com.sjc.cc.entity.TccCloudDatacenter;
import com.sjc.cc.entity.TccCloudplatform;
import com.sjc.cc.entity.TccClusterConfig;
import com.sjc.cc.entity.TccConfigAssApplycase;
import com.sjc.cc.entity.TccConfigCase;
import com.sjc.cc.entity.TccEmployee;
import com.sjc.cc.entity.TccExpdCapacity;
import com.sjc.cc.entity.TccInstanceInfo;
import com.sjc.cc.entity.TccIpConfigInfo;
import com.sjc.cc.entity.TccOrgan;
import com.sjc.cc.entity.TccOs;
import com.sjc.cc.entity.TccPhysiscResourceInfo;
import com.sjc.cc.entity.TccProjectAss;
import com.sjc.cc.entity.TccProjectInfo;
import com.sjc.cc.entity.TccSetMealConfig;
import com.sjc.cc.entity.TccSnapshotCfg;
import com.sjc.cc.entity.TccSnapshotHistory;
import com.sjc.cc.entity.TccSrt;
import com.sjc.cc.entity.TccSrtApplyedhostAss;
import com.sjc.cc.entity.TccSysStoreCase;
import com.sjc.cc.entity.TccTemplateCase;
import com.sjc.cc.highnetwork.service.HignNetworkService;
import com.sjc.cc.host.service.HostService;
import com.sjc.cc.hostMonitorAlarm.api.service.HostMonitorAlarmApiService;
import com.sjc.cc.hostMonitorAlarm.bean.bo.HostMonitorBean;
import com.sjc.cc.instance.service.CloneVmService;
import com.sjc.cc.instance.service.VmAssistService;
import com.sjc.cc.instance.service.VmService;
import com.sjc.cc.instance.thread.DeleteTemplateThread;
import com.sjc.cc.instance.thread.VmCallable;
import com.sjc.cc.instance.util.InstanceUtils;
import com.sjc.cc.instance.vo.VmInfo;
import com.sjc.cc.operlog.service.OperLogService;
import com.sjc.cc.pf.EnvironmentConstant;
import com.sjc.cc.pf.exception.ApplicationException;
import com.sjc.cc.resrcexpd.vo.ResrcExpdVO;
import com.sjc.cc.service.service.CloudStackService;
import com.sjc.cc.service.service.ConfigAssApplyCaseService;
import com.sjc.cc.service.service.MealService;
import com.sjc.cc.service.service.StorageService;
import com.sjc.cc.service.service.TemplateService;
import com.sjc.cc.service.service.VolumeService;
import com.sjc.cc.service.util.MapUtils;
import com.sjc.cc.snapshot.category.service.SnapshotCategoryService;
import com.sjc.cc.snapshot.service.VmSnapshotService;
import com.sjc.adaptee.cloud.cloudstack.version43.module.os.pojo.OS;
import com.sjc.adaptee.cloud.cloudstack.version43.module.os.pojo.OsVo;
import com.sjc.adaptee.cloud.cloudstack.version43.module.os.request.OsListRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.os.response.OsListResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.serviceoffering.pojo.ServiceOffering;
import com.sjc.adaptee.cloud.cloudstack.version43.module.serviceoffering.request.ListServiceOfferingsRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.serviceoffering.response.ListServiceOfferingsResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.template.request.DeleteTemplateRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.pojo.VirtualMachine;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.ChangeServiceForVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.DeployVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.DestroyVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.RebootVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.StartVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.request.StopVirtualMachineRequest;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.ChangeServiceForVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.DeployVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.DestroyVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.ListVirtualMachinesResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.RebootVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.StartVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.response.StopVirtualMachineResponse;
import com.sjc.adaptee.cloud.cloudstack.version43.pojo.AsyncJob;
import com.sjc.adaptee.cloud.vmware.version51.module.clustercomputeresource.request.ListClusterComputeResourcesRequest;
import com.sjc.adaptee.cloud.vmware.version51.module.clustercomputeresource.response.ListClusterComputeResourcesResponse;
import com.sjc.adaptee.cloud.vmware.version51.module.datacenter.request.ListDatacentersRequest;
import com.sjc.adaptee.cloud.vmware.version51.module.datacenter.response.ListDatacentersResponse;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.AddVirtualMachineDiskRequest;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.CloneVitualMachineRequest;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.GetVirtualMachineRequest;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.AddVirtualMachineDiskReponse;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.CloneVitualMachineResponse;
import com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.GetVirtualMachineResponse;
import com.sjc.target.Target;
import com.vmware.vim25.CustomizationAdapterMapping;
import com.vmware.vim25.CustomizationFixedIp;
import com.vmware.vim25.CustomizationFixedName;
import com.vmware.vim25.CustomizationGlobalIPSettings;
import com.vmware.vim25.CustomizationGuiUnattended;
import com.vmware.vim25.CustomizationIPSettings;
import com.vmware.vim25.CustomizationIdentification;
import com.vmware.vim25.CustomizationLinuxOptions;
import com.vmware.vim25.CustomizationLinuxPrep;
import com.vmware.vim25.CustomizationSpec;
import com.vmware.vim25.CustomizationSysprep;
import com.vmware.vim25.CustomizationUserData;
import com.vmware.vim25.CustomizationWinOptions;
import com.vmware.vim25.VirtualMachineCloneSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.VirtualMachineRelocateSpec;
import com.vmware.vim25.mo.ClusterComputeResource;
import com.vmware.vim25.mo.Datastore;
import com.vmware.vim25.mo.HostSystem;

public class VmServiceImpl extends AbstractBusinessService implements VmService {
    private static final long serialVersionUID = 1L;
    public static final String IN_PROCESS = "0";
    public static final String SUCCESS = "1";
    public static final String FAILURE = "2";
    public static final String STOPPED = "Stopped";
    public VolumeService volumeService;
    private OperLogService operLogService;
    private VmAssistService vmAssistService;
    private StorageService storageService;
    private CloudStackService cloudStackService;
    private HostMonitorAlarmApiService zabbixApiService;
    private HostService hostService;
    private ConfigAssApplyCaseService configAssApplyCaseService;
    private CapacityMgmtService capacityMgmtService;
    private ApplicationCacheService applicationCacheService;
    private SnapshotCategoryService snapshotCategoryService;
    private HignNetworkService hignNetworkService;
    private VmSnapshotService vmSnapshotService;
    private TemplateService templateService;
    private MealService mealService;

    // ?  ?
    public Map<String, String> getTemplateOffering(String networkId, String osType, String clusterId, String sysId,
            String zoneId, Long mealId) {
        Map<String, String> map = new HashMap<String, String>();
        StringBuffer sqlBuffer = new StringBuffer();
        if (StringUtils.isNotBlank(sysId)) {
            sqlBuffer.append("select distinct t.cs_template_offering_id,t.template_case_id from ");
            sqlBuffer.append("T_CC_VLAN_NETWORK vlan inner join T_CC_TEMPLATE_CASE ");
            sqlBuffer.append("t on vlan.zone_uuid = t.zoneid ");
            sqlBuffer.append("inner join T_CC_CLUSTER_CONFIG c on t.virtual_type=c.vtype ");
            sqlBuffer.append("inner join T_CC_OS os on t.os_version_cd=os.os_version_cd ");
            sqlBuffer.append("inner join T_CC_SET_MEAL_CONFIG config on config.os_case_id=os.os_id ");
            sqlBuffer.append("where vlan.uuid = '" + networkId + "' ");
            sqlBuffer.append("and c.id='" + clusterId + "' and t.enable_flg=1 ");
            sqlBuffer.append("and vlan.enable_flg=1  ");
            sqlBuffer.append("and t.zoneid='" + zoneId + "' ");
            sqlBuffer.append("and os.os_type='" + osType + "' ");
            sqlBuffer.append("and config.set_meal_id='" + mealId + "'");
            sqlBuffer.append("and t.template_type_cd='" + osType + "'");
        } else {
            sqlBuffer.append("select distinct t.cs_template_offering_id,t.template_case_id from ");
            sqlBuffer.append(" t_cc_template_case t ");
            sqlBuffer.append("inner join T_CC_CLUSTER_CONFIG c on t.virtual_type=c.vtype ");
            sqlBuffer.append("and c.id='" + clusterId + "' and t.enable_flg=1 and t.zoneid='" + zoneId + "'");
        }
        @SuppressWarnings("unchecked")
        List<Object[]> list = this.commonDao.findBySqlNoUpperLow(sqlBuffer.toString(), null, -1, -1);
        if (!list.isEmpty()) {
            Object[] obj = list.get(0);
            map.put("templateUuid", obj[0].toString());
            map.put("templateId", obj[1].toString());
        }
        return map;
    }

    // cloudstack
    public synchronized Map<String, String> createCS(Long assId, String networkUuid, String clusterId,
            TccProjectInfo tccProjectInfo, String vmName) throws Exception, Throwable {
        boolean attachFlag = false;
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        Map<String, String> errorMap = new HashMap<String, String>();
        String errorMsg = "";
        TccConfigAssApplycase ass = configAssApplyCaseService.getConfigAssApplyCase(assId);
        if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
            ass.setSanStorageSize(tccProjectInfo.getSanStorageSize());
        } else {
            ass.setSanStorageSize("0");
        }

        if (StringUtils.isNotBlank(tccProjectInfo.getNasStorageSize())) {
            ass.setNasStorageSize(tccProjectInfo.getNasStorageSize());
        } else {
            ass.setNasStorageSize("0");
        }

        DeployVirtualMachineRequest deployVmReq = new DeployVirtualMachineRequest();
        deployVmReq
                .setServiceOfferingId(ass.getTccSetMealConfig().getTccConfigCase().getServiceOfferingId().trim());
        // 1????(??uuid?enable_flg0)?Os??????DB
        // 2?????
        TccSetMealConfig meal = ass.getTccSetMealConfig();
        TccTemplateCase template = meal.getTccTemplateCase();
        if (template == null || StringUtils.isBlank(template.getCsTemplateOfferingId())
                || BusinessEnvironment.DISABLE_FLG.equals(template.getEnableFlg())) {
            Map<String, String> resultMap = this.getTemplateOffering(networkUuid,
                    ass.getTccSetMealConfig().getTccOs().getOsType(), clusterId,
                    tccProjectInfo.getInstallVmProjectId(), tccProjectInfo.getZoneId(),
                    ass.getTccSetMealConfig().getSetMealId());
            if (resultMap == null || resultMap.get("templateUuid") == null || resultMap.get("templateId") == null) {
                errorMsg = "??cloudstack?";
                logger.error(errorMsg);
                errorMap.put("FAILURE", errorMsg);
                String[] parameters = { networkUuid, ass.getTccSetMealConfig().getTccOs().getOsType(), clusterId,
                        tccProjectInfo.getInstallVmProjectId(), tccProjectInfo.getZoneId(),
                        ass.getTccSetMealConfig().getSetMealId() + "" };
                // ?
                // exceptionOperationService.saveException(new
                // Exception(errorMsg),
                // ExceptionType.BUSINESSException + "",
                // VmServiceImpl.class.toString()+"",
                // "getTemplateOffering", parameters,
                // BusinessEnvironment.OPER_TYPE_ADD_VM, "cloudstack");
                return errorMap;
            }
            deployVmReq.setTemplateId(resultMap.get("templateUuid"));
            ass.setTemplateId(resultMap.get("templateId"));
            // ???
            template = templateService.getTemplateCase(Long.valueOf(resultMap.get("templateId")));
            meal.setTccTemplateCase(template);
            mealService.updateMeal(meal);
        } else {
            deployVmReq.setTemplateId(template.getCsTemplateOfferingId());
            ass.setTemplateId(String.valueOf(template.getTemplateCaseId()));
        }
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> vlanList = (List<Map<String, Object>>) this.commonDao.querySqlByJdbcTpl(
                    "select a.ID as vlanId  from  T_CC_VLAN_NETWORK a "
                            + "join T_CC_PROJECT_INFO b on a.SYS_ID=b.PROJECT_ID where  a.SYS_ID="
                            + tccProjectInfo.getProjectId() + " and a.UUID='" + networkUuid + "' ",
                    new ArrayList<Object>(), null);
            if (vlanList != null && vlanList.size() > 0) {
                Map<String, Object> rs = (Map<String, Object>) vlanList.get(0);
                ass.setVlanId(Long.valueOf(String.valueOf(rs.get("vlanId"))));
            }
        } catch (Exception ex) {
            logger.error("VLANID" + ex);
        }
        /*
         * ???ID ???? ??
         */
        TccPhysiscResourceInfo tccPhysiscResourceInfo = null;
        List<TccPhysiscResourceInfo> listPhysiscResourceInfo = this.commonDao
                .find(" from TccPhysiscResourceInfo where enableFlg=1 AND CLUSTERID = " + clusterId);
        if (null != listPhysiscResourceInfo && !listPhysiscResourceInfo.isEmpty()) {
            for (TccPhysiscResourceInfo TccPhysiscResourceInfoT : listPhysiscResourceInfo) {
                if (null == tccPhysiscResourceInfo) {
                    tccPhysiscResourceInfo = TccPhysiscResourceInfoT;
                } else {
                    try {
                        if (TccPhysiscResourceInfoT.getCpuCoreRemainCount() > tccPhysiscResourceInfo
                                .getCpuCoreRemainCount()) {
                            tccPhysiscResourceInfo = TccPhysiscResourceInfoT;
                        }
                    } catch (Exception e) {
                        logger.warn("host:" + TccPhysiscResourceInfoT.getPhysicsName());
                    }
                }
            }
        }
        if (null != tccPhysiscResourceInfo) {
            deployVmReq.setHostId(tccPhysiscResourceInfo.getUuid());
        }

        TccClusterConfig clusterConfig = vmAssistService.getClusterConfig(Long.parseLong(clusterId));
        ass.setVrSubType(clusterConfig.getVtype());
        TccCloudDatacenter dc = (TccCloudDatacenter) commonDao.get(TccCloudDatacenter.class,
                Long.valueOf(clusterConfig.getZoneId().trim()));
        deployVmReq.setZoneId(dc.getUuid());
        // ?
        ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTING);
        configAssApplyCaseService.updateConfigAssApplyCase(ass);
        ass = configAssApplyCaseService.getConfigAssApplyCase(ass.getAssId());
        // //IP?
        if (vmName != null && !vmName.equals("")) {
            deployVmReq.setName(vmName.replaceAll(" ", ""));
            boolean flag = vmAssistService.checkDuplVmName(deployVmReq.getName());
            if (flag == false) {
                errorMsg = "????";
                logger.error(errorMsg);
                errorMap.put("FAILURE", errorMsg);

                String[] parameters = { deployVmReq.getName() };
                // ??
                // exceptionOperationService.saveException(new
                // Exception(errorMsg),
                // ExceptionType.BUSINESSException + "", "VmServiceImpl",
                // "vmAssistService.checkDuplVmName", parameters,
                // BusinessEnvironment.OPER_TYPE_ADD_VM, "cloudstack");
                return errorMap;
            }
        }
        // 
        if (null == dc || null == dc.getNetworkType() || !dc.getNetworkType().equals("Basic")) {
            deployVmReq.setNetworkIds(networkUuid.trim());
        }
        //  cloud-dev
        // CloudStack??
        AsyncJob asyncjobRespId = null;
        try {
            deployVmReq.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
            deployVmReq = (DeployVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(deployVmReq);
            DeployVirtualMachineResponse deployResponse = (DeployVirtualMachineResponse) TccCloudPlatUitls
                    .getAdapte().execute(deployVmReq);
            asyncjobRespId = deployResponse.getDeployVirtualMachineResponse();
        } catch (Exception e) {
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                    loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_ADD_VM, ass, 2);
            errorMsg = "IO???";
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            String[] parameters = { "serviceOfferingId=" + deployVmReq.getServiceOfferingId(),
                    "templateId=" + deployVmReq.getTemplateId(), "networkId=" + deployVmReq.getNetworkIds(),
                    "vmName=" + deployVmReq.getName(), "zoneId=" + deployVmReq.getZoneId() };
            // ??
            // exceptionOperationService.saveException(e,
            // ExceptionType.RESOURCEException + "", "VmServiceImpl",
            // "(DeployVirtualMachineResponse)
            // TccCloudPlatUitls.getAdapte().execute(deployVmReq)", parameters,
            // BusinessEnvironment.OPER_TYPE_ADD_VM,
            // "cloudstack:"+deployVmReq.getHost());
            return errorMap;
        }

        String jobStatus = asynQueryVmStatus(asyncjobRespId.getJobId(),
                this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
        // ?
        if (SUCCESS.equals(jobStatus)) {
            VirtualMachine vmVo = cloudStackService.getVmInfoCS(asyncjobRespId.getJobId(),
                    this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());

            String serviceOfferingId = vmVo.getServiceOfferingId();
            // ?
            String storageType = "";
            ListServiceOfferingsRequest cmd1 = new ListServiceOfferingsRequest();
            cmd1.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
            cmd1.setId(serviceOfferingId);
            cmd1.setIsSystem("false");
            cmd1 = (ListServiceOfferingsRequest) TccCloudPlatUitls.setRequestParam(cmd1);
            ListServiceOfferingsResponse findserviceOfferResponse = (ListServiceOfferingsResponse) TccCloudPlatUitls
                    .getAdapte().execute(cmd1);
            List<ServiceOffering> findserviceofferingVoArr = findserviceOfferResponse
                    .getListServiceOfferingsResponse().getServiceOffering();
            if (findserviceofferingVoArr != null && findserviceofferingVoArr.size() > 0) {
                for (ServiceOffering vo : findserviceofferingVoArr) {
                    storageType = vo.getStorageType();
                }
            } else {
                String[] parameters = { "serviceId=" + serviceOfferingId,
                        "cloudstack?" + this.queryPlatformByClusterId(clusterId).getAdminurl() };
                // ??
                // exceptionOperationService.saveException(new
                // Exception(""+vmName+""+vmVo.getServiceOfferingName()+"?"),
                // ExceptionType.RESOURCEException + "", "VmServiceImpl",
                // "(ListServiceOfferingsResponse)
                // TccCloudPlatUitls.getAdapte().execute(cmd1)", parameters,
                // BusinessEnvironment.OPER_TYPE_ADD_VM,
                // "cloudstack:"+deployVmReq.getHost());
            }

            String ip = vmVo.getNic().get(0).getIpAddress();
            StringBuffer updateSql = new StringBuffer();
            updateSql.append("UPDATE T_CC_IP_CONFIG_INFO f SET f.USED_FLAG='1',REMARK='" + vmVo.getName()
                    + "'  WHERE f.IP_ADDRESS ='" + ip + "'");
            commonDao.updateByNativeSql(updateSql.toString());
            String volumeOfferingId = "";// ?UUID
            // SAN??
            if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
                try {
                    if (Integer.valueOf(tccProjectInfo.getSanStorageSize()) > 0) {
                        // ????
                        TccSysStoreCase ssc = new TccSysStoreCase();
                        ssc.setStoreCaseName(tccProjectInfo.getSanStorageSize() + "GB");
                        ssc.setStoreSize(Long.valueOf(tccProjectInfo.getSanStorageSize()));
                        ssc.setMomo(ass.getTccSetMealConfig().getTccPluginStoreCase().getMomo());
                        ssc = storageService.mergeSysStoreCase(ssc,
                                this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString(),
                                storageType.trim());
                        volumeOfferingId = volumeService.createVolumeCS(vmName + "D001",
                                tccProjectInfo.getSanStorageSize(), ssc.getDiskOfferingId(),
                                vmVo.getZoneId().trim());
                        attachFlag = volumeService.attachVolumeCS(volumeOfferingId, vmVo.getId(),
                                this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
                        ass.setAttachFlag(attachFlag);
                        if (attachFlag) {
                            logService.saveOperLog("?", vmName + "?" + vmName + "D001"
                                    + BusinessEnvironment.OPER_RESULT_SUCCESS, ass, 2);
                        } else {
                            logService.saveOperLog("", vmName + "?" + vmName + "D001"
                                    + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
                        }
                    }
                } catch (Exception e) {
                    // ?
                    errorMsg = "?IO???";
                    logger.warn(errorMsg);
                    DestroyVirtualMachineRequest request = new DestroyVirtualMachineRequest();
                    request.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
                    request.setId(vmVo.getId());
                    request = (DestroyVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(request);
                    DestroyVirtualMachineResponse response = null;
                    // ????
                    try {
                        response = (DestroyVirtualMachineResponse) TccCloudPlatUitls.getAdapte().execute(request);
                    } catch (Exception ex) {
                        String[] parameters = { "plateId=" + request.getCloud(), "vmUuid=" + vmVo.getId() };
                        // exceptionOperationService.saveException(e,
                        // ExceptionType.RESOURCEException + "",
                        // "VolumeServiceImpl",
                        // "attachVolumeCS", parameters,
                        // BusinessEnvironment.OPER_TYPE_DESTROY_VM,
                        // "cloudstack:"+request.getHost());
                    }
                    String jobStatus_tmp = asynQueryVmStatus(response.getDestroyVirtualMachineResponse().getJobId(),
                            this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
                    if (SUCCESS.equals(jobStatus_tmp)) {
                        e.printStackTrace();
                        errorMap.put("FAILURE", errorMsg);
                        return errorMap;
                    }
                }
            }
            // ?
            String osTypeName = "";
            String osVersionCode = ass.getTccSetMealConfig().getTccSetMealSelfConfig().getOsVersionCd();
            DetachedCriteria criteria = DetachedCriteria.forClass(TccOs.class);
            criteria.add(Restrictions.eq("osVersionCd", osVersionCode));
            @SuppressWarnings("unchecked")
            List<TccOs> tccOsList = commonDao.findByCriteria(criteria);

            if (tccOsList == null || tccOsList.size() == 0 || tccOsList.get(0).getOsName() == null) {
                // ??cloudstack?
                OsListRequest osRequest = new OsListRequest();
                osRequest.setCloud(Target.CLOUDSTACK);
                osRequest = (OsListRequest) TccCloudPlatUitls.setRequestParam(osRequest);
                OsListResponse osResponse = (OsListResponse) TccCloudPlatUitls.getAdapte().execute(osRequest);
                OsVo osVo = osResponse.getListostypesresponse();
                String osDescription = "";
                if (osVo != null && osVo.getOstype().length > 0) {
                    OS[] osArray = osVo.getOstype();
                    for (OS osType : osArray) {
                        if (osType.equals(vmVo.getGuestosId())) {
                            osDescription = osType.getDescription();
                        }
                    }
                }
                if (osDescription.contains("windows") || osDescription.contains("windows")) {
                    osTypeName = "windows";
                } else {
                    osTypeName = "linux";
                }
            } else {
                // ???
                osTypeName = tccOsList.get(0).getOneLevelOs();
            }

            // ?
            ass.setOsType(osTypeName);

            // IP
            XmlUtils utils = new XmlUtils();
            List<String> ipList = new ArrayList<String>();
            ipList.add(vmVo.getNic().get(0).getIpAddress().trim());
            utils.addConnection("", ipList);

            // ?????
            TccSrt srt = vmAssistService.getSrt(ass.getTccSrt().getSrtId());
            TccApplyedHostResource applyedHostResource = vmAssistService.mergeApplyedHostResource(vmVo, ass, "",
                    volumeOfferingId);

            /** add host to monitor by Destiny : begin **/
            String host = String.valueOf(applyedHostResource.getApplyResourceId());
            String visibleName = vmName;

            if (!zabbixApiService.isAddHostToMonitorByHostName(host)) {
                HostMonitorBean hostinfo = new HostMonitorBean();
                hostinfo.setHostName(host);
                hostinfo.setVisibleName(visibleName);
                hostinfo.setIp(ip);
                hostinfo.setOsName(osTypeName);
                applyedHostResource.setMonitorFlg(zabbixApiService.addHostToMonitor(hostinfo) ? "1" : "0");
            } else {
                logger.info("[" + visibleName + "]zabbix");
                applyedHostResource.setMonitorFlg("1");
            }

            commonDao.update(applyedHostResource);
            /** add host to monitor by Destiny : end **/

            vmAssistService.saveSrtApplyedhostAss(applyedHostResource, srt);

            applyedHostResource.setHardwareTypeCd("186");

            applyedHostResource.setClusterId(clusterId);
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTSUCC);
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            // ?? CPU?MEM?
            capacityMgmtService.takingCpuRam(applyedHostResource.getTccPhysiscResourceInfo(),
                    ass.getTccSetMealConfig().getTccConfigCase().getCpuCoreCount(),
                    ass.getTccSetMealConfig().getTccConfigCase().getRamSize());
            // ??
            TccProjectInfo projectInfo = tccProjectInfo;
            vmAssistService.saveProjectAss(applyedHostResource, projectInfo);
            String displayName = deployVmReq.getName();
            TccApplyedHostResource ahr = vmAssistService
                    .getApplyedHostResource(applyedHostResource.getApplyResourceId());
            ahr.setHostNane(displayName);
            vmAssistService.updateApplyedHostResource(ahr);
            // ???snapshotcategory?
            TccSnapshotCfg snapshotCfg = new TccSnapshotCfg();
            snapshotCfg.setCrtDttm(new Date());
            Set<TccApplyedHostinfo> tccApplyedHostinfos = ass.getTccApplyedHostinfos();
            for (TccApplyedHostinfo temp : tccApplyedHostinfos) {
                snapshotCfg.setCrtUserId(temp.getCrtUserId() + "");
                break;
            }
            snapshotCfg.setCrtUserId(String.valueOf(srt.getCrtUserId()));
            snapshotCfg.setShotMaxNum(0L);
            snapshotCfg.setHostId(applyedHostResource.getApplyResourceId());
            snapshotCfg.setVmName(displayName);
            snapshotCfg.setEnableFlg("1");
            snapshotCategoryService.AddSnapshotCategory(snapshotCfg);

            logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + "" + vmName
                    + BusinessEnvironment.OPER_RESULT_SUCCESS, ass, 2);
            logService.saveOperLog(
                    "" + loginUserInfo.getEmpName() + "" + vmName
                            + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    BusinessEnvironment.OPER_TYPE_ADD_VM, ass, 2);
            errorMap.put("SUCCESS", applyedHostResource.getApplyResourceId() + "");
            return errorMap;
        } else {// 

            logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "" + vmName
                    + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
            logService.saveOperLog(
                    "" + loginUserInfo.getEmpName() + "" + vmName
                            + BusinessEnvironment.OPER_RESULT_FAILURE,
                    BusinessEnvironment.OPER_TYPE_ADD_VM, ass, 2);
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            errorMsg = "?,??!";
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            return errorMap;
        }
    }

    public List<TccCloudplatform> getAllCloudplatform() {
        List<TccCloudplatform> listCloudPlatform = this.commonDao
                .find(" from TccCloudplatform where enableFlg=1   ");
        if (null != listCloudPlatform && listCloudPlatform.size() > 0) {
            return listCloudPlatform;
        }
        return null;
    }

    /**
     * ?vCenter???
     * 
     * @param osId
     * @return
     */
    public boolean validateCreateAndCloneByVc(String osId) {
        if (StringUtils.isBlank(osId)) {
            return false;
        }
        // ?vCenter??
        ParametersType paramType = vmAssistService.getParametersType(680L);
        ParametersValue paramVal = new ParametersValue();
        paramVal.setParametersType(paramType);
        List<ParametersValue> paramValueList = vmAssistService.getParametersValueList(paramVal);
        for (ParametersValue val : paramValueList) {
            logger.info("AttrValueNameCn:" + val.getAttrValueNameCn() + " osId:" + osId);
            if (val.getAttrValueNameCn().equals(osId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * vcenter??
     * 
     */
    private Map<String, Object> getVCTemplate(String osName, String enviromentEncode, String datacenterName,
            String cloudPlatformId, String clusterId) {
        Map<String, Object> map = null;
        // 
        /*if (osName.equalsIgnoreCase("Red Hat Enterprise Linux 6.0 (32-bit)")) {
           osName = "Red Hat Enterprise Linux 6 (32-bit)";
        } else if (osName
        .equalsIgnoreCase("Red Hat Enterprise Linux 6.0 (64-bit)")) {
           osName = "Red Hat Enterprise Linux 6 (64-bit)";
        }*/
        StringBuffer sql = new StringBuffer();
        // ?T_CC_TEMPLATE_CASE
        // ?1??OS_VERSION_CDT_CC_OSOS_VERSION_CD?
        sql.append(
                " SELECT DISTINCT C.CS_TEMPLATE_OFFERING_ID, C.VC_TEMPLATE_OFFERING_ID, C.TEMPLATE_CASE_ID, C.VIRTUAL_TYPE FROM T_CC_TEMPLATE_CASE C INNER JOIN T_CC_OS O ON O.OS_VERSION_CD = C.OS_VERSION_CD ");
        sql.append(" AND O.OS_NAME = '" + osName + "' ");
        // ?2??ENABLE_FLG1?USEAGE_FLAGE?
        sql.append(
                " INNER JOIN T_CC_SET_MEAL_CONFIG T ON T.OS_CASE_ID = O.OS_ID AND T.ENABLE_FLG = '1' AND T.USEAGE_FLAGE = '"
                        + enviromentEncode.trim() + "' ");
        // ?3??ZONEIDT_CC_CLOUD_DATACENTERZONE_NAME?T_CC_CLOUD_DATACENTERCLOUDPLATFORM_ID?
        sql.append(" INNER JOIN T_CC_CLOUD_DATACENTER D ON D.ZONE_ID = C.DATACENTER_ID AND D.ZONE_NAME = '"
                + datacenterName + "' AND D.CLOUDPLATFORM_ID = " + cloudPlatformId);
        //  ?
        sql.append(" INNER JOIN T_CC_CLUSTER_CONFIG CC ON CC.ZONEID = D.ZONE_ID AND CC.ID = " + clusterId);
        // ?4ENABLE_FLG1?
        sql.append(" WHERE C.ENABLE_FLG = '1' AND CC.VTYPE = C.VIRTUAL_TYPE ");
        @SuppressWarnings("unchecked")
        List<Object[]> resultList = this.commonDao.findBySqlNoUpperLow(sql.toString(), null, -1, -1);
        if (!resultList.isEmpty()) {
            // ??????
            map = new HashMap<String, Object>();
            Object obj[] = resultList.get(0);
            map.put("templateId", obj[0]);
            map.put("templateName", obj[1]);
            map.put("id", obj[2]);
            map.put("virtualType", obj[3]);
        }
        return map;
    }

    public Map<String, String> createVC(Long assId, IpZoneEnum ipZone, String clusterId,
            TccProjectInfo tccProjectInfo, String vmName, String osName, String networkname, String datastoreName)
            throws Exception, Throwable {
        Map<String, String> errorMap = new HashMap<String, String>();
        String errorMsg = "";

        // ??IP?
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT f.IP_ADDRESS, f.MEMO FROM T_CC_IP_CONFIG_INFO f WHERE f.name='" + networkname
                + "'  AND  f.used_flag=0 ORDER BY  ip_config_id asc");
        List<Object[]> ipList = commonDao.findBySqlNoUpperLow(sql.toString(), null, -1, -1);
        // ip?
        if (ipList.size() == 0) {
            errorMsg = "?IP?!";
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            errorMap.put("SUCCESS", "false");
            errorMap.put("msg", errorMsg);
            return errorMap;
        }

        TccConfigAssApplycase ass = configAssApplyCaseService.getConfigAssApplyCase(assId);
        // ?
        TccConfigCase configCase = ass.getTccSetMealConfig().getTccConfigCase();
        // ???ID
        TccClusterConfig clusterConfig = vmAssistService.getClusterConfig(Long.parseLong(clusterId));
        ass.setVrSubType(clusterConfig.getVtype());
        // ??
        ass.setMiddlewareName(applicationCacheService.getMapValue("273", ass.getMiddlewareCd()));
        if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
            ass.setSanStorageSize(tccProjectInfo.getSanStorageSize());
        } else {
            ass.setSanStorageSize("0");
        }
        if (StringUtils.isNotBlank(tccProjectInfo.getNasStorageSize())) {
            ass.setNasStorageSize(tccProjectInfo.getNasStorageSize());
        } else {
            ass.setNasStorageSize("0");
        }
        CloneVitualMachineRequest clonevmRequest = new CloneVitualMachineRequest();
        clonevmRequest.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
        clonevmRequest.setName(vmName);

        // ***** by zhachaoy i*****
        // ?
        VirtualMachineCloneSpec virtualMachineCloneSpec = new VirtualMachineCloneSpec();

        // ???
        VirtualMachineRelocateSpec virtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
        // ?
        // 
        ListClusterComputeResourcesRequest ListClusterComputeResourcesRequestT = new ListClusterComputeResourcesRequest();
        ListClusterComputeResourcesRequestT
                .setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
        ListClusterComputeResourcesRequestT.setName(clusterConfig.getClusterName());
        ListClusterComputeResourcesRequestT = (ListClusterComputeResourcesRequest) TccCloudPlatUitls
                .setRequestParam(ListClusterComputeResourcesRequestT);
        ListClusterComputeResourcesResponse ListClusterComputeResourcesResponseT = (ListClusterComputeResourcesResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(ListClusterComputeResourcesRequestT);
        ClusterComputeResource ClusterComputeResourceT = ListClusterComputeResourcesResponseT
                .getListClusterComputeResourcesResponse().getClusterComputeResource().get(0);
        try {
            // 
            virtualMachineRelocateSpec.setPool(ClusterComputeResourceT.getResourcePool().getMOR());
        } catch (Exception e) {
            logger.error("?" + clusterConfig.getClusterName());
            errorMsg = "?" + clusterConfig.getClusterName();
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            errorMap.put("SUCCESS", "false");
            errorMap.put("msg", errorMsg);
            return errorMap;
        }
        // 
        Datastore DatastoreT = null;
        for (Datastore datasotre : ClusterComputeResourceT.getDatastores()) {
            if (datasotre.getName().equals(datastoreName)) {
                DatastoreT = datasotre;
            }
        }
        // ??
        HostSystem HostSystemT = null;
        for (HostSystem hostSystem : ClusterComputeResourceT.getHosts()) {
            if (null == HostSystemT) {
                HostSystemT = hostSystem;
            } else {
                try {
                    if (hostSystem.getVms().length < HostSystemT.getVms().length) {
                        HostSystemT = hostSystem;
                    }
                } catch (Exception e) {
                    logger.warn("host:" + hostSystem.getName());
                }
            }
        }
        try {
            // ?
            virtualMachineRelocateSpec.setHost(HostSystemT.getMOR());// ,??
        } catch (Exception e) {
            logger.error("" + clusterConfig.getClusterName() + "??");
            errorMsg = "" + clusterConfig.getClusterName() + "??";
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            errorMap.put("SUCCESS", "false");
            errorMap.put("msg", errorMsg);
            return errorMap;
        }
        try {
            // 
            virtualMachineRelocateSpec.setDatastore(DatastoreT.getMOR());// ,
        } catch (Exception e) {
            logger.error("" + clusterConfig.getClusterName() + "?"
                    + datastoreName);
            errorMsg = "" + clusterConfig.getClusterName() + "?"
                    + datastoreName;
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            errorMap.put("SUCCESS", "false");
            errorMap.put("msg", errorMsg);
            return errorMap;
        }
        virtualMachineCloneSpec.setLocation(virtualMachineRelocateSpec);

        // ???
        VirtualMachineConfigSpec virtualMachineConfigSpec = new VirtualMachineConfigSpec();
        // memory
        virtualMachineConfigSpec.setMemoryMB(configCase.getRamSize() * 1024);
        // cpu

        virtualMachineConfigSpec.setNumCPUs(configCase.getCpuCoreCount().intValue());
        virtualMachineCloneSpec.setConfig(virtualMachineConfigSpec);

        // ???
        virtualMachineCloneSpec.setPowerOn(true);
        virtualMachineCloneSpec.setTemplate(false);

        // 1???
        // 2?????
        TccSetMealConfig meal = ass.getTccSetMealConfig();
        TccTemplateCase template = meal.getTccTemplateCase();
        Map<String, Object> map = null;
        if (template == null || StringUtils.isBlank(template.getCsTemplateOfferingId())
                || BusinessEnvironment.DISABLE_FLG.equals(template.getEnableFlg())) {
            map = this.getVCTemplate(osName, tccProjectInfo.getEvnCode(), clusterConfig.getDcname(),
                    this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "", clusterId);
            // ??
            if (map == null || map.isEmpty() || map.get("id") == null) {
                errorMsg = "vCenter" + osName + "?";
                logger.error(errorMsg);
                errorMap.put("FAILURE", errorMsg);
                return errorMap;
            }
            // ??
            template = (TccTemplateCase) this.commonDao.get(TccTemplateCase.class,
                    Long.valueOf(String.valueOf(map.get("id"))));
            meal.setTccTemplateCase(template);
            mealService.updateMeal(meal);
        } else {
            String name = template.getUsername();
            String pass = template.getPasswd();
            map = new HashMap<String, Object>();
            map.put("templateName", template.getTemplateName());
            map.put("id", template.getTemplateCaseId());
            map.put("templateId", template.getCsTemplateOfferingId());

        }

        if (null != map) {
            String str = ipList.get(0)[1].toString();
            String[] cidr = str.split(",");
            if (null != map.get("templateId")
                    && map.get("templateId").toString().toUpperCase().indexOf("WINDOWS") >= 0) {
                // Windows?
                CustomizationSpec cspec = new CustomizationSpec();
                CustomizationGlobalIPSettings gIP = new CustomizationGlobalIPSettings();
                cspec.setGlobalIPSettings(gIP);
                // This is windows so choose the sysprep
                CustomizationSysprep sprep = new CustomizationSysprep();
                CustomizationGuiUnattended guiUnattended = new CustomizationGuiUnattended();
                guiUnattended.setAutoLogon(false); // do not autoLogin on reboot for
                guiUnattended.setAutoLogonCount(0); // do not autologin on reboot.
                guiUnattended.setTimeZone(4); // set to Eastern time.
                //            CustomizationPassword pass = new CustomizationPassword();
                //              pass.setPlainText(true);
                //              pass.setValue("!QAZ2wsx");
                //              guiUnattended.setPassword(pass);  // reset Administrator account Password.
                sprep.setGuiUnattended(guiUnattended);
                // add VM to WORKGROUP
                CustomizationIdentification identification = new CustomizationIdentification();
                identification.setJoinWorkgroup("WORKGROUP");
                sprep.setIdentification(identification);
                //             String productId = queryProductId("OS"); // only needed for windows os's
                //             if("Windows2003"))
                //             {
                //             CustomizationLicenseFilePrintData licenseFilePrintData = new CustomizationLicenseFilePrintData();
                //             licenseFilePrintData.setAutoMode(CustomizationLicenseDataMode.perServer);
                //             licenseFilePrintData.setAutoUsers(5);
                //             sprep.setLicenseFilePrintData(licenseFilePrintData);
                //             }

                // setup UserData
                CustomizationUserData userData = new CustomizationUserData();
                CustomizationFixedName n = new CustomizationFixedName();
                n.setName(vmName);//hostname
                userData.setComputerName(n);
                userData.setFullName("Some Name"); // This may change in the future
                userData.setOrgName("Some Organization");
                userData.setProductId(""); // Product Serial (needed for
                // Windows 2003 and 2008)
                sprep.setUserData(userData);
                cspec.setIdentity(sprep);
                // NicSettingMap part
                CustomizationAdapterMapping adaptorMap = new CustomizationAdapterMapping();
                CustomizationIPSettings adapter = new CustomizationIPSettings();
                CustomizationFixedIp fixedIp = new CustomizationFixedIp();
                adapter.setDnsServerList(new String[] { cidr[2] });
                adapter.setGateway(new String[] { cidr[1] });
                fixedIp.setIpAddress(ipList.get(0)[0].toString());
                adapter.setIp(fixedIp);
                adapter.setSubnetMask(cidr[0]);
                adaptorMap.setAdapter(adapter);
                CustomizationAdapterMapping[] nicSettingMap = new CustomizationAdapterMapping[] { adaptorMap };
                cspec.setNicSettingMap(nicSettingMap);
                CustomizationWinOptions options = new CustomizationWinOptions();
                options.setChangeSID(true);
                options.setDeleteAccounts(false);
                cspec.setOptions(options);
                //            cspec.setEncryptionKey(manager.getEncryptionKey());
                //            specItem.setSpec(cspec);
                virtualMachineCloneSpec.setCustomization(cspec);
            } else {
                // Linux?
                // CustomizationSpecItem specItem = new CustomizationSpecItem();
                // CustomizationSpecInfo specInfo = new CustomizationSpecInfo();
                // specItem.setInfo(specInfo);
                CustomizationSpec customSpec = new CustomizationSpec();
                CustomizationLinuxOptions linuxOptions = new CustomizationLinuxOptions();
                customSpec.setOptions(linuxOptions);
                CustomizationLinuxPrep linuxPrep = new CustomizationLinuxPrep();
                linuxPrep.setDomain("default");
                // linuxPrep.setHwClockUTC(true);
                // linuxPrep.setTimeZone("Canada/Eastern");
                CustomizationFixedName fixedName = new CustomizationFixedName();
                fixedName.setName(vmName);//hostname
                linuxPrep.setHostName(fixedName);
                customSpec.setIdentity(linuxPrep);
                CustomizationGlobalIPSettings gIp = new CustomizationGlobalIPSettings();
                customSpec.setGlobalIPSettings(gIp);
                CustomizationFixedIp fixedIp = new CustomizationFixedIp();
                fixedIp.setIpAddress(ipList.get(0)[0].toString());//ipaddress
                CustomizationIPSettings adapter = new CustomizationIPSettings();
                adapter.setIp(fixedIp);
                adapter.setDnsServerList(new String[] { cidr[2] });
                adapter.setGateway(new String[] { cidr[1] });
                adapter.setSubnetMask(cidr[0]);
                CustomizationAdapterMapping adapterMap = new CustomizationAdapterMapping();
                adapterMap.setAdapter(adapter);
                CustomizationAdapterMapping[] nicSettingMap = new CustomizationAdapterMapping[] { adapterMap };
                customSpec.setNicSettingMap(nicSettingMap);
                // CustomizationSpecManager specManager =
                // si.getCustomizationSpecManager();
                // customSpec.setEncryptionKey(specManager.getEncryptionKey());
                virtualMachineCloneSpec.setCustomization(customSpec);
            }
        }

        clonevmRequest.setVirtualMachineCloneSpec(virtualMachineCloneSpec);

        // ?
        ListDatacentersRequest ListDatacentersRequestT = new ListDatacentersRequest();
        ListDatacentersRequestT.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
        ListDatacentersRequestT.setName(clusterConfig.getDcname());
        ListDatacentersRequestT = (ListDatacentersRequest) TccCloudPlatUitls
                .setRequestParam(ListDatacentersRequestT);
        ListDatacentersResponse ListDatacentersResponseT = (ListDatacentersResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(ListDatacentersRequestT);

        clonevmRequest.setDatacenter(ListDatacentersResponseT.getListDatacentersResponse().getDatacenter().get(0));

        // 
        GetVirtualMachineRequest GetVirtualMachineRequestT = new GetVirtualMachineRequest();
        GetVirtualMachineRequestT.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
        GetVirtualMachineRequestT.setVmName(map.get("templateName").toString());
        GetVirtualMachineRequestT = (GetVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(GetVirtualMachineRequestT);
        GetVirtualMachineResponse GetVirtualMachineResponseT = (GetVirtualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(GetVirtualMachineRequestT);

        clonevmRequest.setVirtualMachine(GetVirtualMachineResponseT.getVitualMachine());
        // ###### by zhachaoy #####

        // ??vCenter??
        //      boolean flag = validateCreateAndCloneByVc(map.get("templateId")
        //            .toString());
        //      if (!flag) {
        //         errorMsg = "??vCenter?";
        //         logger.error(errorMsg);
        //         errorMap.put("FAILURE", errorMsg);
        //         errorMap.put("SUCCESS", "false");
        //         errorMap.put("msg", errorMsg);
        //         return errorMap;
        //      }
        clonevmRequest = (CloneVitualMachineRequest) TccCloudPlatUitls.setRequestParam(clonevmRequest);
        CloneVitualMachineResponse cloneVmResponse = (CloneVitualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(clonevmRequest);
        if (cloneVmResponse.isResult()) {
            // ?
            if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
                AddVirtualMachineDiskRequest addDiskRequest = new AddVirtualMachineDiskRequest();
                addDiskRequest.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
                addDiskRequest.setDiskSize(tccProjectInfo.getSanStorageSize());
                addDiskRequest.setName(vmName);
                addDiskRequest = (AddVirtualMachineDiskRequest) TccCloudPlatUitls.setRequestParam(addDiskRequest);
                AddVirtualMachineDiskReponse addResponse = (AddVirtualMachineDiskReponse) TccCloudPlatUitls
                        .getVmwareAdapte().execute(addDiskRequest);
            }
            GetVirtualMachineRequest getVmRequest = new GetVirtualMachineRequest();
            getVmRequest.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
            getVmRequest.setVmName(vmName);
            getVmRequest = (GetVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(getVmRequest);
            GetVirtualMachineResponse response = (GetVirtualMachineResponse) TccCloudPlatUitls.getVmwareAdapte()
                    .execute(getVmRequest);

            String vmGutestId = response.getVitualMachine().getConfig().getGuestId();
            // ??
            if (vmGutestId.contains("win") || vmGutestId.contains("windows")) {
                vmGutestId = "windows";
            } else {
                vmGutestId = "linux";
            }

            ass.setTemplateId(String.valueOf(map.get("id")));
            ass.setOsType(vmGutestId);
            // ?
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTSUCC);
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            ass = configAssApplyCaseService.getConfigAssApplyCase(ass.getAssId());
            // ?????
            TccSrt srt = vmAssistService.getSrt(ass.getTccSrt().getSrtId());
            TccApplyedHostResource applyedHostResource = vmAssistService
                    .mergeApplyedHostResource(response.getVitualMachine(), ass, null, null, clusterId);

            // ???
            applyedHostResource.setHostLoginUsername(template.getUsername());
            applyedHostResource.setHostLoginPassword(template.getPasswd());
            applyedHostResource.setHardwareTypeCd("186");

            // ?ip?
            applyedHostResource.setIpAddress(ipList.get(0)[0].toString());

            /** add host to monitor by Destiny : begin **/
            String host = String.valueOf(applyedHostResource.getApplyResourceId());
            //         String hostName = applyedHostResource.getHostNane(); 
            String visibleName = applyedHostResource.getHostNane();

            if (!zabbixApiService.isAddHostToMonitorByHostName(host)) {
                HostMonitorBean hostinfo = new HostMonitorBean();
                hostinfo.setHostName(host);
                hostinfo.setVisibleName(visibleName);
                hostinfo.setIp(applyedHostResource.getIpAddress());
                hostinfo.setOsName(vmGutestId);
                applyedHostResource.setMonitorFlg(zabbixApiService.addHostToMonitor(hostinfo) ? "1" : "0");
            } else {
                logger.info("[" + host + "]zabbix");
                applyedHostResource.setMonitorFlg("1");
            }

            commonDao.update(applyedHostResource);
            /** add host to monitor by Destiny : end **/

            // ?IP??
            vmAssistService.saveSrtApplyedhostAss(applyedHostResource, srt);
            // ip?
            StringBuffer updateSql = new StringBuffer();
            updateSql.append("UPDATE T_CC_IP_CONFIG_INFO f SET f.USED_FLAG='1' WHERE f.IP_ADDRESS ='"
                    + ipList.get(0)[0].toString() + "'");
            // ip?
            commonDao.updateByNativeSql(updateSql.toString());
            // CPU?MEM?
            capacityMgmtService.takingCpuRam(applyedHostResource.getTccPhysiscResourceInfo(),
                    configCase.getCpuCoreCount(), configCase.getRamSize());
            // ??
            TccProjectInfo projectInfo = tccProjectInfo;
            vmAssistService.saveProjectAss(applyedHostResource, projectInfo);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog(
                    "" + loginUserInfo.getEmpName() + "venter" + vmName
                            + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    BusinessEnvironment.OPER_TYPE_ADD_VM, applyedHostResource, 2);
            logger.info("vCenter????"
                    + applyedHostResource.getHostNane());
            errorMap.put("SUCCESS", applyedHostResource.getApplyResourceId() + "");
            // ???snapshotcategory?
            TccSnapshotCfg snapshotCfg = new TccSnapshotCfg();
            snapshotCfg.setCrtDttm(new Date());
            Set<TccApplyedHostinfo> tccApplyedHostinfos = ass.getTccApplyedHostinfos();
            for (TccApplyedHostinfo temp : tccApplyedHostinfos) {
                snapshotCfg.setCrtUserId(temp.getCrtUserId() + "");
                break;
            }
            snapshotCfg.setCrtUserId(String.valueOf(srt.getCrtUserId()));
            snapshotCfg.setShotMaxNum(0L);
            snapshotCfg.setHostId(applyedHostResource.getApplyResourceId());
            snapshotCfg.setVmName(response.getVitualMachine().getName());
            snapshotCfg.setEnableFlg("1");
            snapshotCategoryService.AddSnapshotCategory(snapshotCfg);

            return errorMap;
        } else {
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "venter"
                    + vmName + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
            logger.info("vCenter?");
            errorMsg = "??,??!";
            logger.error(errorMsg);
            errorMap.put("FAILURE", errorMsg);
            errorMap.put("SUCCESS", "false");
            errorMap.put("msg", errorMsg);
            return errorMap;
        }

    }

    @Override
    public Map<String, String> cloneVC(Long srtId, Long applyResourceId) throws Exception, Throwable {// <<<<<<<<<<<<<<<<<<<<<
        /**
         * LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance()
         * .getCurrentUser(); Map<String, String> errorMap = new HashMap<String,
         * String>(); String errorMsg = ""; // ?? TccApplyedHostResource
         * aApplyedHostResource = vmAssistService
         * .getApplyedHostResource(applyResourceId);
         * 
         * if (EnvironmentConstant.DISENABLE.equals(aApplyedHostResource
         * .getEnableFlg())) { throw new
         * ApplicationException("??????"); } // ?????
         * TccConfigAssApplycase aConfigAssApplycase = aApplyedHostResource
         * .getTccConfigAssApplycase(); // ?(?) // ????
         * TccConfigAssApplycase newConfigAssApplycase = new
         * TccConfigAssApplycase();
         * BeanUtils.copyProperties(newConfigAssApplycase, aConfigAssApplycase);
         * newConfigAssApplycase.setAssId(null); //
         * newConfigAssApplycase.setTccSrt(newPressApply);
         * newConfigAssApplycase.setIpType(newConfigAssApplycase.getIpType()
         * .substring(3));
         * 
         * TccConfigCase configCase =
         * newConfigAssApplycase.getTccSetMealConfig() .getTccConfigCase();
         * TccTemplateCase templateCase = newConfigAssApplycase
         * .getTccSetMealConfig().getTccTemplateCase(); TccSysStoreCase
         * sysStoreCase = newConfigAssApplycase
         * .getTccSetMealConfig().getTccSysStoreCase();
         * 
         * newConfigAssApplycase = configAssApplyCaseService
         * .mergeConfigAssApplyCase(newConfigAssApplycase); // ?IP String
         * ipType = aConfigAssApplycase.getIpType(); String[] ipTypes =
         * ipType.split("[@]"); if (ipTypes != null && ipTypes.length > 0) {
         * ipType = ipTypes[0]; } IpZoneEnum ipZone =
         * IpZoneEnum.getById(ipType); CloneVitualMachineRequest cloneRequest =
         * new CloneVitualMachineRequest(); // ?IP? Ip ip =
         * capacityMgmtService.loadIpBeforeCreateVm(newConfigAssApplycase
         * .getAssId(), ipZone); if (null != ip) {
         * cloneRequest.setHost(ip.toString());
         * cloneRequest.setIpAddress(ip.toString()); } else {
         * newConfigAssApplycase
         * .setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
         * configAssApplyCaseService
         * .updateConfigAssApplyCase(newConfigAssApplycase);
         * logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
         * loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_ADD_VM,
         * newConfigAssApplycase, 2); errorMsg = "IP";
         * logger.error(errorMsg); errorMap.put("FAILURE", errorMsg); return
         * errorMap; } // VC???IP_??_?10.10.11.13__?
         * String vmName = aApplyedHostResource.getHostNane(); String[] vmNames =
         * vmName.split("[_]"); vmName = ip.toString() + "_" + vmNames[1] + "_" +
         * vmNames[2]; cloneRequest.setName(vmName);
         * cloneRequest.setCloud(this.queryPlatformByvmId(applyResourceId +
         * "").getCloudplatformId() + "");
         * cloneRequest.setClusterName(aApplyedHostResource
         * .getTccPhysiscResourceInfo().getTccCluster().getClusterName());
         * cloneRequest.setMemory(String.valueOf(configCase.getRamSize() *
         * 1024));
         * cloneRequest.setCpu(String.valueOf(configCase.getCpuCoreCount()));
         * cloneRequest .setDisk(String.valueOf(sysStoreCase.getStoreSize() *
         * 1024));
         * cloneRequest.setOsName(templateCase.getVcTemplateOfferingId()); //
         * ??vCenter?? boolean flag =
         * validateCreateAndCloneByVc(templateCase .getVcTemplateOfferingId());
         * if (!flag) { errorMsg = "??vCenter?";
         * logger.error(errorMsg); errorMap.put("FAILURE", errorMsg); return
         * errorMap; } // vCenter cloneRequest =
         * (CloneVitualMachineRequest) TccCloudPlatUitls
         * .setRequestParam(cloneRequest); CloneVitualMachineResponse
         * cloneResponse = (CloneVitualMachineResponse) TccCloudPlatUitls
         * .getVmwareAdapte().execute(cloneRequest); Boolean isOK =
         * cloneResponse.isResult(); if (isOK) { GetVirtualMachineRequest
         * getVmRequest = new GetVirtualMachineRequest();
         * getVmRequest.setCloud(this .queryPlatformByvmId(applyResourceId +
         * "").getCloudplatformId() + ""); getVmRequest.setVmName(vmName);
         * getVmRequest = (GetVirtualMachineRequest) TccCloudPlatUitls
         * .setRequestParam(getVmRequest); GetVirtualMachineResponse
         * getVmResponse = (GetVirtualMachineResponse) TccCloudPlatUitls
         * .getAdapte().execute(getVmRequest); // ?
         * newConfigAssApplycase
         * .setSetupStats(BusinessEnvironment.SETUP_STATS_INSTSUCC);
         * configAssApplyCaseService
         * .updateConfigAssApplyCase(newConfigAssApplycase);
         * newConfigAssApplycase = configAssApplyCaseService
         * .getConfigAssApplyCase(newConfigAssApplycase.getAssId()); //
         * IP?&?? isOK =
         * capacityMgmtService.afterCreateVm(newConfigAssApplycase, ipZone, ip);
         * if (!isOK) {// 
         * logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
         * loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_ADD_VM,
         * newConfigAssApplycase, 2); errorMsg = "IP???";
         * logger.error(errorMsg); errorMap.put("FAILURE", errorMsg); return
         * errorMap; } // ????? TccSrt srt =
         * vmAssistService.getSrt(newConfigAssApplycase
         * .getTccSrt().getSrtId()); TccApplyedHostResource
         * newApplyedHostResource = vmAssistService
         * .mergeApplyedHostResource(getVmResponse.getVitualMachine(),
         * newConfigAssApplycase, ip.toString(), null, null);
         * vmAssistService.saveSrtApplyedhostAss(newApplyedHostResource, srt); //
         * CPU?MEM? capacityMgmtService.takingCpuRam(newApplyedHostResource
         * .getTccPhysiscResourceInfo(), configCase.getCpuCoreCount(),
         * configCase.getRamSize()); // ?? //
         * Hibernate.initialize(pressApply.getTccProjectInfo()); //
         * TccProjectInfo projectInfo = pressApply.getTccProjectInfo();
         * TccProjectAss newTccProjectAss = new TccProjectAss(); //
         * newTccProjectAss.setTccProjectInfo(projectInfo);
         * newTccProjectAss.setTccApplyedHostinfo(newApplyedHostResource);
         * this.commonDao.save(newTccProjectAss); // 2.2????
         * capacityMgmtService.takingX86SelfServiceAfterCreate(srtId,
         * newTccProjectAss.getProjectAssId()); // ? TccSetMealConfig
         * setMealConfig = newConfigAssApplycase .getTccSetMealConfig(); if
         * (null != setMealConfig) { String setMealType =
         * setMealConfig.getSetMealType(); if
         * (BusinessEnvironment.SET_MEAL_TYPE_DBSERV .equals(setMealType)) { //
         * ???? if (null != newConfigAssApplycase.getTccDbInstance()) { //
         * ? TccDbInstance newTccDbInstance = new TccDbInstance();
         * TccDbInstance tccDbInstance = newConfigAssApplycase
         * .getTccDbInstance(); BeanUtils.copyProperties(newTccDbInstance,
         * tccDbInstance); newTccDbInstance.setInstanceId(null);
         * this.commonDao.save(newTccDbInstance); newConfigAssApplycase
         * .setTccDbInstance(newTccDbInstance); // ??? if (null !=
         * tccDbInstance.getTccDbAccounts()) { // ?? List<TccDbAccount>
         * listAcc = new ArrayList<TccDbAccount>(); TccDbAccount
         * newTccDbAccount = null; // ?? Hibernate.initialize(tccDbInstance
         * .getTccDbAccounts()); Set<TccDbAccount> setAcc = tccDbInstance
         * .getTccDbAccounts(); for (TccDbAccount tccDbAccount : setAcc) {
         * newTccDbAccount = new TccDbAccount();
         * BeanUtils.copyProperties(newTccDbAccount, tccDbAccount);
         * newTccDbAccount.setAccountId(null); newTccDbAccount
         * .setTccDbInstance(newTccDbInstance); listAcc.add(newTccDbAccount); }
         * if (null != listAcc && listAcc.size() > 0) {
         * this.commonDao.saveOrUpdateAll(listAcc); } } } } } //
         * ????, if (null !=
         * aApplyedHostResource.getTccSysAccountInfos()) {
         * Hibernate.initialize(aApplyedHostResource .getTccSysAccountInfos());
         * Set<TccSysAccountInfo> setTccSys = aApplyedHostResource
         * .getTccSysAccountInfos(); if (null != setTccSys && setTccSys.size() >
         * 0) { List<TccSysAccountInfo> listTccSys = new ArrayList<TccSysAccountInfo>();
         * TccSysAccountInfo newTccSysAccountInfo = null; for (TccSysAccountInfo
         * tccSysAccountInfo : setTccSys) { newTccSysAccountInfo = new
         * TccSysAccountInfo(); BeanUtils.copyProperties(newTccSysAccountInfo,
         * tccSysAccountInfo); newTccSysAccountInfo.setAccId(null);
         * newTccSysAccountInfo .setTccApplyedHostinfo(newApplyedHostResource);
         * listTccSys.add(newTccSysAccountInfo); }
         * this.commonDao.saveOrUpdateAll(listTccSys); } } // ?,????
         * if (null != aConfigAssApplycase.getTccInstanceInfos()) {
         * Hibernate.initialize(aConfigAssApplycase.getTccInstanceInfos()); Set<TccInstanceInfo>
         * setInst = aConfigAssApplycase .getTccInstanceInfos(); if (null !=
         * setInst && setInst.size() > 0) { TccInstanceInfo newTccInstanceInfo =
         * null; List<TccSysAccountInfo> listTccSys = new ArrayList<TccSysAccountInfo>();
         * TccSysAccountInfo newTccSysAccountInfo = null; for (TccInstanceInfo
         * tccInstanceInfo : setInst) { if
         * (EnvironmentConstant.ENABLE.equals(tccInstanceInfo .getEnableFlg())) {
         * newTccInstanceInfo = new TccInstanceInfo();
         * BeanUtils.copyProperties(newTccInstanceInfo, tccInstanceInfo);
         * newTccInstanceInfo.setInstanceId(null);
         * newTccInstanceInfo.setCrtDttm(new Date());
         * newTccInstanceInfo.setCrtUserId(loginUserInfo .getUserPartyId());
         * newTccInstanceInfo.setLastuptDttm(new Date());
         * newTccInstanceInfo.setLastuptUserId(loginUserInfo .getUserPartyId());
         * newTccInstanceInfo .setTccConfigAssApplycase(newConfigAssApplycase);
         * newTccInstanceInfo .setTccProjectAss(newTccProjectAss);
         * newTccInstanceInfo.setTccReleaseResources(null);
         * newTccInstanceInfo.setTccSysAccountInfos(null);
         * this.commonDao.save(newTccInstanceInfo); if (null !=
         * tccInstanceInfo.getTccSysAccountInfos()) {
         * Hibernate.initialize(tccInstanceInfo .getTccSysAccountInfos()); Set<TccSysAccountInfo>
         * setTccSys = tccInstanceInfo .getTccSysAccountInfos(); if (null !=
         * setTccSys && setTccSys.size() > 0) { for (TccSysAccountInfo
         * tccSysAccountInfo : setTccSys) { newTccSysAccountInfo = new
         * TccSysAccountInfo(); BeanUtils.copyProperties( newTccSysAccountInfo,
         * tccSysAccountInfo); newTccSysAccountInfo.setAccId(null);
         * newTccSysAccountInfo .setTccInstanceInfo(newTccInstanceInfo);
         * listTccSys.add(newTccSysAccountInfo); } } } } } // ???? if (null !=
         * listTccSys && listTccSys.size() > 0) {
         * this.commonDao.saveOrUpdateAll(listTccSys); } } }
         * logService.saveOperLog("?", "" + loginUserInfo.getEmpName() +
         * "cloudstack" + BusinessEnvironment.OPER_RESULT_SUCCESS,
         * aApplyedHostResource, 2); logger.info("vCenter??");
         * 
         * errorMap.put("SUCCESS", newApplyedHostResource.getApplyResourceId() +
         * ""); return errorMap; } else { newConfigAssApplycase
         * .setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
         * configAssApplyCaseService
         * .updateConfigAssApplyCase(newConfigAssApplycase);
         * 
         * logService.saveOperLog("", "" + loginUserInfo.getEmpName() +
         * "cloudstack" + vmName + BusinessEnvironment.OPER_RESULT_FAILURE,
         * aApplyedHostResource, 2); logger.info("vCenter?");
         * 
         * errorMsg = ",??!"; logger.error(errorMsg);
         * errorMap.put("FAILURE", errorMsg); return errorMap; }
         */
        return null;
    }

    public Map<String, String> cloneVC(Long assId, Long sourceId, Long clusterId, TccProjectInfo tccProjectInfo,
            String vmName, String networkname) throws Exception, Throwable {
        System.out.print("cloneVC mutl");

        Map<String, String> errorMsg = new HashMap<String, String>();

        TccConfigAssApplycase ass = (TccConfigAssApplycase) configAssApplyCaseService.getConfigAssApplyCase(assId);
        TccApplyedHostResource host = (TccApplyedHostResource) this.commonDao.get(TccApplyedHostResource.class,
                sourceId);

        if (EnvironmentConstant.DISENABLE.equals(host.getEnableFlg())) {
            errorMsg.put("SUCCESS", "false");
            errorMsg.put("msg", "??????");
            return errorMsg;
        }
        // ?
        ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTING);
        configAssApplyCaseService.updateConfigAssApplyCase(ass);
        if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
            ass.setSanStorageSize(tccProjectInfo.getSanStorageSize());
        } else {
            ass.setSanStorageSize("0");
        }
        if (StringUtils.isNotBlank(tccProjectInfo.getNasStorageSize())) {
            ass.setNasStorageSize(tccProjectInfo.getNasStorageSize());
        } else {
            ass.setNasStorageSize("0");
        }

        TccConfigCase configCase = ass.getTccSetMealConfig().getTccConfigCase();
        TccTemplateCase templateCase = (TccTemplateCase) this.commonDao.get(TccTemplateCase.class,
                Long.valueOf(host.getTemplateId()));
        TccSysStoreCase sysStoreCase = ass.getTccSetMealConfig().getTccSysStoreCase();

        /*
         * ???ID ???? ??
         */
        TccClusterConfig clusterConfig = vmAssistService.getClusterConfig(clusterId);
        ass.setVrSubType(clusterConfig.getVtype());
        if (vmName != null && !vmName.equals("")) {
            boolean flag = vmAssistService.checkDuplVmName(vmName);
            if (flag == false) {
                String error = "????";
                logger.error(error);
                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg", error);
                return errorMsg;
            }
        }
        CloneVitualMachineRequest cloneRequest = new CloneVitualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByClusterId(clusterConfig.getId() + "");
        cloneRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");

        try {
            cloneRequest.setName(vmName);

            // cloneRequest.setDatacenterName(BusinessEnvironment.VCENTER_DCNAME);
            // cloneRequest.setClusterName(clusterConfig.getClusterName());
            // cloneRequest.setDatacenterName(clusterConfig.getDcname());
            //
            // cloneRequest.setTemplateName(host.getHostNane());
            // cloneRequest.setMemory(String.valueOf((host.getRamSize())));
            // cloneRequest.setCpu(host.getCpuCoreCount().toString());
            // cloneRequest.setDisk(String.valueOf(Integer.valueOf(templateCase
            // .getTemplateSize()) * 1024));
            // cloneRequest.setOsName(templateCase.getCsTemplateOfferingId());

            // ***** by zhachaoy i*****
            // ?
            VirtualMachineCloneSpec virtualMachineCloneSpec = new VirtualMachineCloneSpec();

            // ???
            VirtualMachineRelocateSpec virtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
            // ?
            // 
            ListClusterComputeResourcesRequest ListClusterComputeResourcesRequestT = new ListClusterComputeResourcesRequest();
            ListClusterComputeResourcesRequestT.setCloud(tcccloudplatform.getCloudplatformId() + "");
            ListClusterComputeResourcesRequestT.setName(clusterConfig.getClusterName());
            ListClusterComputeResourcesRequestT = (ListClusterComputeResourcesRequest) TccCloudPlatUitls
                    .setRequestParam(ListClusterComputeResourcesRequestT);
            ListClusterComputeResourcesResponse ListClusterComputeResourcesResponseT = (ListClusterComputeResourcesResponse) TccCloudPlatUitls
                    .getVmwareAdapte().execute(ListClusterComputeResourcesRequestT);
            ClusterComputeResource ClusterComputeResourceT = ListClusterComputeResourcesResponseT
                    .getListClusterComputeResourcesResponse().getClusterComputeResource().get(0);
            try {
                // 
                virtualMachineRelocateSpec.setPool(ClusterComputeResourceT.getResourcePool().getMOR());
            } catch (Exception e) {
                logger.error("?" + clusterConfig.getClusterName());
                errorMsg.put("FAILURE", "?" + clusterConfig.getClusterName());

                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg", "?" + clusterConfig.getClusterName());
                return errorMsg;
            }
            // ?
            Datastore DatastoreT = null;
            for (Datastore datasotre : ClusterComputeResourceT.getDatastores()) {
                if (null == DatastoreT) {
                    DatastoreT = datasotre;
                } else {
                    try {
                        if (datasotre.getInfo().getFreeSpace() > DatastoreT.getInfo().getFreeSpace()) {
                            DatastoreT = datasotre;
                        }
                    } catch (Exception e) {
                        logger.warn("datastore:" + datasotre.getName());
                    }
                }
            }
            // ??
            HostSystem HostSystemT = null;
            for (HostSystem hostSystem : ClusterComputeResourceT.getHosts()) {
                if (null == HostSystemT) {
                    HostSystemT = hostSystem;
                } else {
                    try {
                        if (hostSystem.getVms().length < HostSystemT.getVms().length) {
                            HostSystemT = hostSystem;
                        }
                    } catch (Exception e) {
                        logger.warn("host:" + hostSystem.getName());
                    }
                }
            }
            try {
                // ?
                virtualMachineRelocateSpec.setHost(HostSystemT.getMOR());// ,??
            } catch (Exception e) {
                logger.error("" + clusterConfig.getClusterName() + "??");
                errorMsg.put("FAILURE",
                        "" + clusterConfig.getClusterName() + "??");

                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg",
                        "" + clusterConfig.getClusterName() + "??");
                return errorMsg;
            }
            try {
                // 
                virtualMachineRelocateSpec.setDatastore(DatastoreT.getMOR());// ,
            } catch (Exception e) {
                logger.error("" + clusterConfig.getClusterName() + "?");
                errorMsg.put("FAILURE",
                        "" + clusterConfig.getClusterName() + "?");
                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg", "" + clusterConfig.getClusterName() + "?");
                return errorMsg;
            }
            virtualMachineCloneSpec.setLocation(virtualMachineRelocateSpec);

            // ???
            VirtualMachineConfigSpec virtualMachineConfigSpec = new VirtualMachineConfigSpec();
            // memory
            virtualMachineConfigSpec.setMemoryMB(configCase.getRamSize() * 1024);
            // cpu
            virtualMachineConfigSpec.setNumCPUs(configCase.getCpuCoreCount().intValue());
            virtualMachineCloneSpec.setConfig(virtualMachineConfigSpec);

            // ???
            virtualMachineCloneSpec.setPowerOn(true);
            virtualMachineCloneSpec.setTemplate(false);

            cloneRequest.setVirtualMachineCloneSpec(virtualMachineCloneSpec);

            // ?
            ListDatacentersRequest ListDatacentersRequestT = new ListDatacentersRequest();
            ListDatacentersRequestT.setCloud(tcccloudplatform.getCloudplatformId() + "");
            ListDatacentersRequestT.setName(clusterConfig.getDcname());
            ListDatacentersRequestT = (ListDatacentersRequest) TccCloudPlatUitls
                    .setRequestParam(ListDatacentersRequestT);
            ListDatacentersResponse ListDatacentersResponseT = (ListDatacentersResponse) TccCloudPlatUitls
                    .getVmwareAdapte().execute(ListDatacentersRequestT);

            cloneRequest
                    .setDatacenter(ListDatacentersResponseT.getListDatacentersResponse().getDatacenter().get(0));

            // 
            GetVirtualMachineRequest GetVirtualMachineRequestT = new GetVirtualMachineRequest();
            GetVirtualMachineRequestT.setCloud(tcccloudplatform.getCloudplatformId() + "");
            GetVirtualMachineRequestT.setVmName(host.getHostNane());
            GetVirtualMachineRequestT = (GetVirtualMachineRequest) TccCloudPlatUitls
                    .setRequestParam(GetVirtualMachineRequestT);
            GetVirtualMachineResponse GetVirtualMachineResponseT = (GetVirtualMachineResponse) TccCloudPlatUitls
                    .getVmwareAdapte().execute(GetVirtualMachineRequestT);

            cloneRequest.setVirtualMachine(GetVirtualMachineResponseT.getVitualMachine());

            cloneRequest = (CloneVitualMachineRequest) TccCloudPlatUitls.setRequestParam(cloneRequest);
            CloneVitualMachineResponse cloneVmResponse = (CloneVitualMachineResponse) TccCloudPlatUitls
                    .getVmwareAdapte().execute(cloneRequest);
            Boolean isOK = cloneVmResponse.isResult();
            if (isOK) {
                GetVirtualMachineRequest getVmRequest = new GetVirtualMachineRequest();
                getVmRequest.setCloud(
                        this.queryPlatformByClusterId(clusterConfig.getId() + "").getCloudplatformId() + "");
                getVmRequest.setVmName(vmName);
                getVmRequest = (GetVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(getVmRequest);
                GetVirtualMachineResponse getVmResponse = (GetVirtualMachineResponse) TccCloudPlatUitls
                        .getVmwareAdapte().execute(getVmRequest);

                // ?
                String vmGutestId = getVmResponse.getVitualMachine().getConfig().getGuestId();
                if (vmGutestId.contains("win") || vmGutestId.contains("windows")) {
                    vmGutestId = "windows";
                } else {
                    vmGutestId = "linux";
                }
                ass.setOsType(vmGutestId);

                errorMsg.put("SUCCESS", "true");
                errorMsg.put("msg", "?[" + vmName + "]");
                String volumeOfferingId = "";// ?UUID7
                // SAN??
                if (ass.getSanStorageSize() != null && !ass.getSanStorageSize().equals("0")
                        && Long.valueOf(ass.getSanStorageSize()).intValue() > 0) {
                    // ????
                    TccSysStoreCase ssc = new TccSysStoreCase();
                    ssc.setStoreCaseName(
                            ass.getTccSetMealConfig().getTccPluginStoreCase().getPluginStoreCaseName());
                    ssc.setStoreSize(Long.valueOf(ass.getSanStorageSize()));
                    ssc.setMomo(ass.getTccSetMealConfig().getTccPluginStoreCase().getMomo());
                    AddVirtualMachineDiskRequest addVmRequest = new AddVirtualMachineDiskRequest();
                    addVmRequest.setCloud(
                            this.queryPlatformByClusterId(clusterConfig.getId() + "").getCloudplatformId() + "");
                    addVmRequest.setName(vmName);
                    addVmRequest.setDiskSize(String.valueOf(Integer.valueOf(ass.getSanStorageSize())));
                    addVmRequest = (AddVirtualMachineDiskRequest) TccCloudPlatUitls.setRequestParam(addVmRequest);
                    AddVirtualMachineDiskReponse addVmResponse = (AddVirtualMachineDiskReponse) TccCloudPlatUitls
                            .getVmwareAdapte().execute(addVmRequest);

                }
                // ?????
                TccSrt srt = vmAssistService.getSrt(ass.getTccSrt().getSrtId());
                TccApplyedHostResource applyedHostResource = vmAssistService.mergeApplyedHostResource(
                        getVmResponse.getVitualMachine(), ass, "", volumeOfferingId, "",
                        clusterConfig.getId().toString());
                applyedHostResource.setTemplateId(host.getTemplateId());
                vmAssistService.saveSrtApplyedhostAss(applyedHostResource, srt);

                ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTSUCC);
                configAssApplyCaseService.updateConfigAssApplyCase(ass);

                // ////////////////////////////////////////////////////////////
                // ??IP?
                StringBuffer sql = new StringBuffer();
                sql.append("SELECT IP_ADDRESS FROM T_CC_IP_CONFIG_INFO f WHERE f.name='" + networkname
                        + "'  AND  f.used_flag=0 ORDER BY  ip_config_id asc");
                List<String> ipList = commonDao.findBySqlNoUpperLow(sql.toString(), null, -1, -1);
                // ip?
                String tmp_errorMsg = "";
                if (ipList.size() == 0) {
                    tmp_errorMsg = "?IP?!";
                    logger.error(errorMsg);
                    errorMsg.put("FAILURE", tmp_errorMsg);
                    errorMsg.put("SUCCESS", "false");
                    errorMsg.put("msg", tmp_errorMsg);
                    return errorMsg;
                }
                applyedHostResource.setIpAddress(ipList.get(0));
                // ?IP??
                vmAssistService.saveApplyedHostResource(applyedHostResource);
                // ip?
                StringBuffer updateSql = new StringBuffer();
                updateSql.append("UPDATE T_CC_IP_CONFIG_INFO f SET f.USED_FLAG='1' WHERE f.IP_ADDRESS ='"
                        + ipList.get(0) + "'");
                // ip?
                commonDao.updateByNativeSql(updateSql.toString());

                // ////////////////////////////////////////////////////////////
                // CPU?MEM?
                capacityMgmtService.takingCpuRam(applyedHostResource.getTccPhysiscResourceInfo(),
                        ass.getTccSetMealConfig().getTccConfigCase().getCpuCoreCount(),
                        ass.getTccSetMealConfig().getTccConfigCase().getRamSize());

                // ??
                TccProjectInfo projectInfo = tccProjectInfo;
                vmAssistService.saveProjectAss(applyedHostResource, projectInfo);

                String displayName = vmName;

                // csInvocator.updateVm_CS(vmVo.getId(), displayName);

                TccApplyedHostResource ahr = vmAssistService
                        .getApplyedHostResource(applyedHostResource.getApplyResourceId());
                ahr.setHostNane(displayName);
                ahr.setHostLoginUsername(templateCase.getUsername());
                ahr.setHostLoginPassword(templateCase.getPasswd());

                ahr.setHardwareTypeCd("186");//?

                vmAssistService.updateApplyedHostResource(ahr);
                // 
                HostMonitorBean hostinfo = new HostMonitorBean();
                hostinfo.setHostName(vmName);
                hostinfo.setIp(applyedHostResource.getIpAddress());

                String osDescription = "";
                if (getVmResponse.getVitualMachine().getConfig().getGuestFullName() != null && getVmResponse
                        .getVitualMachine().getConfig().getGuestFullName().toLowerCase().indexOf("win") > -1) {
                    hostinfo.setOsName("windows");
                } else {

                    hostinfo.setOsName("linux");
                }
                // linux,windows
                hostinfo.setPort("10050");
                hostinfo.setStatus(0);//
                hostinfo.setMonitorType(1);
                try {
                    zabbixApiService.addHostToMonitor(hostinfo);
                } catch (Exception ex) {
                    this.logger.error("?", ex);
                }

                // ???snapshotcategory?
                TccSnapshotCfg snapshotCfg = new TccSnapshotCfg();
                snapshotCfg.setCrtDttm(new Date());
                Set<TccApplyedHostinfo> tccApplyedHostinfos = ass.getTccApplyedHostinfos();
                for (TccApplyedHostinfo temp : tccApplyedHostinfos) {
                    snapshotCfg.setCrtUserId(temp.getCrtUserId() + "");
                    break;
                }
                snapshotCfg.setCrtUserId(String.valueOf(srt.getCrtUserId()));
                snapshotCfg.setShotMaxNum(0L);
                snapshotCfg.setHostId(ahr.getApplyResourceId());
                snapshotCfg.setVmName(displayName);
                snapshotCfg.setEnableFlg("1");
                snapshotCategoryService.AddSnapshotCategory(snapshotCfg);

                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + "vcenter"
                        + BusinessEnvironment.OPER_RESULT_SUCCESS, ass, 2);
                errorMsg.put("SUCCESS", "true");
            } else {// 

                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "vcenter"
                        + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
                ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
                configAssApplyCaseService.updateConfigAssApplyCase(ass);
                logger.error(errorMsg);
                errorMsg.put("SUCCESS", "false");
                // errorMsg.put("msg", "[" + vmName + "]" + errorMsg);
                errorMsg.put("msg", "[" + vmName + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();

            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
            logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "vcenter"
                    + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            logger.error(e);
            errorMsg.put("SUCCESS", "false");
            errorMsg.put("msg", "[" + vmName + "]" + e.getMessage());
        }
        return errorMsg;
    }

    public boolean destroyVm(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        if (null != applyedHostResource
                && applyedHostResource.getVirtualType().equals(BusinessEnvironment.VIRTUAL_TYPE_VC)) {
            return destroyVC(applyResourceId);
        } else if (null != applyedHostResource
                && applyedHostResource.getVirtualType().equals(BusinessEnvironment.VIRTUAL_TYPE_CS)) {
            return destroyCS(applyResourceId);
        } else {
            return false;
        }
    }

    @Override
    public boolean destroyCS(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        logService.saveOperLog("?", loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_DESTROY_VM
                + BusinessEnvironment.OPER_RESULT_IN_PROCESS, applyedHostResource, 2);
        if (StringUtils.isNotBlank(applyedHostResource.getVolumeUuid())) {
            boolean detachVolumeFlag = volumeService.detachVolumeCS("", applyedHostResource.getVolumeUuid(),
                    applyedHostResource.getUuid());
            String platformId = this.queryPlatformByvmId(applyedHostResource.getApplyResourceId() + "")
                    .getCloudplatformId().toString();
            // ?????
            if (detachVolumeFlag) {
                boolean deleteVolumeFlag = volumeService.deleteVolumeCS(applyedHostResource.getVolumeUuid(),
                        platformId);
                // ???
                if (!deleteVolumeFlag) {
                    logger.warn(
                            "???UUID" + applyedHostResource.getStorageSize() + "GB ");
                    logService.saveOperLog("",
                            "" + loginUserInfo.getEmpName() + "?"
                                    + applyedHostResource.getStorageSize() + "GB "
                                    + BusinessEnvironment.OPER_RESULT_FAILURE,
                            applyedHostResource, 2);
                    return deleteVolumeFlag;
                }
            } else {
                logger.warn("????UUID" + applyedHostResource.getStorageSize() + "GB ");
                logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "??"
                        + applyedHostResource.getStorageSize() + "GB " + BusinessEnvironment.OPER_RESULT_FAILURE,
                        applyedHostResource, 2);
                return detachVolumeFlag;
            }
        }
        DestroyVirtualMachineRequest destroyVmRequest = new DestroyVirtualMachineRequest();
        destroyVmRequest.setCloud(
                this.queryPlatformByvmId(applyedHostResource.getApplyResourceId() + "").getCloudplatformId() + "");
        destroyVmRequest.setId(applyedHostResource.getUuid());
        destroyVmRequest = (DestroyVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(destroyVmRequest);
        DestroyVirtualMachineResponse destroyVmResponse = (DestroyVirtualMachineResponse) TccCloudPlatUitls
                .getAdapte().execute(destroyVmRequest);
        AsyncJob asyncJob = destroyVmResponse.getDestroyVirtualMachineResponse();
        String result = asynQueryVmStatus(asyncJob.getJobId(),
                this.queryPlatformByvmId(applyResourceId.toString()).getCloudplatformId().toString());
        boolean isOK = false;
        if (this.SUCCESS.equalsIgnoreCase(result)) {
            isOK = true;
            if (isOK) {
                boolean falg = capacityMgmtService.releaseCpuMemIp(applyedHostResource);
                if (!falg) {
                    logger.warn("IP??");
                }
                // 
                vmAssistService.removeTccSysDict(applyedHostResource.getIpAddress());
                // ?
                applyedHostResource.setEnableFlg(BusinessEnvironment.DISABLE_FLG);
                applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_DESTROYED);// ?
                /** delete host from zabbix by Destiny * */

                try {
                    boolean issuccess = zabbixApiService.deleteHost(applyedHostResource.getIpAddress());
                    if (!issuccess) {
                        logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                                loginUserInfo.getEmpName() + "", applyedHostResource, 2);
                        this.logger.error(applyedHostResource.getIpAddress() + "?");
                    } else {
                        // ?
                        applyedHostResource.setMonitorFlg(BusinessEnvironment.DISABLE_FLG);
                    }
                } catch (Exception ex) {
                    logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                            loginUserInfo.getEmpName() + "", applyedHostResource, 2);
                    this.logger.error(applyedHostResource.getIpAddress() + "?", ex);
                }

                /** end delete host from zabbix * */

                vmAssistService.updateApplyedHostResource(applyedHostResource);

                logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
                        loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_DESTROY_VM, applyedHostResource,
                        2);
            } else {
                isOK = false;
                logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                        loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_DESTROY_VM, applyedHostResource,
                        2);
            }
            // 
            List<String> list = new ArrayList<String>();
            list.add(String.valueOf(applyedHostResource.getApplyResourceId()));
            vmSnapshotService.deleteVmSnapshot(list);

        }
        return isOK;
    }

    @Override
    public boolean destroyVC(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        GetVirtualMachineRequest getVmRequest = new GetVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        getVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        getVmRequest.setVmName(applyedHostResource.getHostNane());
        getVmRequest = (GetVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(getVmRequest);
        GetVirtualMachineResponse getVmResponse = (GetVirtualMachineResponse) TccCloudPlatUitls.getVmwareAdapte()
                .execute(getVmRequest);
        try {
            VirtualMachinePowerState vm = getVmResponse.getVitualMachine().getRuntime().getPowerState();
            // ?vCenter??,,??.,?.
            if (vm == VirtualMachinePowerState.poweredOn) {
                boolean flag = stopVC(applyResourceId);
                if (!flag)
                    return false;
            }
        } catch (Exception e) {
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>:" + getVmRequest.getVmName() + "?", e);
        }
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.DestroyVirtualMachineRequest destroyVmRequest = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.DestroyVirtualMachineRequest();
        destroyVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        destroyVmRequest.setName(applyedHostResource.getHostNane());
        destroyVmRequest = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.DestroyVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(destroyVmRequest);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.DestroyVirtualMachineResponse destroyVmResponse = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.DestroyVirtualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(destroyVmRequest);
        boolean isOK = false;
        if (destroyVmResponse.isResult()) {
            isOK = true;
            boolean falg = true;
            if (!falg) {
                logger.warn("IP??");
            }
            logger.info("VC??");
            // 
            // vmAssistService.removeTccSysDict(applyedHostResource.getIpAddress());
            // ?
            applyedHostResource.setEnableFlg(BusinessEnvironment.DISABLE_FLG);
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_DESTROYED);// ?
            /** delete host from zabbix by Destiny * */

            try {
                boolean issuccess = zabbixApiService.deleteHost(applyedHostResource.getIpAddress());
                if (!issuccess) {
                    logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                            loginUserInfo.getEmpName() + "", applyedHostResource, 2);
                    this.logger.error(applyedHostResource.getIpAddress() + "?");
                } else {
                    // ?
                    applyedHostResource.setMonitorFlg(BusinessEnvironment.DISABLE_FLG);
                }
            } catch (Exception ex) {
                logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
                        loginUserInfo.getEmpName() + "", applyedHostResource, 2);
                this.logger.error(applyedHostResource.getIpAddress() + "?", ex);
            }

            /** end delete host from zabbix * */

            vmAssistService.updateApplyedHostResource(applyedHostResource);

            logService.saveOperLog(
                    "?", "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);
        } else {
            isOK = false;
            logger.info("VC?");
            logService.saveOperLog(
                    "", "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
        }

        return isOK;
    }

    @Override
    public boolean rebootCS(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        RebootVirtualMachineRequest rebootRequest = new RebootVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        rebootRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        rebootRequest.setId(applyedHostResource.getUuid());
        rebootRequest = (RebootVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(rebootRequest);
        RebootVirtualMachineResponse rebootResponse = (RebootVirtualMachineResponse) TccCloudPlatUitls.getAdapte()
                .execute(rebootRequest);
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        logger.info("??");
        String jobStatus = asynQueryVmStatus(rebootResponse.getRebootVirtualMachineResponse().getJobId(),
                this.queryPlatformByvmId(applyResourceId.toString()).getCloudplatformId().toString());
        if (SUCCESS.equals(jobStatus)) { // ?
            LoginUserInfo loginUserInfos = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("?",
                    "" + loginUserInfos.getEmpName() + "??cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);

            logger.info("???");
            return true;
        } else { // 
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "??cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            logger.info("??");
            return false;
        }
    }

    @Override
    public boolean rebootVC(Long applyResourceId) throws Exception, Throwable {
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.RebootVirtualMachineRequest rebootRequest = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.RebootVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        rebootRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        rebootRequest.setName(applyedHostResource.getHostNane());
        rebootRequest = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.RebootVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(rebootRequest);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.RebootVirtualMachineResponse rebootResponse = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.RebootVirtualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(rebootRequest);
        logService.saveOperLog(BusinessEnvironment.OPER_RESULT_IN_PROCESS,
                loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_REBOOT_VM, applyedHostResource, 2);
        logger.info("??");
        boolean isOK = rebootResponse.isResult();
        //??10 ????
        Thread.sleep(10 * 1000);
        if (isOK) {// ?
            logService.saveOperLog("?",
                    "" + loginUserInfo.getEmpName() + "??vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);

            logger.info("???");
            return true;
        } else {
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "??vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            logger.info("??");
            return false;
        }
    }

    /**
     * ?
     * 
     * @param jobid
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public String asynQueryVmStatus(String jobid, String platformId)
            throws InterruptedException, ExecutionException {
        VmCallable task = new VmCallable(jobid, platformId);
        ExecutorService es = Executors.newFixedThreadPool(1);
        Future<String> future = es.submit(task);
        String jobStatus = future.get();
        es.shutdownNow();
        return jobStatus;
    }

    public boolean recoverCS(Long applyResourceId) throws Exception {

        // TccApplyedHostResource applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyResourceId);
        // VirtualmachineVo vmVo = csInvocator
        // .recoverVmById_CS(applyedHostResource.getUuid());// ??
        //
        // if (vmVo.getState().equals(operLogService.STOPPED)) {
        //
        // applyedHostResource.setEnableFlg(BusinessEnvironment.ENABLE_FLG);
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        //
        // LoginUserInfo
        // loginUserInfo=LoginUserInfoHolder.getInstance().getCurrentUser();
        // logService.saveOperLog("?",""+loginUserInfo.getEmpName()+"??cloudstack"+applyedHostResource.getHostNane()+BusinessEnvironment.OPER_RESULT_SUCCESS,
        // applyedHostResource, 2);
        // logger.info("???");
        // return true;
        // } else {LoginUserInfo loginUserInfo =
        // LoginUserInfoHolder.getInstance().getCurrentUser();
        // logService.saveOperLog("",""+loginUserInfo.getEmpName()+"??cloudstack"+applyedHostResource.getHostNane()+BusinessEnvironment.OPER_RESULT_FAILURE,
        // applyedHostResource, 2);
        // return false;
        // }
        return false;
    }

    public boolean startCS(Long applyResourceId) throws Exception, Throwable {
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        StartVirtualMachineRequest startVmRequest = new StartVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        startVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        startVmRequest.setId(applyedHostResource.getUuid());
        startVmRequest.setHostId(applyedHostResource.getTccPhysiscResourceInfo().getUuid());
        startVmRequest = (StartVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(startVmRequest);
        StartVirtualMachineResponse startVmResponse = (StartVirtualMachineResponse) TccCloudPlatUitls.getAdapte()
                .execute(startVmRequest);
        String jobStatus = asynQueryVmStatus(startVmResponse.getStartVirtualMachineResponse().getJobId(),
                this.queryPlatformByvmId(applyResourceId.toString()).getCloudplatformId().toString());
        if (SUCCESS.equals(jobStatus)) {// ?
            logService.saveOperLog("?", loginUserInfo.getEmpName() + BusinessEnvironment.OPER_TYPE_START_VM,
                    applyedHostResource, 2);
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
            vmAssistService.updateApplyedHostResource(applyedHostResource);

            logger.info("???");
            return true;
        } else {// 
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "?cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            logger.info("??");
            return false;
        }
    }

    public boolean startVC(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StartVirtualMachineRequest startVmRequest = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StartVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        startVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        startVmRequest.setName(applyedHostResource.getHostNane());
        startVmRequest = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StartVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(startVmRequest);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StartVirtualMachineResponse startVmResponse = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StartVirtualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(startVmRequest);
        Boolean isOK = startVmResponse.isResult();
        //?10 ??
        Thread.sleep(10 * 1000);
        if (isOK) {
            logger.info("VC??");
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
            vmAssistService.updateApplyedHostResource(applyedHostResource);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("?",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);
            return true;
        } else {
            logger.info("VC?");
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            return false;
        }
    }

    public boolean stopCS(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        StopVirtualMachineRequest stopVmRequest = new StopVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        stopVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        stopVmRequest.setId(applyedHostResource.getUuid());
        stopVmRequest = (StopVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(stopVmRequest);
        StopVirtualMachineResponse stopVmResponse = (StopVirtualMachineResponse) TccCloudPlatUitls.getAdapte()
                .execute(stopVmRequest);
        stopVmResponse.getStopVirtualMachineResponse();
        String jobStatus = asynQueryVmStatus(stopVmResponse.getStopVirtualMachineResponse().getJobId(),
                this.queryPlatformByvmId(applyResourceId.toString()).getCloudplatformId().toString());
        if (SUCCESS.equals(jobStatus)) {// ?
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
            vmAssistService.updateApplyedHostResource(applyedHostResource);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("?",
                    "" + loginUserInfo.getEmpName() + "?cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);
            logger.info("???");
            return true;
        } else { // 
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog(BusinessEnvironment.OPER_TYPE_STOP_VM,
                    "" + loginUserInfo.getEmpName() + "?cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "?cloudstack"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            logger.info("??");
            return false;
        }
    }

    @Override
    public boolean stopVC(Long applyResourceId) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest stopVmRequest = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        stopVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        stopVmRequest.setName(applyedHostResource.getHostNane());
        stopVmRequest = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(stopVmRequest);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StopVirtualMachineResponse stopVmResponse = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StopVirtualMachineResponse) TccCloudPlatUitls
                .getVmwareAdapte().execute(stopVmRequest);
        Boolean isOK = stopVmResponse.isResult();
        if (isOK) {
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
            vmAssistService.updateApplyedHostResource(applyedHostResource);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("?",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);

            return true;
        } else {
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            return false;
        }
    }

    @Override
    public boolean stopVC(Long applyResourceId, String srt) throws Exception, Throwable {
        TccApplyedHostResource applyedHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest stopVmRequest = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest();
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(applyResourceId + "");
        stopVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
        stopVmRequest.setName(applyedHostResource.getHostNane());
        stopVmRequest = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.request.StopVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(stopVmRequest);
        com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StopVirtualMachineResponse stopVmResponse = new com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StopVirtualMachineResponse();
        try {
            stopVmResponse = (com.sjc.adaptee.cloud.vmware.version51.module.virtualmachine.response.StopVirtualMachineResponse) TccCloudPlatUitls
                    .getVmwareAdapte().execute(stopVmRequest);
        } catch (Exception e) {
            //logger.debug("", e);
            return false;
        }
        Boolean isOK = stopVmResponse.isResult();
        if (isOK) {
            applyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
            vmAssistService.updateApplyedHostResource(applyedHostResource);
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("?",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                    applyedHostResource, 2);

            return true;
        } else {
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("",
                    "" + loginUserInfo.getEmpName() + "?vcenter"
                            + applyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_FAILURE,
                    applyedHostResource, 2);
            return false;
        }
    }

    public boolean modifyProgramCS(String vmId, String serviceOfferingId) throws Exception, Throwable {
        ChangeServiceForVirtualMachineRequest changeVmRequest = new ChangeServiceForVirtualMachineRequest();

        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(vmId + "");
        changeVmRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");

        changeVmRequest.setId(vmId);
        changeVmRequest.setServiceOfferingId(serviceOfferingId);
        changeVmRequest = (ChangeServiceForVirtualMachineRequest) TccCloudPlatUitls
                .setRequestParam(changeVmRequest);
        ChangeServiceForVirtualMachineResponse changeVmResponse = (ChangeServiceForVirtualMachineResponse) TccCloudPlatUitls
                .getAdapte().execute(changeVmRequest);
        com.sjc.adaptee.cloud.cloudstack.version43.module.virtualmachine.pojo.VirtualMachine vm = changeVmResponse
                .getChangeServiceForVirtualMachineResponse().getVirtualMachine();
        boolean flag = false;
        if (vm != null) {
            if (vm.getState().equals(operLogService.STOPPED)) {
                logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
                        BusinessEnvironment.OPER_TYPE_UPDATE, vm, 2);

                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + "vcenter"
                        + vm.getName() + BusinessEnvironment.OPER_RESULT_SUCCESS, vm, 2);
                flag = true;
            } else {
                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "vcenter"
                        + vm.getName() + BusinessEnvironment.OPER_RESULT_FAILURE, vm, 2);
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public void mountIsoCS(String isoId, String vmId) throws Exception {
        // AsyncjobRespId asyncjobRespId = csInvocator
        // .attachIso2Vm_CS(isoId, vmId);
        // // TODO
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
        // BusinessEnvironment.OPER_TYPE_MOUNT_VOLUME, asyncjobRespId, 2);
    }

    @Override
    public String openConsoleCS(Long applyResourceId) throws Exception {
        // TccApplyedHostResource applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyResourceId);
        // String url = csInvocator.getVmConsoleUrlbyId_CS(applyedHostResource
        // .getUuid());
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
        // BusinessEnvironment.OPER_TYPE_QUERY, applyedHostResource, 2);
        // return url;
        return "";
    }

    /**
     * CloudStack?
     */
    @Override
    public boolean moveVmWareCS(Long applyResourceId, String hostId) throws Exception {
        return false;
        //
        // TccApplyedHostResource applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyResourceId);
        // AsyncjobRespId asyncjobRespId = csInvocator.vMotion_CS(
        // applyedHostResource.getUuid(), hostId, "");
        //
        // // ???
        // if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_RUNNING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING_MIGRATING);
        // } else if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_STOP)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP_MIGRATING);
        // }
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        // applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyedHostResource
        // .getApplyResourceId());
        //
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_IN_PROCESS,
        // BusinessEnvironment.OPER_TYPE_MIGRATE_VM, applyedHostResource,
        // 2);
        //
        // String jobStatus = asynQueryVmStatus(asyncjobRespId.getJobid());
        //
        // if (SUCCESS.equals(jobStatus)) {// ?
        //
        // // 
        // TccPhysiscResourceInfo physiscResourceInfo = new
        // TccPhysiscResourceInfo();
        // physiscResourceInfo.setUuid(hostId);
        // List<TccPhysiscResourceInfo> physiscResourceInfoList =
        // vmAssistService
        // .getPhysiscResourceInfoList(physiscResourceInfo);
        // if (null != physiscResourceInfoList
        // && !physiscResourceInfoList.isEmpty()) {
        // if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_RUNNING_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
        // } else if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_STOP_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        // }
        // applyedHostResource
        // .setTccPhysiscResourceInfo(physiscResourceInfoList
        // .get(0));
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        // }
        //
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
        // BusinessEnvironment.OPER_TYPE_MIGRATE_VM,
        // applyedHostResource, 2);
        //
        // return true;
        // } else {// 
        // logger.info("CS??");
        // if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_RUNNING_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
        // } else if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_STOP_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        // }
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        //
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
        // BusinessEnvironment.OPER_TYPE_MIGRATE_VM,
        // applyedHostResource, 2);
        //
        // return false;
        // }
    }

    @Override
    public boolean moveVmWareVC(Long applyResourceId, String hostName) throws Exception {

        // TccApplyedHostResource applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyResourceId);
        // VCInvocator invocator = VCInvocator.getInstance(applyedHostResource
        // .getTccPhysiscResourceInfo().getTccCluster().getVcenter());
        //
        // // ?vCenter??,,??.,?.
        // // VirtualMachine vm =
        // // invocator.getVMbyName(applyedHostResource.getHostNane());
        // // if (vm.getRuntime().getPowerState() ==
        // // VirtualMachinePowerState.poweredOn) {
        // // boolean flag = stopVC(applyResourceId);
        // // if(!flag) return false;
        // // }
        //
        // // ???
        // if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_RUNNING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING_MIGRATING);
        // } else if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_STOP)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP_MIGRATING);
        // }
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        // applyedHostResource = vmAssistService
        // .getApplyedHostResource(applyedHostResource
        // .getApplyResourceId());
        // // System.out.println("?!");
        // Boolean isOK = invocator.vMotion(applyedHostResource.getHostNane(),
        // hostName);
        // // System.out.println("!");
        // // System.out.println(isOK);
        // if (isOK) {
        //
        // // 
        // TccPhysiscResourceInfo physiscResourceInfo = new
        // TccPhysiscResourceInfo();
        // physiscResourceInfo.setPhysicsIp(hostName);
        // List<TccPhysiscResourceInfo> physiscResourceInfoList =
        // vmAssistService
        // .getPhysiscResourceInfoList(physiscResourceInfo);
        // if (null != physiscResourceInfoList
        // && !physiscResourceInfoList.isEmpty()) {
        // if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_RUNNING_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
        // } else if (applyedHostResource.getRunStatusCd().equals(
        // BusinessEnvironment.VM_RUN_STATUS_STOP_MIGRATING)) {
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        // }
        // applyedHostResource
        // .setTccPhysiscResourceInfo(physiscResourceInfoList
        // .get(0));
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        // }
        //
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_SUCCESS,
        // BusinessEnvironment.OPER_TYPE_MIGRATE_VM,
        // applyedHostResource, 2);
        // } else {
        // // VC?????
        // applyedHostResource
        // .setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        // vmAssistService.updateApplyedHostResource(applyedHostResource);
        //
        // logService.saveOperLog(BusinessEnvironment.OPER_RESULT_FAILURE,
        // BusinessEnvironment.OPER_TYPE_MIGRATE_VM,
        // applyedHostResource, 2);
        // }

        return false;
    }

    /**
     * ?
     */
    @SuppressWarnings("unchecked")
    public boolean expandVm(Long srtApplyedhostAssId) throws Exception, Throwable {
        TccSrtApplyedhostAss srtApplyedhostAss = vmAssistService.getSrtApplyedhostAss(srtApplyedhostAssId);
        TccSrt srt = srtApplyedhostAss.getTccSrt();
        TccExpdCapacity expdCapacity = vmAssistService.getExpdCapacity(srt.getSrtId());
        TccApplyedHostinfo applyedHostinfo = srtApplyedhostAss.getTccApplyedHostinfo();
        TccApplyedHostResource applyedHostResource = vmAssistService
                .getApplyedHostResource(applyedHostinfo.getApplyResourceId());
        applyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_INSTALL); // 
        vmAssistService.updateApplyedHostResource(applyedHostResource);
        applyedHostResource = vmAssistService.getApplyedHostResource(applyedHostResource.getApplyResourceId());
        boolean flag = false;
        String VirtualType = applyedHostResource.getVirtualType();
        // ?
        // 01.VCVC?
        if (BusinessEnvironment.VIRTUAL_TYPE_VC.equals(VirtualType)) {
            flag = capacityMgmtService.upgradeVmVC(srt.getSrtId());
        }
        // 02.CSCS?
        else if (BusinessEnvironment.VIRTUAL_TYPE_CS.equals(VirtualType)) {
            flag = capacityMgmtService.upgradeVmCS(srt.getSrtId());// ?
        }
        if (!flag) {
            applyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_FAIL); // 
            vmAssistService.updateApplyedHostResource(applyedHostResource);
            return flag;
        }

        // ???
        TccApplyedHostResource newApplyedHostResource = new TccApplyedHostResource();
        BeanUtils.copyProperties(newApplyedHostResource, applyedHostResource);
        newApplyedHostResource.setCpuCoreCount(expdCapacity.getCpuCoreCount());
        newApplyedHostResource.setRamSize(expdCapacity.getRamSize());
        if (null != expdCapacity.getStoreSize()) {
            newApplyedHostResource.setStorageSize(newApplyedHostResource.getStorageSize() == null ? 0
                    : newApplyedHostResource.getStorageSize() + expdCapacity.getStoreSize());
        } else if (null != expdCapacity.getNasStoreSize()) {
            newApplyedHostResource.setNasStorageSize(newApplyedHostResource.getNasStorageSize() == null ? 0
                    : newApplyedHostResource.getNasStorageSize() + expdCapacity.getNasStoreSize());
        }
        newApplyedHostResource.setOrginResourceID(applyedHostResource.getOrginResourceID());
        newApplyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
        // ?
        newApplyedHostResource.setApplyResourceId(null);
        newApplyedHostResource.setLastuptDttm(null); // ?
        newApplyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_SUCCESS); // ??
        // ?
        newApplyedHostResource = vmAssistService.mergeApplyedHostResource(newApplyedHostResource);

        // ??
        applyedHostResource.setRunStatusCd(BusinessEnvironment.RESOURCE_RUNTYPE_EXPDEND);// ?
        applyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_SUCCESS);// ?
        applyedHostResource.setEnableFlg(EnvironmentConstant.DISENABLE); // 
        vmAssistService.updateApplyedHostResource(applyedHostResource);

        // ????
        srtApplyedhostAss.setTccApplyedHostinfo(newApplyedHostResource);
        vmAssistService.updateSrtApplyedhostAss(srtApplyedhostAss);
        // ?
        List<TccProjectAss> newProjectAssList = new ArrayList<TccProjectAss>();
        TccProjectAss newTccProjectAss = new TccProjectAss();

        // ??
        TccProjectAss projectAss = new TccProjectAss();
        projectAss.setTccApplyedHostinfo(applyedHostResource);

        // ***** by zhachaoy *****
        DetachedCriteria criteria = DetachedCriteria.forClass(TccProjectAss.class);
        if (null != projectAss && null != projectAss.getProjectAssId()) {
            criteria.add(Restrictions.eq("projectAssId", projectAss.getProjectAssId()));
        }
        if (null != projectAss && null != projectAss.getTccProjectInfo()) {
            criteria.add(Restrictions.eq("tccProjectInfo", projectAss.getTccProjectInfo()));
        }
        if (null != projectAss && null != projectAss.getTccApplyedHostinfo()) {
            criteria.add(Restrictions.eq("tccApplyedHostinfo", projectAss.getTccApplyedHostinfo()));
        }
        // ?1
        criteria.add(Restrictions.or(Restrictions.eq("enableFlg", EnvironmentConstant.ENABLE),
                Restrictions.isNull("enableFlg")));

        List<TccProjectAss> projectAssList = commonDao.findByCriteria(criteria);
        // ##### by zhachaoy #####

        for (TccProjectAss pa : projectAssList) {
            // ?
            BeanUtils.copyProperties(newTccProjectAss, pa);
            newTccProjectAss.setProjectAssId(null);
            newTccProjectAss.setTccInstanceInfo(null);
            newTccProjectAss.setTccApplyedHostinfo(newApplyedHostResource);
            newProjectAssList.add(newTccProjectAss);
            pa.setEnableFlg(EnvironmentConstant.DISENABLE);
        }
        vmAssistService.updateProjectAssList(projectAssList);
        // ??
        this.commonDao.saveOrUpdateAll(newProjectAssList);

        // 
        List<Object> list = snapshotCategoryService
                .getVmSnapshotCategory(applyedHostResource.getApplyResourceId().toString());
        List<TccSnapshotCfg> tccSnapshotCfgsList = null;
        List<TccSnapshotHistory> tccSnapshotHistories = null;
        if (list != null && list.size() > 0) {
            for (int k = 0; k < list.size(); k++) {
                if (k == 0) {
                    // ??
                    tccSnapshotCfgsList = (List<TccSnapshotCfg>) list.get(0);
                } else if (k == 1) {
                    // ?
                    tccSnapshotHistories = (List<TccSnapshotHistory>) list.get(1);
                }
            }
            // ?resourceId? ?resourceId?
            if (tccSnapshotCfgsList != null && tccSnapshotCfgsList.size() > 0) {
                for (TccSnapshotCfg sc : tccSnapshotCfgsList) {
                    sc.setHostId(newApplyedHostResource.getApplyResourceId());
                    this.commonDao.saveOrUpdate(sc);
                }
            }
            if (tccSnapshotHistories != null && tccSnapshotHistories.size() > 0) {
                // ??resourceId? ?resourceId?
                for (TccSnapshotHistory sh : tccSnapshotHistories) {
                    sh.setVmId(newApplyedHostResource.getApplyResourceId());
                    this.commonDao.saveOrUpdate(sh);
                }
            }

        }
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        logService.saveOperLog("?",
                "" + loginUserInfo.getEmpName() + "cloudstack"
                        + newApplyedHostResource.getHostNane() + BusinessEnvironment.OPER_RESULT_SUCCESS,
                newApplyedHostResource, 2);
        return true;
    }

    @Override
    public boolean expandMinicomputer(Long srtApplyedhostAssId) throws Exception, Throwable {

        TccSrtApplyedhostAss srtApplyedhostAss = vmAssistService.getSrtApplyedhostAss(srtApplyedhostAssId);
        TccSrt srt = srtApplyedhostAss.getTccSrt();
        TccExpdCapacity expdCapacity = vmAssistService.getExpdCapacity(srt.getSrtId());

        TccApplyedHostinfo applyedHostinfo = srtApplyedhostAss.getTccApplyedHostinfo();
        TccApplyedHostResource applyedHostResource = vmAssistService
                .getApplyedHostResource(applyedHostinfo.getApplyResourceId());

        applyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_SUCCESS); // ?
        vmAssistService.updateApplyedHostResource(applyedHostResource);
        applyedHostResource = vmAssistService.getApplyedHostResource(applyedHostResource.getApplyResourceId());

        // ???
        TccApplyedHostResource newApplyedHostResource = new TccApplyedHostResource();
        BeanUtils.copyProperties(newApplyedHostResource, applyedHostResource);
        // /CPU????????
        if (expdCapacity.getCpuCoreCount() > newApplyedHostResource.getCpuCoreCount()) {
            newApplyedHostResource.setCpuCoreCount(expdCapacity.getCpuCoreCount());
        }
        if (expdCapacity.getRamSize() > newApplyedHostResource.getRamSize()) {
            newApplyedHostResource.setRamSize(expdCapacity.getRamSize());
        }
        if (null != expdCapacity.getStoreSize()) {
            newApplyedHostResource.setStorageSize(newApplyedHostResource.getStorageSize() == null ? 0
                    : newApplyedHostResource.getStorageSize() + expdCapacity.getStoreSize());
        } else if (null != expdCapacity.getNasStoreSize()) {
            newApplyedHostResource.setNasStorageSize(newApplyedHostResource.getNasStorageSize() == null ? 0
                    : newApplyedHostResource.getNasStorageSize() + expdCapacity.getNasStoreSize());
        }
        newApplyedHostResource.setOrginResourceID(applyedHostResource.getOrginResourceID());
        if (applyedHostResource.getRunStatusCd().equals(BusinessEnvironment.RESOURCE_RUNTYPE_RUNCAPACITY)) {
            newApplyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_RUNNING);
        } else if (applyedHostResource.getRunStatusCd().equals(BusinessEnvironment.RESOURCE_RUNTYPE_STOPCAPACITY)) {
            newApplyedHostResource.setRunStatusCd(BusinessEnvironment.VM_RUN_STATUS_STOP);
        }
        // ?
        newApplyedHostResource.setApplyResourceId(null);
        newApplyedHostResource.setLastuptDttm(null); // ?
        newApplyedHostResource.setProcessStatus(null); // ??
        // ?
        newApplyedHostResource = vmAssistService.mergeApplyedHostResource(newApplyedHostResource);

        // ??
        applyedHostResource.setRunStatusCd(BusinessEnvironment.RESOURCE_RUNTYPE_EXPDEND);// ?
        applyedHostResource.setProcessStatus(BusinessEnvironment.RESOURCE_TYPE_SUCCESS);// ?
        applyedHostResource.setEnableFlg(EnvironmentConstant.DISENABLE); // 
        vmAssistService.updateApplyedHostResource(applyedHostResource);

        // ????
        srtApplyedhostAss.setTccApplyedHostinfo(newApplyedHostResource);
        vmAssistService.updateSrtApplyedhostAss(srtApplyedhostAss);

        // ?
        List<TccProjectAss> newProjectAssList = new ArrayList<TccProjectAss>();
        TccProjectAss newTccProjectAss = new TccProjectAss();

        // ??
        TccProjectAss projectAss = new TccProjectAss();
        projectAss.setTccApplyedHostinfo(applyedHostResource);
        List<TccProjectAss> projectAssList = vmAssistService.getProjectAssList(projectAss);
        for (TccProjectAss pa : projectAssList) {
            // ?
            BeanUtils.copyProperties(newTccProjectAss, pa);
            newTccProjectAss.setProjectAssId(null);
            newTccProjectAss.setTccInstanceInfo(null);
            newTccProjectAss.setEnableFlg(EnvironmentConstant.DISENABLE);
            newProjectAssList.add(newTccProjectAss);
            // ???
            pa.setTccApplyedHostinfo(newApplyedHostResource);
        }
        vmAssistService.updateProjectAssList(projectAssList);
        // ??
        this.commonDao.saveOrUpdateAll(newProjectAssList);

        // ???
        LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
        logService.saveOperLog(
                BusinessEnvironment.OPER_RESULT_SUCCESS, loginUserInfo.getEmpName()
                        + BusinessEnvironment.OPER_TYPE_ADD_VM + newApplyedHostResource.getHostNane(),
                newApplyedHostResource, 2);

        return true;
    }

    @Override
    public TccInstanceInfo expandInstance(ResrcExpdVO resrcExpdVO) throws Exception {
        return null;
    }

    private TccProjectAss getTccProjectAss(long newIpAddressId, long instanceInfoId) throws Exception {
        TccProjectAss newTccProjectAss = new TccProjectAss();
        TccInstanceInfo tccInstanceInfo = (TccInstanceInfo) this.commonDao.get(TccInstanceInfo.class,
                instanceInfoId);
        // ?IP?Id?IP?
        TccApplyedHostResource tccApplyedHostResource = new TccApplyedHostResource();
        TccIpConfigInfo tccIpConfigInfo = (TccIpConfigInfo) this.commonDao.get(TccIpConfigInfo.class,
                newIpAddressId);
        tccApplyedHostResource.setTccIpConfigInfo(tccIpConfigInfo);
        List<TccApplyedHostResource> list = vmAssistService.getApplyedHostResourceList(tccApplyedHostResource);
        if (null != list && list.size() > 0) {
            tccApplyedHostResource = list.get(0);
        } else {
            throw new ApplicationException("?IP???");
        }
        Hibernate.initialize(tccInstanceInfo.getTccProjectAss());
        TccProjectAss tccProjectAss = tccInstanceInfo.getTccProjectAss();
        Hibernate.initialize(tccProjectAss.getTccProjectInfo());
        // ?
        TccProjectInfo tccProjectInfo = tccProjectAss.getTccProjectInfo();
        // ?? ?
        newTccProjectAss.setTccApplyedHostinfo(tccApplyedHostResource);
        newTccProjectAss.setTccProjectInfo(tccProjectInfo);
        List<TccProjectAss> listAss = vmAssistService.getProjectAssList(newTccProjectAss);
        if (null != listAss && listAss.size() > 0) {
            newTccProjectAss = listAss.get(0);
        }
        // ?
        else {
            newTccProjectAss = vmAssistService.mergeProjectAss(tccApplyedHostResource, tccProjectInfo);
        }
        return newTccProjectAss;
    }

    @Override
    public VmInfo getVmInfo(String ip, String name, String password, Long applyResourceId) throws Exception {
        VmInfo vmInfo = new VmInfo();
        vmInfo = getVmInfo(vmInfo, ip, name, password);
        vmInfo = getVmInfo(vmInfo, applyResourceId);
        return vmInfo;
    }

    @Override
    public VmInfo getVmInfo(Long applyResourceId) throws Exception {
        logger.info("pass by");
        return getVmInfo(new VmInfo(), applyResourceId);
    }

    @Override
    public VmInfo getVmInfo(String ip, String name, String password) {
        return getVmInfo(new VmInfo(), ip, name, password);
    }

    /**
     * ?CPU??shell?ip?????
     * 
     * @param vmInfo
     * @param ip
     * @param name
     * @param password
     * @return
     */
    private VmInfo getVmInfo(VmInfo vmInfo, String ip, String name, String password) {
        logger.debug("??");
        String assignedCpu = "";
        String assignedMemory = "";
        String assignedStorage = "";
        try {
            // assignedCpu = hostSysInfoService.getHostCpuUsage(ip, name,
            // password);
            // assignedMemory = hostSysInfoService.getHostMemoryUsed(ip, name,
            // password);
            // assignedStorage =
            // hostSysInfoService.getHostStorageUsePercentage(ip, name,
            // password);

            logger.debug("CPU" + assignedCpu);
            logger.debug("MEM" + assignedMemory);
            logger.debug("" + assignedStorage);
        } catch (Exception e) {
            assignedCpu = "0";
            assignedMemory = "0";
            assignedStorage = "0%";
            logger.info("shell?CPU??", e);
        }
        vmInfo.setAssignedCpu(assignedCpu + "%");
        vmInfo.setAssignedMemory(InstanceUtils.round(new Double(assignedMemory) * 100, 2) + "%");
        vmInfo.setAssignedStorage(assignedStorage);
        return vmInfo;
    }

    /**
     * ??
     * 
     * @param applyResourceId
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private VmInfo getVmInfo(VmInfo vmInfo, Long applyResourceId) throws Exception {
        logger.debug(",ID:" + applyResourceId);
        TccApplyedHostResource applyHostResource = vmAssistService.getApplyedHostResource(applyResourceId);
        TccProjectInfo projectInfo = vmAssistService.getProjectInfo(applyHostResource);
        TccOrgan tccOrgan = null;
        TccEmployee employee = null;
        if (null != projectInfo) {
            tccOrgan = vmAssistService.getOrgan(projectInfo.getProjectId());
            employee = vmAssistService.getEmployeeByProjectId(projectInfo.getProjectId());
        } else {
            // TODO what
        }
        TccProjectAss projectAss = vmAssistService.getProjectAss(applyHostResource);
        TccInstanceInfo instanceInfo = null;
        // if (null != projectAss) {
        // instanceInfo = vmAssistService.getInstanceInfo(projectAss);
        // }

        Map<String, String> optionMap = applicationCacheService.getCacheList("100");
        Map<String, Object> usageMap = hostService
                .getUsageById(String.valueOf(applyHostResource.getApplyResourceId()));
        if (usageMap != null) {
            logger.debug("CPU:" + (String) usageMap.get("cpuUsage"));
            logger.debug("MEM:" + (String) usageMap.get("memUsage"));
            vmInfo.setAssignedCpu((String) usageMap.get("cpuUsage"));
            vmInfo.setAssignedMemory((String) usageMap.get("memUsage"));
            // vmInfo.setAssignedStorage(assignedStorage);
        }
        vmInfo.setVmId(applyHostResource.getUuid());
        vmInfo.setVmName(applyHostResource.getHostNane());
        vmInfo.setVmip(applyHostResource.getIpAddress());
        vmInfo.setApplyResourceId(applyHostResource.getApplyResourceId().toString());
        if (applyHostResource.getRunStatusCd().equalsIgnoreCase("01"))
            vmInfo.setRunStatus("?"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("02"))
            vmInfo.setRunStatus("?"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("03"))
            vmInfo.setRunStatus("????"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("04"))
            vmInfo.setRunStatus("??,??"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("05"))
            vmInfo.setRunStatus("??,??"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("06"))
            vmInfo.setRunStatus("??,??"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("07"))
            vmInfo.setRunStatus("?"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("08"))
            vmInfo.setRunStatus("?"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("09"))
            vmInfo.setRunStatus("??,???"); // ?
        else if (applyHostResource.getRunStatusCd().equalsIgnoreCase("10"))
            vmInfo.setRunStatus("??,???"); // ?

        vmInfo.setVirtualType(applyHostResource.getVirtualType());
        vmInfo.setSystemType(MapUtils.get(optionMap, applyHostResource.getOsVersionCd()));
        vmInfo.setCpuTotal(String.valueOf(applyHostResource.getCpuCoreCount()));// CPU
        vmInfo.setMemoryTotal(String.valueOf(applyHostResource.getRamSize()));// 
        vmInfo.setHostId(applyHostResource.getTccPhysiscResourceInfo().getResourceId() + "");
        vmInfo.setHostName(applyHostResource.getTccPhysiscResourceInfo().getPhysicsName() + "");
        vmInfo.setHostIp(applyHostResource.getTccPhysiscResourceInfo().getPhysicsIp() + "");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(
                "SELECT DISTINCT d.zone_name FROM T_CC_APPLYED_HOST_RESOURCE t INNER JOIN T_CC_PHYSISC_RESOURCE_INFO  p ON  ");
        stringBuffer.append(
                "t.resource_Id= p.resource_id  INNER JOIN T_CC_CLOUD_DATACENTER d ON d.zone_id=p.zoneid WHERE t.APPLY_RESOURCE_ID='"
                        + vmInfo.getApplyResourceId() + "'");
        List<Object> listPod = (List<Object>) this.commonDao.findBySql(stringBuffer.toString(), null, -1, -1);
        if (listPod != null) {
            vmInfo.setPods(String.valueOf(listPod.get(0)));
        }
        if (applyHostResource.getTccPhysiscResourceInfo() != null
                && applyHostResource.getTccPhysiscResourceInfo().getTccCluster() != null) {
            vmInfo.setClusterId(applyHostResource.getTccPhysiscResourceInfo().getTccCluster().getId() + ""); // ?ID
            vmInfo.setClusters(applyHostResource.getTccPhysiscResourceInfo().getTccCluster().getClusterName()); // ???,?vCenter?
        } else {
            vmInfo.setClusterId(null);
            vmInfo.setClusters(null);
        }
        vmInfo.setRemarks(applyHostResource.getMemo());

        if (null != tccOrgan) { // 
            vmInfo.setDepartment(tccOrgan.getPartyFullname());
        }
        if (null != employee) { // 
            vmInfo.setMangment(employee.getAccountNo());
        }
        String HardwareTypeCd = applyHostResource.getTccPhysiscResourceInfo().getHardwareTypeCd();
        String DeviceTypeName = applicationCacheService.getMapValue("168", HardwareTypeCd);// ????
        vmInfo.setDeviceType(DeviceTypeName);

        if (null != projectInfo) {
            vmInfo.setProject(projectInfo.getProjectName());
            vmInfo.setAppType(projectInfo.getDataFlag());
            vmInfo.setApplicationTime(projectInfo.getProjecgBeginDttm() == null ? ""
                    : projectInfo.getProjecgBeginDttm() + "-"
                            + (projectInfo.getProjecgEndDttm() == null ? "" : projectInfo.getProjecgEndDttm()));
        }

        vmInfo.setBuildTime(DateUtil.dateToString(applyHostResource.getCrtDttm(), DateUtil.DEFAULT_FORMAT));

        logger.debug("?");
        return vmInfo;
    }

    /**
     * ********************************??*******************************
     * ****
     */
    /**
     * cloudstack
     */
    public synchronized Map<String, String> CloneVm(Long assId, Long copyHostId, String clusterId,
            TccProjectInfo tccProjectInfo, String vmName, String vlanUuId) throws Exception, Throwable {
        TccConfigAssApplycase ass = (TccConfigAssApplycase) configAssApplyCaseService.getConfigAssApplyCase(assId);
        TccApplyedHostinfo host = (TccApplyedHostinfo) this.commonDao.get(TccApplyedHostinfo.class, copyHostId);
        // ?
        ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTING);
        configAssApplyCaseService.updateConfigAssApplyCase(ass);
        if (StringUtils.isNotBlank(tccProjectInfo.getSanStorageSize())) {
            ass.setSanStorageSize(tccProjectInfo.getSanStorageSize());
        } else {
            ass.setSanStorageSize("0");
        }
        TccCloudplatform tcccloudplatform = this.queryPlatformByvmId(host.getApplyResourceId() + "");
        if (StringUtils.isNotBlank(tccProjectInfo.getNasStorageSize())) {
            ass.setNasStorageSize(tccProjectInfo.getNasStorageSize());
        } else {
            ass.setNasStorageSize("0");
        }
        /*
         * ???ID ??
         */
        TccClusterConfig clusterConfig = vmAssistService.getClusterConfig(Long.parseLong(clusterId));
        try {
            List<Map<String, Object>> vlanList = (List<Map<String, Object>>) this.commonDao.querySqlByJdbcTpl(
                    "select a.ID as vlanId from  T_CC_VLAN_NETWORK a "
                            + "join T_CC_PROJECT_INFO b on a.SYS_ID=b.PROJECT_ID where  a.SYS_ID="
                            + tccProjectInfo.getProjectId() + " and a.UUID='" + vlanUuId + "' ",
                    new ArrayList<Object>(), null);
            if (vlanList != null && vlanList.size() > 0) {
                Map<String, Object> rs = (Map<String, Object>) vlanList.get(0);
                ass.setVlanId(Long.valueOf(String.valueOf(rs.get("vlanId"))));
            }
        } catch (Exception ex) {
            logger.error("VLANID" + ex);
            String error = "VLANID";
            Map<String, String> errorMsg = new HashMap<String, String>();
            errorMsg.put("SUCCESS", "false");
            errorMsg.put("msg", error);
            return errorMsg;
        }
        ass.setVrSubType(clusterConfig.getVtype());

        Map<String, String> errorMsg = new HashMap<String, String>();
        if (vmName != null && !vmName.equals("")) {
            boolean flag = vmAssistService.checkDuplVmName(vmName);
            if (flag == false) {
                String error = "????";
                logger.error(error);
                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg", error);
                return errorMsg;
            }
        }
        try {
            // ?uuid,?,??id,Id
            // String vmid,String name,String hostId,String networkId
            TccCloudDatacenter dc = (TccCloudDatacenter) commonDao.get(TccCloudDatacenter.class,
                    Long.valueOf(clusterConfig.getZoneId()));
            String jobId = CloneVmService.CloneVm(host.getUuid(), vmName, null, vlanUuId,
                    this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString(), dc);
            String jobStatus = asynQueryVmStatus(jobId,
                    this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());

            if (SUCCESS.equals(jobStatus)) {
                errorMsg.put("SUCCESS", "true");
                errorMsg.put("msg", "?[" + vmName + "]");
                VirtualMachine vmVo = cloudStackService.getVmInfoCS(jobId,
                        this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());

                String serviceOfferingId = vmVo.getServiceOfferingId();
                // ?
                String storageType = "";
                ListServiceOfferingsRequest cmd1 = new ListServiceOfferingsRequest();
                cmd1.setCloud(this.queryPlatformByClusterId(clusterId).getCloudplatformId() + "");
                cmd1.setId(serviceOfferingId);
                cmd1.setIsSystem("false");
                cmd1 = (ListServiceOfferingsRequest) TccCloudPlatUitls.setRequestParam(cmd1);
                ListServiceOfferingsResponse findserviceOfferResponse = (ListServiceOfferingsResponse) TccCloudPlatUitls
                        .getAdapte().execute(cmd1);
                List<ServiceOffering> findserviceofferingVoArr = findserviceOfferResponse
                        .getListServiceOfferingsResponse().getServiceOffering();
                if (findserviceofferingVoArr != null && findserviceofferingVoArr.size() > 0) {
                    for (ServiceOffering vo : findserviceofferingVoArr) {
                        storageType = vo.getStorageType();
                    }
                }

                String ip = vmVo.getNic().get(0).getIpAddress();
                StringBuffer updateSql = new StringBuffer();
                updateSql.append(
                        "UPDATE T_CC_IP_CONFIG_INFO f SET f.USED_FLAG='1' WHERE f.IP_ADDRESS ='" + ip + "'");
                commonDao.updateByNativeSql(updateSql.toString());

                String volumeOfferingId = "";
                try {
                    // ?UUID7
                    // SAN??
                    if (ass.getSanStorageSize() != null && !ass.getSanStorageSize().equals("0")
                            && Long.valueOf(ass.getSanStorageSize()).intValue() > 0) {
                        // ????
                        TccSysStoreCase ssc = new TccSysStoreCase();
                        ssc.setStoreCaseName(
                                ass.getTccSetMealConfig().getTccPluginStoreCase().getPluginStoreCaseName());
                        ssc.setStoreSize(Long.valueOf(ass.getSanStorageSize()));
                        ssc.setMomo(ass.getTccSetMealConfig().getTccPluginStoreCase().getMomo());
                        ssc = storageService.mergeSysStoreCase(ssc,
                                this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString(),
                                storageType);

                        volumeOfferingId = volumeService.createVolumeCS(vmName + "D01", ass.getSanStorageSize(),
                                ssc.getDiskOfferingId(), vmVo.getZoneId());

                        boolean attachFlag = volumeService.attachVolumeCS(volumeOfferingId, vmVo.getId(),
                                this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
                        ass.setAttachFlag(attachFlag);
                        if (attachFlag) {
                            logService.saveOperLog("?", vmName + "?" + vmName + "D01"
                                    + BusinessEnvironment.OPER_RESULT_SUCCESS, ass, 2);
                        } else {
                            logService.saveOperLog("", vmName + "?" + vmName + "D01"
                                    + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
                        }
                    }
                } catch (Exception e) {
                    DestroyVirtualMachineRequest request = new DestroyVirtualMachineRequest();

                    request.setCloud(tcccloudplatform.getCloudplatformId() + "");
                    request.setId(vmVo.getId());
                    request = (DestroyVirtualMachineRequest) TccCloudPlatUitls.setRequestParam(request);
                    DestroyVirtualMachineResponse response = (DestroyVirtualMachineResponse) TccCloudPlatUitls
                            .getAdapte().execute(request);
                    String jobStatus_tmp = asynQueryVmStatus(response.getDestroyVirtualMachineResponse().getJobId(),
                            this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString());
                    if (SUCCESS.equals(jobStatus_tmp)) {
                        e.printStackTrace();
                        errorMsg.put("SUCCESS", "false");
                        errorMsg.put("msg", "?IO???");
                    }
                    return errorMsg;
                }
                // 
                HostMonitorBean hostinfo = new HostMonitorBean();
                hostinfo.setHostName(vmVo.getNic().get(0).getIpAddress());
                hostinfo.setIp(vmVo.getNic().get(0).getIpAddress());
                OsListRequest osRequest = new OsListRequest();
                osRequest.setCloud(tcccloudplatform.getCloudplatformId() + "");
                osRequest = (OsListRequest) TccCloudPlatUitls.setRequestParam(osRequest);
                OsListResponse osListResponse = (OsListResponse) TccCloudPlatUitls.getAdapte().execute(osRequest);
                String osDescription = "";
                if (osListResponse.getListostypesresponse().getCount() > 0) {
                    for (OS osType : osListResponse.getListostypesresponse().getOstype()) {
                        if (osType.equals(vmVo.getGroupId())) {
                            osDescription = osType.getDescription();
                        }
                    }
                }
                if (osDescription.contains("windows") || osDescription.contains("windows")) {
                    hostinfo.setOsName("windows");
                } else {
                    hostinfo.setOsName("linux");
                }
                // linux,windows
                hostinfo.setPort("10050");
                hostinfo.setStatus(0);//
                hostinfo.setMonitorType(1);
                try {
                    zabbixApiService.addHostToMonitor(hostinfo);
                } catch (Exception ex) {
                    this.logger.error("?", ex);
                }
                // ?
                ass.setOsType(hostinfo.getOsName());

                // ?(????)
                new DeleteTemplateThread(vmVo.getTemplateId(), vmVo.getZoneId(),
                        this.queryPlatformByClusterId(clusterId).getCloudplatformId().toString()).start();
                // ?????
                TccSrt srt = vmAssistService.getSrt(ass.getTccSrt().getSrtId());
                TccApplyedHostResource applyedHostResource = vmAssistService.mergeApplyedHostResource(vmVo, ass, "",
                        volumeOfferingId);
                vmAssistService.saveSrtApplyedhostAss(applyedHostResource, srt);

                applyedHostResource.setHardwareTypeCd("186");

                ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTSUCC);
                configAssApplyCaseService.updateConfigAssApplyCase(ass);

                // CPU?MEM?
                capacityMgmtService.takingCpuRam(applyedHostResource.getTccPhysiscResourceInfo(),
                        ass.getTccSetMealConfig().getTccConfigCase().getCpuCoreCount(),
                        ass.getTccSetMealConfig().getTccConfigCase().getRamSize());

                // ??
                TccProjectInfo projectInfo = tccProjectInfo;
                vmAssistService.saveProjectAss(applyedHostResource, projectInfo);

                // ??????IP_??_?10.10.11.13__?

                // String projectName =
                // URLEncoder.encode(projectInfo.getProjectName(), "UTF-8");
                String displayName = vmName;

                // csInvocator.updateVm_CS(vmVo.getId(), displayName);

                TccApplyedHostResource ahr = vmAssistService
                        .getApplyedHostResource(applyedHostResource.getApplyResourceId());
                ahr.setHostNane(displayName);
                // ??
                ahr.setTemplateId(host.getTemplateId());
                // ?
                ahr.setClusterId(clusterId);
                vmAssistService.updateApplyedHostResource(ahr);

                // ???snapshotcategory?
                TccSnapshotCfg snapshotCfg = new TccSnapshotCfg();
                snapshotCfg.setCrtDttm(new Date());
                Set<TccApplyedHostinfo> tccApplyedHostinfos = ass.getTccApplyedHostinfos();
                for (TccApplyedHostinfo temp : tccApplyedHostinfos) {
                    snapshotCfg.setCrtUserId(temp.getCrtUserId() + "");
                    break;
                }
                snapshotCfg.setCrtUserId(String.valueOf(srt.getCrtUserId()));
                snapshotCfg.setShotMaxNum(0L);
                snapshotCfg.setHostId(ahr.getApplyResourceId());
                snapshotCfg.setVmName(displayName);
                snapshotCfg.setEnableFlg("1");
                snapshotCategoryService.AddSnapshotCategory(snapshotCfg);

                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("?", "" + loginUserInfo.getEmpName()
                        + "cloudstack" + vmName + BusinessEnvironment.OPER_RESULT_SUCCESS, ass, 2);
                errorMsg.put("SUCCESS", "true");

            } else {// 

                LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
                logService.saveOperLog("", "" + loginUserInfo.getEmpName()
                        + "cloudstack" + vmName + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
                ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
                configAssApplyCaseService.updateConfigAssApplyCase(ass);
                logger.error(errorMsg);
                errorMsg.put("SUCCESS", "false");
                errorMsg.put("msg", "[" + vmName + "]" + errorMsg);
            }
        } catch (Exception e) {
            LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
            logService.saveOperLog("", "" + loginUserInfo.getEmpName() + "cloudstack"
                    + vmName + BusinessEnvironment.OPER_RESULT_FAILURE, ass, 2);
            ass.setSetupStats(BusinessEnvironment.SETUP_STATS_INSTFAIL);// ?
            configAssApplyCaseService.updateConfigAssApplyCase(ass);
            e.printStackTrace();
            logger.error(e);
            errorMsg.put("SUCCESS", "false");
            errorMsg.put("msg", "[" + vmName + "]" + e.getMessage());
        }
        return errorMsg;

    }

    class RemoveCloneTemplate implements Runnable {
        private String templateId;
        private String zoneId;

        RemoveCloneTemplate(String templateId) {
            this.templateId = templateId;
        }

        public void run() {
            try {
                DeleteTemplateRequest deleteTemplateRequest = new DeleteTemplateRequest();
                deleteTemplateRequest.setCloud(Target.CLOUDSTACK);
                deleteTemplateRequest.setId(templateId);
                deleteTemplateRequest.setZoneid(zoneId);
                deleteTemplateRequest = (DeleteTemplateRequest) TccCloudPlatUitls
                        .setRequestParam(deleteTemplateRequest);
                TccCloudPlatUitls.getAdapte().execute(deleteTemplateRequest);
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }

        public String getTemplateId() {
            return templateId;
        }

        public void setTemplateId(String templateId) {
            this.templateId = templateId;
        }

        public String getZoneId() {
            return zoneId;
        }

        public void setZoneId(String zoneId) {
            this.zoneId = zoneId;
        }

    }

    /***************************************************************************
     * ?? t_cc_apply_hostinfo monitorflg ? null null?? 0 
     * 1 ?
     * 
     * @return
     */

    public boolean updateHostMonitorFlgByName(String hostName, String flg) {
        boolean result = false;
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("UPDATE T_CC_APPLYED_HOSTINFO SET MONITOR_FLG = " + flg + " WHERE  HOST_NANE = '"
                + hostName + "' ");
        if (commonDao.updateByNativeSql(sqlBuffer.toString()) > 0) {
            result = true;
        }
        return result;
    }

    public CloudStackService getCloudStackService() {
        return cloudStackService;
    }

    public void setCloudStackService(CloudStackService cloudStackService) {
        this.cloudStackService = cloudStackService;
    }

    public ConfigAssApplyCaseService getConfigAssApplyCaseService() {
        return configAssApplyCaseService;
    }

    public void setConfigAssApplyCaseService(ConfigAssApplyCaseService configAssApplyCaseService) {
        this.configAssApplyCaseService = configAssApplyCaseService;
    }

    public CapacityMgmtService getCapacityMgmtService() {
        return capacityMgmtService;
    }

    public void setCapacityMgmtService(CapacityMgmtService capacityMgmtService) {
        this.capacityMgmtService = capacityMgmtService;
    }

    public VmAssistService getVmAssistService() {
        return vmAssistService;
    }

    public void setVmAssistService(VmAssistService vmAssistService) {
        this.vmAssistService = vmAssistService;
    }

    public StorageService getStorageService() {
        return storageService;
    }

    public void setStorageService(StorageService storageService) {
        this.storageService = storageService;
    }

    public VolumeService getVolumeService() {
        return volumeService;
    }

    public void setVolumeService(VolumeService volumeService) {
        this.volumeService = volumeService;
    }

    public ApplicationCacheService getApplicationCacheService() {
        return applicationCacheService;
    }

    public void setApplicationCacheService(ApplicationCacheService applicationCacheService) {
        this.applicationCacheService = applicationCacheService;
    }

    public HostService getHostService() {
        return hostService;
    }

    public void setHostService(HostService hostService) {
        this.hostService = hostService;
    }

    public SnapshotCategoryService getSnapshotCategoryService() {
        return snapshotCategoryService;
    }

    public void setSnapshotCategoryService(SnapshotCategoryService snapshotCategoryService) {
        this.snapshotCategoryService = snapshotCategoryService;
    }

    public HignNetworkService getHignNetworkService() {
        return hignNetworkService;
    }

    public void setHignNetworkService(HignNetworkService hignNetworkService) {
        this.hignNetworkService = hignNetworkService;
    }

    public VmSnapshotService getVmSnapshotService() {
        return vmSnapshotService;
    }

    public void setVmSnapshotService(VmSnapshotService vmSnapshotService) {
        this.vmSnapshotService = vmSnapshotService;
    }

    public OperLogService getOperLogService() {
        return operLogService;
    }

    public void setOperLogService(OperLogService operLogService) {
        this.operLogService = operLogService;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public MealService getMealService() {
        return mealService;
    }

    public void setMealService(MealService mealService) {
        this.mealService = mealService;
    }

    @Override
    public Map<String, String> getVmPlatformInfo(Long vmId) {
        StringBuilder sql = new StringBuilder(
                "SELECT PLATFORM.CLOUDPLATFORM_IP ip, PLATFORM.CLOUDPLATFORM_USER username, ");
        sql.append(" PLATFORM.CLOUDPLATFORM_PASSWORD password, PLATFORM.CLOUDPLATFORM_KEY platformKey ");
        sql.append(" FROM T_CC_APPLYED_HOSTINFO HOST ");
        sql.append(" LEFT JOIN T_CC_CLOUD_DATACENTER DATACENTER ON HOST.ZONEID = DATACENTER.ZONE_ID ");
        sql.append(
                " LEFT JOIN T_CC_CLOUDPLATFORM PLATFORM ON DATACENTER.CLOUDPLATFORM_ID = PLATFORM.CLOUDPLATFORM_ID ");
        sql.append(" WHERE HOST.APPLY_RESOURCE_ID = ? ");

        List<Map<String, Object>> platInfoList = commonDao.findAsMapList(sql.toString(), new Object[] { vmId });
        if (platInfoList != null && platInfoList.size() > 0) {
            Map<String, String> map = new HashMap<String, String>();
            for (Entry<String, Object> entry : platInfoList.get(0).entrySet()) {
                map.put(entry.getKey(), (String) entry.getValue());
            }
            return map;
        }

        return null;
    }

    public HostMonitorAlarmApiService getZabbixApiService() {
        return zabbixApiService;
    }

    public void setZabbixApiService(HostMonitorAlarmApiService zabbixApiService) {
        this.zabbixApiService = zabbixApiService;
    }

}