Exemple #1
0
  /**
   * 克隆虚拟机,CloneVM_Task<br>
   * <br>
   * 是否转换为模板
   *
   * @param resultMap
   * @param url
   * @param username
   * @param password
   * @param dcId
   * @param vmMor
   * @param cloneName
   * @param isTemplate
   * @param rpId
   * @return
   */
  private static void cloneVM(
      HashMap<String, Object> resultMap,
      String url,
      String username,
      String password,
      String dcId,
      ManagedObjectReference vmMor,
      String cloneName,
      boolean isTemplate,
      String rpId) {
    try {
      VIMCache cache = VIMCache.getInstance(url, username, password);

      ManagedObjectReference dcMor = cache.getDatacenter(dcId);
      // ManagedObjectReference vmMor = cache.getVirtualMachine(vmId);
      ManagedObjectReference vmFolderMor = cache.getVMFolder(dcId);
      ManagedObjectReference rpMor = null;
      if (!Util.normalizeString(rpId).equals("")) {
        rpMor = cache.getResourcePool(rpId);
      }

      if ((dcMor != null) && (vmMor != null) && (vmFolderMor != null)) {
        ExtendedAppUtil ecb = getECB(url, username, password);

        VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
        VirtualMachineRelocateSpec relocSpec = new VirtualMachineRelocateSpec();
        cloneSpec.setLocation(relocSpec);
        cloneSpec.setPowerOn(false);
        cloneSpec.setTemplate(isTemplate);
        // 如果是从模板部署为虚拟机需要指定资源池
        if (rpMor != null) {
          relocSpec.setPool(rpMor);
        }

        ManagedObjectReference taskMor =
            ecb.getServiceConnection3()
                .getService()
                .cloneVM_Task(vmMor, vmFolderMor, cloneName, cloneSpec);

        execTaskAndRecordResultMap(ecb, taskMor, resultMap);
      } else {
        if (dcMor == null) {
          recordResultMapError(resultMap, "数据中心'" + dcId + "'不存在");
        }
        if (vmMor == null) {
          // recordResultMapError(resultMap, "虚拟机'" + vmId
          // + "'不存在");
          recordResultMapError(resultMap, "虚拟机'" + "'不存在");
        }
        if (vmFolderMor == null) {
          recordResultMapError(resultMap, "数据中心'" + dcId + "'的vmFolder不存在");
        }
      }
    } catch (Exception e) {
      LOGGER.error("cloneVM error, ", e);
      recordResultMapException(resultMap, e);
    }
  }
