Exemple #1
0
  private static void reconfigVirtualMachine() throws Exception {
    System.out.println("ReConfigure The Virtual Machine ..........");
    VirtualMachineFileInfo vmFileInfo = new VirtualMachineFileInfo();
    vmFileInfo.setLogDirectory("[" + datastore + "] " + vmName);
    vmFileInfo.setSnapshotDirectory("[" + datastore + "] " + vmName);
    vmFileInfo.setSuspendDirectory("[" + datastore + "] " + vmName);
    vmFileInfo.setVmPathName("[" + datastore + "] " + vmName + "/" + vmName + ".vmx");

    VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
    vmConfigSpec.setFiles(vmFileInfo);

    ManagedObjectReference taskmor = vimPort.reconfigVMTask(getVmByVMname(vmName), vmConfigSpec);

    Object[] result =
        waitForValues(
            taskmor,
            new String[] {"info.state", "info.error"},
            new String[] {"state"},
            new Object[][] {new Object[] {TaskInfoState.SUCCESS, TaskInfoState.ERROR}});
    if (result[0].equals(TaskInfoState.SUCCESS)) {
      System.out.println("ReConfigure The Virtual Machine .......... Done");
    } else {
      System.out.println("Some Exception While Reconfiguring The VM " + result[0]);
    }
  }
  /**
   * Creates the virtual machine.
   *
   * @throws RemoteException the remote exception
   * @throws Exception the exception
   */
  void createVirtualMachine()
      throws RemoteException, RuntimeFaultFaultMsg, InvalidPropertyFaultMsg,
          InvalidCollectorVersionFaultMsg, OutOfBoundsFaultMsg, DuplicateNameFaultMsg,
          VmConfigFaultFaultMsg, InsufficientResourcesFaultFaultMsg, AlreadyExistsFaultMsg,
          InvalidDatastoreFaultMsg, FileFaultFaultMsg, InvalidStateFaultMsg, InvalidNameFaultMsg,
          TaskInProgressFaultMsg {

    ManagedObjectReference dcmor =
        getMOREFsInContainerByType(serviceContent.getRootFolder(), "Datacenter")
            .get(dataCenterName);

    if (dcmor == null) {
      System.out.println("Datacenter " + dataCenterName + " not found.");
      return;
    }
    ManagedObjectReference hostmor = getMOREFsInContainerByType(dcmor, "HostSystem").get(hostname);
    if (hostmor == null) {
      System.out.println("Host " + hostname + " not found");
      return;
    }

    ManagedObjectReference crmor =
        (ManagedObjectReference)
            getMOREFs.entityProps(hostmor, new String[] {"parent"}).get("parent");
    if (crmor == null) {
      System.out.println("No Compute Resource Found On Specified Host");
      return;
    }

    ManagedObjectReference resourcepoolmor =
        (ManagedObjectReference)
            getMOREFs.entityProps(crmor, new String[] {"resourcePool"}).get("resourcePool");
    ManagedObjectReference vmFolderMor =
        (ManagedObjectReference)
            getMOREFs.entityProps(dcmor, new String[] {"vmFolder"}).get("vmFolder");

    VirtualMachineConfigSpec vmConfigSpec =
        createVmConfigSpec(virtualMachineName, dataStore, diskSize, crmor, hostmor);

    vmConfigSpec.setName(virtualMachineName);
    vmConfigSpec.setAnnotation("VirtualMachine Annotation");
    vmConfigSpec.setMemoryMB(new Long(vmMemory));
    vmConfigSpec.setNumCPUs(numCpus);
    vmConfigSpec.setGuestId(guestOsId);

    ManagedObjectReference taskmor =
        vimPort.createVMTask(vmFolderMor, vmConfigSpec, resourcepoolmor, hostmor);
    if (getTaskResultAfterDone(taskmor)) {
      System.out.printf("Success: Creating VM  - [ %s ] %n", virtualMachineName);
    } else {
      String msg = "Failure: Creating [ " + virtualMachineName + "] VM";
      throw new RuntimeException(msg);
    }
    ManagedObjectReference vmMor =
        (ManagedObjectReference)
            getMOREFs.entityProps(taskmor, new String[] {"info.result"}).get("info.result");
    System.out.println("Powering on the newly created VM " + virtualMachineName);
    // Start the Newly Created VM.
    powerOnVM(vmMor);
  }
  /**
   * Creates the vm config spec object.
   *
   * @param vmName the vm name
   * @param datastoreName the datastore name
   * @param diskSizeMB the disk size in mb
   * @param computeResMor the compute res moref
   * @param hostMor the host mor
   * @return the virtual machine config spec object
   * @throws Exception the exception
   */
  VirtualMachineConfigSpec createVmConfigSpec(
      String vmName,
      String datastoreName,
      int diskSizeMB,
      ManagedObjectReference computeResMor,
      ManagedObjectReference hostMor)
      throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg {

    ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor);
    List<VirtualDevice> defaultDevices = getDefaultDevices(computeResMor, hostMor);
    VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec();
    String networkName = null;
    if (configTarget.getNetwork() != null) {
      for (int i = 0; i < configTarget.getNetwork().size(); i++) {
        VirtualMachineNetworkInfo netInfo = configTarget.getNetwork().get(i);
        NetworkSummary netSummary = netInfo.getNetwork();
        if (netSummary.isAccessible()) {
          networkName = netSummary.getName();
          break;
        }
      }
    }
    ManagedObjectReference datastoreRef = null;
    if (datastoreName != null) {
      boolean flag = false;
      for (int i = 0; i < configTarget.getDatastore().size(); i++) {
        VirtualMachineDatastoreInfo vdsInfo = configTarget.getDatastore().get(i);
        DatastoreSummary dsSummary = vdsInfo.getDatastore();
        if (dsSummary.getName().equals(datastoreName)) {
          flag = true;
          if (dsSummary.isAccessible()) {
            datastoreRef = dsSummary.getDatastore();
          } else {
            throw new RuntimeException("Specified Datastore is not accessible");
          }
          break;
        }
      }
      if (!flag) {
        throw new RuntimeException("Specified Datastore is not Found");
      }
    } else {
      boolean flag = false;
      for (int i = 0; i < configTarget.getDatastore().size(); i++) {
        VirtualMachineDatastoreInfo vdsInfo = configTarget.getDatastore().get(i);
        DatastoreSummary dsSummary = vdsInfo.getDatastore();
        if (dsSummary.isAccessible()) {
          datastoreName = dsSummary.getName();
          datastoreRef = dsSummary.getDatastore();
          flag = true;
          break;
        }
      }
      if (!flag) {
        throw new RuntimeException("No Datastore found on host");
      }
    }
    String datastoreVolume = getVolumeName(datastoreName);
    VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo();
    vmfi.setVmPathName(datastoreVolume);
    configSpec.setFiles(vmfi);
    // Add a scsi controller
    int diskCtlrKey = 1;
    VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec();
    scsiCtrlSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
    VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController();
    scsiCtrl.setBusNumber(0);
    scsiCtrlSpec.setDevice(scsiCtrl);
    scsiCtrl.setKey(diskCtlrKey);
    scsiCtrl.setSharedBus(VirtualSCSISharing.NO_SHARING);
    String ctlrType = scsiCtrl.getClass().getName();
    ctlrType = ctlrType.substring(ctlrType.lastIndexOf(".") + 1);

    // Find the IDE controller
    VirtualDevice ideCtlr = null;
    for (int di = 0; di < defaultDevices.size(); di++) {
      if (defaultDevices.get(di) instanceof VirtualIDEController) {
        ideCtlr = defaultDevices.get(di);
        break;
      }
    }

    // Add a floppy
    VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec();
    floppySpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
    VirtualFloppy floppy = new VirtualFloppy();
    VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo();
    flpBacking.setDeviceName("/dev/fd0");
    floppy.setBacking(flpBacking);
    floppy.setKey(3);
    floppySpec.setDevice(floppy);

    // Add a cdrom based on a physical device
    VirtualDeviceConfigSpec cdSpec = null;

    if (ideCtlr != null) {
      cdSpec = new VirtualDeviceConfigSpec();
      cdSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
      VirtualCdrom cdrom = new VirtualCdrom();
      VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo();
      cdDeviceBacking.setDatastore(datastoreRef);
      cdDeviceBacking.setFileName(datastoreVolume + "testcd.iso");
      cdrom.setBacking(cdDeviceBacking);
      cdrom.setKey(20);
      cdrom.setControllerKey(new Integer(ideCtlr.getKey()));
      cdrom.setUnitNumber(new Integer(0));
      cdSpec.setDevice(cdrom);
    }

    // Create a new disk - file based - for the vm
    VirtualDeviceConfigSpec diskSpec = null;
    diskSpec = createVirtualDisk(datastoreName, diskCtlrKey, datastoreRef, diskSizeMB);

    // Add a NIC. the network Name must be set as the device name to create the NIC.
    VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
    if (networkName != null) {
      nicSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
      VirtualEthernetCard nic = new VirtualPCNet32();
      VirtualEthernetCardNetworkBackingInfo nicBacking =
          new VirtualEthernetCardNetworkBackingInfo();
      nicBacking.setDeviceName(networkName);
      nic.setAddressType("generated");
      nic.setBacking(nicBacking);
      nic.setKey(4);
      nicSpec.setDevice(nic);
    }

    List<VirtualDeviceConfigSpec> deviceConfigSpec = new ArrayList<VirtualDeviceConfigSpec>();
    deviceConfigSpec.add(scsiCtrlSpec);
    deviceConfigSpec.add(floppySpec);
    deviceConfigSpec.add(diskSpec);
    if (ideCtlr != null) {
      deviceConfigSpec.add(cdSpec);
      deviceConfigSpec.add(nicSpec);
    } else {
      deviceConfigSpec = new ArrayList<VirtualDeviceConfigSpec>();
      deviceConfigSpec.add(nicSpec);
    }
    configSpec.getDeviceChange().addAll(deviceConfigSpec);
    return configSpec;
  }