Exemple #2
0
  /**
   * 创建虚拟机,CreateVM_Task
   *
   * @param url
   * @param username
   * @param password
   * @param dcId
   * @param haId
   * @param rpId
   * @param name
   * @param descr
   * @param guestId
   * @param numCpus
   * @param numCores
   * @param memoryMB
   * @param dsId
   * @param diskSizeMB
   * @return
   */
  public static Map<String, Object> createVM(
      String url,
      String username,
      String password,
      String dcId,
      String haId,
      String rpId,
      String name,
      String descr,
      String guestId,
      int numCpus,
      int numCores,
      long memoryMB,
      String dsId,
      long diskSizeMB) {
    // CreateVM_Task
    // http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.apiref.doc_50%2Fvim.Folder.html&path=5_0_2_5_3_75

    // VirtualMachineConfigSpec
    // http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.apiref.doc_50%2Fvim.vm.ConfigSpec.html

    // 1.VimBindingStub对象执行createVM_Task方法
    // 共4个参数,_this,config,pool,host
    // 其中host可以不指定,但是pool需要有权限Resource.AssignVMToPool

    // 1._this:从dc获取一下vmFolder
    // 公司环境的vmFolder树形结构itimsDC(datacenter-2)-->vm(group-v3)
    // 公司环境中的主机群集属性结果itimsDC(datacenter-2)-->host,group-h4(datacenter-2)-->itimsHA(domain-c73)
    // 在管理系统中的云对应主机群集,在保存主机群集的id同时也保存dc的id
    // ManagedObjectReference vmFolderMor =
    // cb.getServiceUtil().getMoRefProp(
    // dcmor, "vmFolder");

    // 2.config:VirtualMachineConfigSpec虚拟机配置

    // 3.pool:从dc的hostFolder对象下获取ComputeResource
    // 公司环境的ComputeResource树形结构itimsDC(datacenter-2)-->host(group-h4)-->itimsHA(domain-c73)-->Resources(resgroup-74)-->testRP(resgroup-121)
    // vim代码:从主机目录中获取计算资源
    // ManagedObjectReference hfmor =
    // cb.getServiceUtil().getMoRefProp(dcmor,
    // "hostFolder");
    // ArrayList crmors = cb.getServiceUtil().getDecendentMoRefs(hfmor,
    // "ComputeResource");

    // 4.host:主机不指定,由计算资源自动分配

    HashMap<String, Object> resultMap = new HashMap<String, Object>();

    try {
      VIMCache cache = VIMCache.getInstance(url, username, password);

      // 获取_this和pool
      ManagedObjectReference dcMor = cache.getDatacenter(dcId);
      // 获取数据中心下的虚拟机文件夹
      ManagedObjectReference vmFolderMor = cache.getVMFolder(dcId);
      // 获取主机群集
      ManagedObjectReference haMor = cache.getComputeResource(haId);
      if (haMor == null) {
        haMor = cache.getClusterComputeResource(haId);
      }
      // 获取资源池
      ManagedObjectReference rpMor = cache.getResourcePool(rpId);
      // 获取数据存储
      ManagedObjectReference dsMor = cache.getDatastore(dsId);

      if ((dcMor != null)
          && (vmFolderMor != null)
          && (haMor != null)
          && (rpMor != null)
          && (dsMor != null)) {

        ExtendedAppUtil ecb = getECB(url, username, password);

        // 创建VirtualMachineConfigSpec
        // http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.ConfigSpec.html
        VirtualMachineConfigSpec vmConfig =
            createVmConfigSpec(
                ecb,
                dcMor,
                haMor,
                name,
                descr,
                guestId,
                numCpus,
                numCores,
                memoryMB,
                dsMor,
                diskSizeMB);

        ManagedObjectReference taskMor =
            ecb.getServiceConnection3()
                .getService()
                .createVM_Task(vmFolderMor, vmConfig, rpMor, null);

        execTaskAndRecordResultMap(ecb, taskMor, resultMap);

        // 如果虚拟机创建成功,获取虚拟机对应的主机id
        if (Util.normalizeObject(resultMap.get(INFO_STATE)).toString().equals(STATE_OK)) {
          String vmId = Util.normalizeObject(resultMap.get(INFO_RESULT)).toString();
          if (!vmId.equals("")) {
            ManagedObjectReference vmMor = cache.getVirtualMachine(vmId);
            Object runtime = getDynamicProperty(ecb, vmMor, DYNAMICPROPERTY_RUNTIME);
            if ((runtime != null) && (runtime instanceof VirtualMachineRuntimeInfo)) {
              VirtualMachineRuntimeInfo runtimeInfo = (VirtualMachineRuntimeInfo) runtime;
              if (runtimeInfo.getHost() != null) {
                String hoId = runtimeInfo.getHost().get_value();
                resultMap.put(INFO_RESULT2, hoId);
              }
            }
          }
        }
      } else {
        if (dcMor == null) {
          recordResultMapError(resultMap, "数据中心'" + dcId + "'不存在");
        }
        if (vmFolderMor == null) {
          recordResultMapError(resultMap, "数据中心'" + dcId + "'的vmFolder不存在");
        }
        if (haMor == null) {
          recordResultMapError(resultMap, "主机群集'" + haId + "'不存在");
        }
        if (rpMor == null) {
          recordResultMapError(resultMap, "'资源池" + rpId + "'不存在");
        }
        if (dsMor == null) {
          recordResultMapError(resultMap, "'数据存储" + dsId + "'不存在");
        }
      }
    } catch (Exception e) {
      LOGGER.error("createVM error, ", e);
      recordResultMapException(resultMap, e);
    }

    return resultMap;
  }
Exemple #3
0
  /**
   * 获取虚拟机的摘要信息
   *
   * @param url
   * @param username
   * @param password
   * @param vmId
   * @return
   */
  public static Map<String, Object> getSummary(
      String url, String username, String password, String vmId) {

    HashMap<String, Object> resultMap = new HashMap<String, Object>();

    try {
      VIMCache cache = VIMCache.getInstance(url, username, password);
      ManagedObjectReference mor = cache.getVirtualMachine(vmId);
      //			System.out.println("vmId--:"+vmId+"===mor-是否存在---------------------------"+mor);

      if (mor != null) {
        ExtendedAppUtil ecb = getECB(url, username, password);

        // 配置
        VirtualMachineConfigInfo config =
            (VirtualMachineConfigInfo) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_CONFIG);

        // 运行
        VirtualMachineRuntimeInfo runtime =
            (VirtualMachineRuntimeInfo) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_RUNTIME);

        // 摘要
        VirtualMachineSummary summary =
            (VirtualMachineSummary) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_SUMMARY);

        // 存储列表
        ManagedObjectReference[] dsList =
            (ManagedObjectReference[]) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_DATASTORE);

        // 网络列表
        ManagedObjectReference[] netList =
            (ManagedObjectReference[]) getDynamicProperty(ecb, mor, DYNAMICPROPERTY_NETWORK);

        // List<Object> properties = getDynamicProperties(ecb, mor,
        // new String[] { DYNAMICPROPERTY_CONFIG,
        // DYNAMICPROPERTY_SUMMARY,
        // DYNAMICPROPERTY_DATASTORE,
        // DYNAMICPROPERTY_NETWORK });
        // VirtualMachineConfigInfo config = (VirtualMachineConfigInfo)
        // properties
        // .get(0);
        // VirtualMachineSummary summary = (VirtualMachineSummary)
        // properties
        // .get(1);
        // ManagedObjectReference[] dsList = (ManagedObjectReference[])
        // properties
        // .get(2);
        // ManagedObjectReference[] netList = (ManagedObjectReference[])
        // properties
        // .get(3);

        String hoId = "";
        if ((runtime != null) && (runtime.getHost() != null)) {
          hoId = runtime.getHost().get_value();
        }
        resultMap.put(SYNC_VM_HOID, hoId);
        resultMap.put(SYNC_COMMON_VID, mor.get_value());
        resultMap.put(SYNC_COMMON_NAME, config.getName());
        int numCore = config.getHardware().getNumCoresPerSocket();
        resultMap.put(SYNC_VM_NUMCORE, numCore);
        if ((config != null) && (summary != null)) {
          // 常规
          // 客户机操作系统
          resultMap.put(SUMMARY_COMMON_GUESTFULLNAME, config.getGuestFullName());

          // 虚拟机版本,样本数据vmx-08
          resultMap.put(SUMMARY_COMMON_VERSION, config.getVersion());
          // CPU
          resultMap.put(SUMMARY_COMMON_CPU, summary.getConfig().getNumCpu());
          // 内存,单位为MB
          resultMap.put(
              SUMMARY_COMMON_MEMORYSIZEMB,
              getByteSizeStrFromMB(summary.getConfig().getMemorySizeMB()));

          // 内存开销,current overhead reservation,单位为字节
          resultMap.put(
              SUMMARY_COMMON_MEMORYOVERHEAD,
              getByteSizeStrFromBytes(summary.getRuntime().getMemoryOverhead()));
          // VMware Tools:
          // 运行状态toolsRunningStatus
          // VirtualMachineToolsRunningStatus:guestToolsExecutingScripts,guestToolsNotRunning,guestToolsRunning
          // 状态(toolsStatus,toolsVersionStatus[Since4.0],toolsVersionStatus2[Since5.0])
          // VirtualMachineToolsVersionStatus:guestToolsBlacklisted[Since5.0],guestToolsCurrent,guestToolsNeedUpgrade,guestToolsNotInstalled,
          // guestToolsSupportedNew[Since5.0],guestToolsSupportedOld[Since5.0],guestToolsTooNew[Since5.0],guestToolsTooOld[Since5.0],guestToolsUnmanaged
          // 正在运行(当前版本)
          // http://pubs.vmware.com/vsphere-50/topic/com.vmware.wssdk.apiref.doc_50/vim.vm.Summary.GuestSummary.html
          // toolsStatus
          // toolsVersionStatus[Since4.0]
          // toolsVersionStatus2[Since5.0]
          // 暂时只获取toolsVersionStatus
          resultMap.put(
              SUMMARY_COMMON_VMWARETOOLS,
              cache.getEnum(summary.getGuest().getToolsRunningStatus())
                  + "("
                  + cache.getEnum(summary.getGuest().getToolsVersionStatus())
                  + ")");
          // IP地址
          resultMap.put(
              SUMMARY_COMMON_IPADDRESS, Util.normalizeString(summary.getGuest().getIpAddress()));
          // DNS名称
          resultMap.put(
              SUMMARY_COMMON_HOSTNAME, Util.normalizeString(summary.getGuest().getHostName()));
          // XXX EVC模式,暂时无法获取
          // String SUMMARY_COMMON_EVCMODEL = "evcmodel";
          // 状况,poweredOff,poweredOn,suspended
          // powerstate在alarmDesc中有翻译
          //					resultMap.put(SUMMARY_COMMON_POWERSTATE, cache
          //							.getAlarmDesc(summary.getRuntime().getPowerState()
          //									.getValue()));

          String powerState = "";
          if (runtime != null) {
            powerState = runtime.getPowerState().toString();
          }
          resultMap.put(SYNC_VM_POWERSTATE, powerState);
          // 主机
          resultMap.put(SUMMARY_COMMON_HOST, getEntityName(ecb, summary.getRuntime().getHost()));
          // XXX 活动任务,暂时无法获取
          // String SUMMARY_COMMON_ACTIVETASK = "activetask";
          // XXX vSphere HA保护,暂时无法获取
          // String SUMMARY_COMMON_VSPHEREHA = "vsphereha";

          // 资源
          // 已消耗的主机CPU,Basic CPU performance
          // statistics,单位MHz,大概是这个值此值变化比较快
          resultMap.put(
              SUMMARY_RESOURCE_OVERALLCPUUSAGE, summary.getQuickStats().getOverallCpuUsage() + MHZ);
          // 已消耗的主机内存:consumed host memory,单位为MB
          resultMap.put(
              SUMMARY_RESOURCE_HOSTMEMORYUSAGE,
              getByteSizeStrFromMB(summary.getQuickStats().getHostMemoryUsage()));
          // 活动客户机内存:active guest memory,单位为MB
          resultMap.put(
              SUMMARY_RESOURCE_GUESTMEMORYUSAGE,
              getByteSizeStrFromMB(summary.getQuickStats().getGuestMemoryUsage()));
          // 未共享的存储
          resultMap.put(
              SUMMARY_RESOURCE_STORAGE_UNSHARED,
              getByteSizeStrFromBytes(summary.getStorage().getUnshared()));
          // 已使用的存储
          resultMap.put(
              SUMMARY_RESOURCE_STORAGE_COMMITTED,
              getByteSizeStrFromBytes(summary.getStorage().getCommitted()));
          // 置备的存储
          resultMap.put(
              SUMMARY_RESOURCE_STORAGE_ALL,
              getByteSizeStrFromBytes(
                  summary.getStorage().getCommitted() + summary.getStorage().getUncommitted()));

          // 存储列表
          DatastoreMgr.recordResultMapDsList(resultMap, ecb, dsList);

          // 网络列表
          NetworkMgr.recordResultMapNetList(resultMap, ecb, netList);

          // 记录处理正确的标识
          recordResultMapSuccess(resultMap);
        } else {
          recordResultMapError(
              resultMap,
              "获取'" + DYNAMICPROPERTY_CONFIG + "'或'" + DYNAMICPROPERTY_SUMMARY + "'信息为空");
        }
      } else {
        recordResultMapError(resultMap, "虚拟机'" + vmId + "'不存在");
      }
    } catch (Exception e) {
      LOGGER.error("getSummary error, ", e);
      recordResultMapException(resultMap, e);
    }

    return resultMap;
  }