com.vmware.vim25.mo.VirtualMachine Java Examples

The following examples show how to use com.vmware.vim25.mo.VirtualMachine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VmwareNetworkProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
protected VirtualEthernetCard editEthernetCards(VirtualMachine machine, String networkName) {
    // ネットワークアダプタ E1000を使用する
    VirtualEthernetCard ethernetCard = new VirtualE1000();

    // 分散ポートグループ情報取得
    DistributedVirtualPortgroupInfo dvPortgroupInfo = getDVPortgroupInfo(machine, networkName);

    if (dvPortgroupInfo != null) {
        // 分散ポートグループの場合
        VirtualEthernetCardDistributedVirtualPortBackingInfo nicBacking = new VirtualEthernetCardDistributedVirtualPortBackingInfo();
        nicBacking.setPort(new DistributedVirtualSwitchPortConnection());
        nicBacking.getPort().setPortgroupKey(dvPortgroupInfo.getPortgroupKey());
        nicBacking.getPort().setSwitchUuid(dvPortgroupInfo.getSwitchUuid());
        ethernetCard.setBacking(nicBacking);
    } else {
        // 標準ポートグループの場合
        VirtualEthernetCardNetworkBackingInfo backingInfo = new VirtualEthernetCardNetworkBackingInfo();
        backingInfo.setDeviceName(networkName);
        ethernetCard.setBacking(backingInfo);
    }

    return ethernetCard;
}
 
Example #2
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
public void waitForStopped(String machineName) {
    VirtualMachine machine = getVirtualMachine(machineName);

    // 停止判定処理
    while (true) {
        try {
            Thread.sleep(30 * 1000L);
        } catch (InterruptedException ignore) {
        }

        VirtualMachineRuntimeInfo runtimeInfo = machine.getRuntime();

        if (runtimeInfo.getPowerState() == VirtualMachinePowerState.poweredOff) {
            break;
        }
    }
}
 
Example #3
Source File: VmwareCustomizeProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
protected List<CustomizationAdapterMapping> createCustomizationAdapterMappings(
        VmwareProcessClient vmwareProcessClient, VirtualMachine machine) {

    List<CustomizationAdapterMapping> nicSettingMap = new ArrayList<CustomizationAdapterMapping>();

    // VirtualEthernetCardを取得
    VirtualMachineConfigInfo configInfo = machine.getConfig();
    for (VirtualDevice device : configInfo.getHardware().getDevice()) {
        if (device instanceof VirtualEthernetCard) {
            VirtualEthernetCard virtualEthernetCard = VirtualEthernetCard.class.cast(device);
            CustomizationAdapterMapping mapping = new CustomizationAdapterMapping();
            CustomizationIPSettings settings = new CustomizationIPSettings();

            // すべてのNICをDHCPにする
            CustomizationDhcpIpGenerator dhcpIp = new CustomizationDhcpIpGenerator();
            settings.setIp(dhcpIp);

            mapping.setMacAddress(virtualEthernetCard.getMacAddress());
            mapping.setAdapter(settings);
            nicSettingMap.add(mapping);
        }
    }

    return nicSettingMap;
}
 
Example #4
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
protected VirtualSCSIController getSCSIController(VirtualMachine machine) {
    // 仮想マシンにあるSCSIコントローラのうち、BusNumberが0のものを取得する
    VirtualSCSIController scsiController = null;
    for (VirtualDevice device : machine.getConfig().getHardware().getDevice()) {
        if (device instanceof VirtualSCSIController) {
            VirtualSCSIController scsiController2 = VirtualSCSIController.class.cast(device);
            if (scsiController2.getBusNumber() == 0) {
                scsiController = scsiController2;
                break;
            }
        }
    }

    if (scsiController == null) {
        // SCSIコントローラが見つからない場合
        // TODO: SCSIコントローラを作る?
        throw new AutoException("EPROCESS-000517", 0);
    }

    return scsiController;
}
 
Example #5
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
protected VirtualDisk getVirtualDisk(VirtualMachine machine, Integer scsiId) {
    // SCSIコントローラを取得
    VirtualSCSIController scsiController = getSCSIController(machine);

    // SCSIコントローラとSCSI IDが一致するディスクを取得
    VirtualDisk disk = null;
    for (VirtualDevice device : machine.getConfig().getHardware().getDevice()) {
        if (device instanceof VirtualDisk) {
            VirtualDisk tmpDisk = VirtualDisk.class.cast(device);
            if (tmpDisk.getControllerKey() != null && tmpDisk.getControllerKey().equals(scsiController.getKey())) {
                if (tmpDisk.getUnitNumber() != null && tmpDisk.getUnitNumber().equals(scsiId)) {
                    disk = tmpDisk;
                    break;
                }
            }
        }
    }

    if (disk == null) {
        // VirtualDiskが見つからない場合
        throw new AutoException("EPROCESS-000518", scsiId);
    }

    return disk;
}
 
Example #6
Source File: VmwareNetworkProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
public DistributedVirtualPortgroupInfo getDVPortgroupInfo(VirtualMachine machine, String networkName) {
    HostSystem host = new HostSystem(machine.getServerConnection(), machine.getRuntime().getHost());
    ComputeResource computeResource = (ComputeResource) host.getParent();
    EnvironmentBrowser envBrowser = computeResource.getEnvironmentBrowser();

    DistributedVirtualPortgroupInfo dvPortgroupInfo = null;
    try {
        ConfigTarget configTarget = envBrowser.queryConfigTarget(host);

        // 分散ポートグループの場合
        if (configTarget.getDistributedVirtualPortgroup() != null) {
            // 分散ポートグループ情報を取得
            dvPortgroupInfo = findDVPortgroupInfo(configTarget.getDistributedVirtualPortgroup(), networkName);
        }
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }

    return dvPortgroupInfo;
}
 
Example #7
Source File: VmwareMachineProcess.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * TODO: メソッドコメントを記述
 *
 * @param vmwareProcessClient
 * @param instanceNo
 */
public void updateCustomValue(VmwareProcessClient vmwareProcessClient, Long instanceNo) {
    // カスタムフィールドがない場合は作成
    CustomFieldDef customFieldDef = vmwareProcessClient.getCustomFieldDef(fieldUserName, VirtualMachine.class);
    if (customFieldDef == null) {
        vmwareProcessClient.addCustomFieldDef(fieldUserName, VirtualMachine.class);
    }

    VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo);
    Instance instance = instanceDao.read(instanceNo);
    Farm farm = farmDao.read(instance.getFarmNo());
    User user = userDao.read(farm.getUserNo());

    // カスタムフィールドの値を設定
    vmwareProcessClient.setCustomValue(vmwareInstance.getMachineName(), fieldUserName, user.getUsername());
}
 
Example #8
Source File: VIJavaUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static String findVMNotOnHost(HostSystem host) throws RemoteException {
  VirtualMachine[] hostVMs = host.getVms();
  boolean foundMatch = false;
  String targetVM = null;
  for (String vmName : vmNames) {
    for (VirtualMachine vm : hostVMs) {
      if (vmName.equals(vm.getName())) {
        foundMatch = true;
        break;
      }
    }
    if (!foundMatch) {
      targetVM = vmName;
      break;
    }
    foundMatch = false;
  }
  return targetVM;
}
 
Example #9
Source File: VmwareIaasHandler.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
throws TargetException {

	boolean result;
	try {
		final ServiceInstance vmwareServiceInstance = getServiceInstance( parameters.getTargetProperties());
		VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineId );
		result = vm != null;

	} catch( Exception e ) {
		throw new TargetException( e );
	}

	return result;
}
 
Example #10
Source File: VIJavaUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static String findVMNotOnHost(HostSystem host) throws RemoteException {
  VirtualMachine[] hostVMs = host.getVms();
  boolean foundMatch = false;
  String targetVM = null;
  for (String vmName : vmNames) {
    for (VirtualMachine vm : hostVMs) {
      if (vmName.equals(vm.getName())) {
        foundMatch = true;
        break;
      }
    }
    if (!foundMatch) {
      targetVM = vmName;
      break;
    }
    foundMatch = false;
  }
  return targetVM;
}
 
Example #11
Source File: VmwareIaasHandler.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public String retrievePublicIpAddress( TargetHandlerParameters parameters, String machineId )
throws TargetException {

	String result = null;
	try {
		ServiceInstance vmwareServiceInstance = VmwareIaasHandler.getServiceInstance( parameters.getTargetProperties());
		String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());
		VirtualMachine vm = VmwareIaasHandler.getVirtualMachine( vmwareServiceInstance, rootInstanceName );
		if( vm != null )
			result = vm.getGuest().getIpAddress();

	} catch( Exception e ) {
		throw new TargetException( e );
	}

	return result;
}
 
Example #12
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void shutdownGuest(String machineName) {
    // VirtualMachine
    VirtualMachine machine = getVirtualMachine(machineName);

    // パワーオフ状態の場合はスキップ
    VirtualMachineRuntimeInfo runtimeInfo = machine.getRuntime();
    if (runtimeInfo.getPowerState() == VirtualMachinePowerState.poweredOff) {
        return;
    }

    // 仮想マシンのシャットダウン
    try {
        machine.shutdownGuest();
    } catch (RemoteException e) {
        throw new AutoException("EPROCESS-000519", e, machineName);
    }

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100415", machineName));
    }

    // シャットダウンが完了するまで待機
    waitForStopped(machineName);

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100416", machineName));
    }
}
 
Example #13
Source File: VmwareNetworkProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
protected List<VirtualEthernetCard> createEthernetCards(VmwareProcessClient vmwareProcessClient, Long instanceNo,
        VirtualMachine machine) {
    Instance instance = instanceDao.read(instanceNo);
    List<VmwareNetwork> vmwareNetworks = vmwareNetworkDao.readByFarmNo(instance.getFarmNo());

    // ネットワーク名の取得
    PlatformVmware platformVmware = platformVmwareDao.read(instance.getPlatformNo());
    String publicNetworkName = platformVmware.getPublicNetwork();
    String privateNetworkName = platformVmware.getPrivateNetwork();
    for (VmwareNetwork vmwareNetwork : vmwareNetworks) {
        if (BooleanUtils.isTrue(vmwareNetwork.getPublicNetwork())) {
            publicNetworkName = vmwareNetwork.getNetworkName();
        } else {
            privateNetworkName = vmwareNetwork.getNetworkName();
        }
    }

    // イーサネット設定の作成
    List<VirtualEthernetCard> ethernetCards = new ArrayList<VirtualEthernetCard>();

    // Public側イーサネット設定
    if (StringUtils.isNotEmpty(publicNetworkName)) {
        VirtualEthernetCard publicEthernetCard = editEthernetCards(machine, publicNetworkName);
        ethernetCards.add(publicEthernetCard);
    }

    // Private側イーサネット設定
    VirtualEthernetCard privateEthernetCard = editEthernetCards(machine, privateNetworkName);
    ethernetCards.add(privateEthernetCard);

    return ethernetCards;
}
 
Example #14
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void setCustomValue(String machineName, String name, String value) {
    // VirtualMachine
    VirtualMachine machine = getVirtualMachine(machineName);

    // カスタム値の設定
    try {
        machine.setCustomValue(name, value);
    } catch (RemoteException e) {
        throw new AutoException("EPROCESS-000527", e, machineName, name);
    }

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100463", machineName, name));
    }
}
 
Example #15
Source File: VmWareMachineConfigurator.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure() throws TargetException {

	try {
		// Is the VM up?
		if( this.vmwareServiceInstance == null )
			this.vmwareServiceInstance = VmwareIaasHandler.getServiceInstance( this.targetProperties );

		VirtualMachine vm = VmwareIaasHandler.getVirtualMachine( this.vmwareServiceInstance, this.rootInstanceName );
		if( vm == null ) {
			this.logger.warning( "No VM named '" + this.rootInstanceName + "' could be found. The VM might not yet be ready." );
			return false;
		}

		// If yes, write user data.
		GuestOperationsManager gom = this.vmwareServiceInstance.getGuestOperationsManager();
		NamePasswordAuthentication npa = new NamePasswordAuthentication();
		npa.username = this.targetProperties.get( VmwareIaasHandler.VM_USER );
		npa.password = this.targetProperties.get( VmwareIaasHandler.VM_PASSWORD );
		GuestProgramSpec spec = new GuestProgramSpec();

		spec.programPath = "/bin/echo";
		spec.arguments = "$\'" + this.userData + "\' > /tmp/roboconf.properties";
		this.logger.fine(spec.programPath + " " + spec.arguments);

		GuestProcessManager gpm = gom.getProcessManager( vm );
		gpm.startProgramInGuest(npa, spec);

		return true;

	} catch( Exception e ) {
		if(++ this.vmwareToolsCheckCount < 20) {
			this.logger.fine("VMWare tools not yet started... check #" + this.vmwareToolsCheckCount + " failed");
			return false;
		}
		throw new TargetException( e );
	}
}
 
Example #16
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
protected VirtualDisk reuseDisk(VirtualMachine machine, Integer scsiId, String fileName) {
    // SCSIコントローラを取得
    VirtualSCSIController scsiController = getSCSIController(machine);

    // 仮想マシン自体のディスクを取得
    VirtualDisk machineDisk = getVirtualDisk(machine, 0);
    VirtualDiskFlatVer2BackingInfo machieBackingInfo = VirtualDiskFlatVer2BackingInfo.class
            .cast(machineDisk.getBacking());

    // VirtualDisk
    VirtualDisk disk = new VirtualDisk();
    disk.setUnitNumber(scsiId);
    disk.setControllerKey(scsiController.getKey());

    // VirtualDiskFlatVer2BackingInfo
    VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo();
    backingInfo.setFileName(fileName);
    backingInfo.setDiskMode("persistent");
    backingInfo.setSplit(false);
    backingInfo.setEagerlyScrub(false);
    backingInfo.setThinProvisioned(machieBackingInfo.getThinProvisioned());
    backingInfo.setWriteThrough(false);
    disk.setBacking(backingInfo);

    // VirtualDeviceConnectInfo
    VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo();
    connectInfo.setAllowGuestControl(false);
    connectInfo.setStartConnected(true);
    connectInfo.setConnected(true);
    disk.setConnectable(connectInfo);

    return disk;
}
 
Example #17
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
protected VirtualDisk newDisk(VirtualMachine machine, Integer scsiId, Integer size) {
    // SCSIコントローラを取得
    VirtualSCSIController scsiController = getSCSIController(machine);

    // 仮想マシン自体のディスクを取得
    VirtualDisk machineDisk = getVirtualDisk(machine, 0);
    VirtualDiskFlatVer2BackingInfo machieBackingInfo = VirtualDiskFlatVer2BackingInfo.class
            .cast(machineDisk.getBacking());

    // VirtualDisk
    VirtualDisk disk = new VirtualDisk();
    disk.setUnitNumber(scsiId);
    disk.setCapacityInKB(size * 1024L * 1024L);
    disk.setControllerKey(scsiController.getKey());

    // VirtualDiskFlatVer2BackingInfo
    VirtualDiskFlatVer2BackingInfo backingInfo = new VirtualDiskFlatVer2BackingInfo();
    backingInfo.setDatastore(null);
    backingInfo.setFileName("");
    backingInfo.setDiskMode("persistent");
    backingInfo.setSplit(false);
    backingInfo.setEagerlyScrub(false);
    backingInfo.setThinProvisioned(machieBackingInfo.getThinProvisioned());
    backingInfo.setWriteThrough(false);
    disk.setBacking(backingInfo);

    // VirtualDeviceConnectInfo
    VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo();
    connectInfo.setAllowGuestControl(false);
    connectInfo.setStartConnected(true);
    connectInfo.setConnected(true);
    disk.setConnectable(connectInfo);

    return disk;
}
 
Example #18
Source File: VmwareProcessClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
protected VirtualMachine getVirtualMachine(String machineName) {
    VirtualMachine machine = vmwareClient.search(VirtualMachine.class, machineName);
    if (machine == null) {
        // 仮想マシンが見つからない場合
        throw new AutoException("EPROCESS-000501", machineName);
    }

    return machine;
}
 
Example #19
Source File: VSphereInfrastructure.java    From chaos-lemur with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Member member) throws DestructionException {
    try {
        VirtualMachine virtualMachine = (VirtualMachine) this.inventoryNavigatorFactory.create()
            .searchManagedEntity("VirtualMachine", member.getId());

        Assert.notNull(virtualMachine, String.format("virtualMachine must not be null for %s", member));

        handleTask(virtualMachine.powerOffVM_Task());
    } catch (InterruptedException | IOException e) {
        throw new DestructionException(String.format("Unable to destroy %s", member), e);
    }
}
 
Example #20
Source File: VmwareInstance.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
@Used("Tests")
public VmwareInstance(@NotNull final VirtualMachine vm, String datacenterId){
  this(vm.getName(),
       vm.getMOR().getVal(),
       vm.getConfig() == null ? new OptionValue[0] : vm.getConfig().getExtraConfig(),
       vm.getRuntime().getPowerState(),
       vm.getConfig() != null && vm.getConfig().isTemplate(),
       vm.getConfig() == null ? "" : vm.getConfig().getChangeVersion(),
       vm.getRuntime().getBootTime(),
       vm.getGuest() == null ? null : vm.getGuest().getIpAddress(),
       vm.getParent().getMOR(),
       datacenterId);
}
 
Example #21
Source File: VIJavaUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static boolean validateVMNotOnHost(ServiceInstance si,
    Folder rootFolder, HostSystem newHost, String vmName, String hostName)
    throws Exception {
  VirtualMachine[] vms = newHost.getVms();
  for (VirtualMachine vmac : vms) {
    if (vmac.getName().equals(vmName)) {
      Log.getLogWriter().info(
          vmName + " is already running on target host " + hostName
              + ". Selecting another pair...");
      return false;
    }
  }
  return true;
}
 
Example #22
Source File: VIJavaUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static boolean validateVMNotOnHost(ServiceInstance si,
    Folder rootFolder, HostSystem newHost, String vmName, String hostName)
    throws Exception {
  VirtualMachine[] vms = newHost.getVms();
  for (VirtualMachine vmac : vms) {
    if (vmac.getName().equals(vmName)) {
      Log.getLogWriter().info(
          vmName + " is already running on target host " + hostName
              + ". Selecting another pair...");
      return false;
    }
  }
  return true;
}
 
Example #23
Source File: VMotionTrigger.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static boolean migrateVM(ServiceInstance si, Folder rootFolder,
    HostSystem newHost, String targetVMName, String newHostName)
    throws Exception {

  log("Selected host [vm] for vMotion: " + newHostName + " [" + targetVMName
      + "]");
  VirtualMachine vm = (VirtualMachine)new InventoryNavigator(rootFolder)
      .searchManagedEntity("VirtualMachine", targetVMName);
  if (vm == null) {
    log(WARNING, "Could not resolve VM " + targetVMName + ", vMotion of this VM cannot be performed.");
    return false;
  }

  ComputeResource cr = (ComputeResource)newHost.getParent();

  String[] checks = new String[] { "cpu", "software" };
  HostVMotionCompatibility[] vmcs = si.queryVMotionCompatibility(vm,
      new HostSystem[] { newHost }, checks);

  String[] comps = vmcs[0].getCompatibility();
  if (checks.length != comps.length) {
    log(WARNING, "CPU/software NOT compatible, vMotion failed.");
    return false;
  }

  long start = System.currentTimeMillis();
  Task task = vm.migrateVM_Task(cr.getResourcePool(), newHost,
      VirtualMachineMovePriority.highPriority,
      VirtualMachinePowerState.poweredOn);
  if (task.waitForMe() == Task.SUCCESS) {
    long end = System.currentTimeMillis();
    log("vMotion of " + targetVMName + " to " + newHostName
        + " completed in " + (end - start) + "ms. Task result: "
        + task.getTaskInfo().getResult());
    return true;
  } else {
    TaskInfo info = task.getTaskInfo();
    log(WARNING, "vMotion of " + targetVMName + " to " + newHostName
        + " failed. Error details: " + info.getError().getFault());
    return false;
  }
}
 
Example #24
Source File: VmwareCustomizeProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
protected void customizeWindows(VmwareProcessClient vmwareProcessClient, VmwareInstance vmwareInstance,
        VirtualMachine machine) {
    CustomizationSpec customSpec = new CustomizationSpec();

    // Windows設定
    CustomizationSysprep identity = new CustomizationSysprep();

    CustomizationGuiUnattended guiUnattended = new CustomizationGuiUnattended();
    guiUnattended.setAutoLogon(false);
    guiUnattended.setAutoLogonCount(1);
    guiUnattended.setTimeZone(235);
    CustomizationPassword password = new CustomizationPassword();
    password.setPlainText(true);

    // Adminパスワードのデフォルトはユーザのパスワードをセットする
    Instance instance = instanceDao.read(vmwareInstance.getInstanceNo());
    Farm farm = farmDao.read(instance.getFarmNo());
    User user = userDao.read(farm.getUserNo());
    PccSystemInfo pccSystemInfo = pccSystemInfoDao.read();
    if (pccSystemInfo == null) {
        // PCC_SYSTEM_INFOのレコードが存在しない場合
        log.error(MessageUtils.getMessage("EPROCESS-000532"));
        throw new AutoException("EPROCESS-000532");
    }
    PasswordEncryptor encryptor = new PasswordEncryptor();
    String decryptPassword = encryptor.decrypt(user.getPassword(), pccSystemInfo.getSecretKey());
    password.setValue(decryptPassword);
    guiUnattended.setPassword(password);
    identity.setGuiUnattended(guiUnattended);

    CustomizationUserData userData = new CustomizationUserData();
    userData.setProductId("");
    userData.setFullName(windowsFullName);
    userData.setOrgName(windowsOrgName);
    CustomizationFixedName computerName = new CustomizationFixedName();
    computerName.setName(instance.getInstanceName());
    userData.setComputerName(computerName);
    identity.setUserData(userData);

    CustomizationIdentification identification = new CustomizationIdentification();
    identification.setJoinWorkgroup(windowsWorkgroup);
    identity.setIdentification(identification);

    // Windows Server 2000, 2003のみ必要
    CustomizationLicenseFilePrintData printData = new CustomizationLicenseFilePrintData();
    printData.setAutoMode(CustomizationLicenseDataMode.perSeat);
    identity.setLicenseFilePrintData(printData);

    customSpec.setIdentity(identity);

    // Windowsオプション設定
    CustomizationWinOptions options = new CustomizationWinOptions();
    options.setChangeSID(true);
    options.setReboot(CustomizationSysprepRebootOption.shutdown);
    customSpec.setOptions(options);

    // グローバル設定
    CustomizationGlobalIPSettings globalIpSettings = new CustomizationGlobalIPSettings();

    // DNSサーバ設定
    List<String> dnsServerList = new ArrayList<String>();
    // Primary DNSサーバ
    dnsServerList.add(Config.getProperty("dns.server"));
    // Secondry DNSサーバ
    String dns2 = Config.getProperty("dns.server2");
    if (dns2 != null && dns2.length() > 0) {
        dnsServerList.add(Config.getProperty("dns.server2"));
    }

    globalIpSettings.setDnsServerList(dnsServerList.toArray(new String[dnsServerList.size()]));
    List<String> dnsSuffixList = new ArrayList<String>();
    dnsSuffixList.add(farm.getDomainName());
    globalIpSettings.setDnsSuffixList(dnsSuffixList.toArray(new String[dnsSuffixList.size()]));
    customSpec.setGlobalIPSettings(globalIpSettings);

    // NIC設定
    List<CustomizationAdapterMapping> nicSettingMap = createCustomizationAdapterMappings(vmwareProcessClient,
            machine);
    customSpec.setNicSettingMap(nicSettingMap.toArray(new CustomizationAdapterMapping[nicSettingMap.size()]));

    vmwareProcessClient.customize(vmwareInstance.getMachineName(), customSpec);

}
 
Example #25
Source File: VmwareCustomizeProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
public void customize(VmwareProcessClient vmwareProcessClient, Long instanceNo) {
    VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo);
    VmwareClient vmwareClient = vmwareProcessClient.getVmwareClient();

    // VirtualMachine
    VirtualMachine machine = vmwareClient.search(VirtualMachine.class, vmwareInstance.getMachineName());
    if (machine == null) {
        // 仮想マシンが見つからない場合
        throw new AutoException("EPROCESS-000501", vmwareInstance.getMachineName());
    }

    // Windowsで始まるOSはカスタマイズする
    Instance instance = instanceDao.read(instanceNo);
    Image image = imageDao.read(instance.getImageNo());
    if (StringUtils.startsWith(image.getOs(), PCCConstant.OS_NAME_WIN)) {
        if (log.isInfoEnabled()) {
            log.info(MessageUtils.getMessage("IPROCESS-100464", vmwareInstance.getMachineName()));
        }
        customizeWindows(vmwareProcessClient, vmwareInstance, machine);

        vmwareProcessClient.powerOnVM(vmwareInstance.getMachineName());

        vmwareProcessClient.waitForStopped(vmwareInstance.getMachineName());

        vmwareProcessClient.powerOnVM(vmwareInstance.getMachineName());

        // ネットワーク名の取得
        PlatformVmware platformVmware = platformVmwareDao.read(instance.getPlatformNo());
        String publicNetworkName = platformVmware.getPublicNetwork();
        String privateNetworkName = platformVmware.getPrivateNetwork();

        List<VmwareNetwork> vmwareNetworks = vmwareNetworkDao.readByFarmNo(instance.getFarmNo());
        for (VmwareNetwork vmwareNetwork : vmwareNetworks) {
            if (BooleanUtils.isTrue(vmwareNetwork.getPublicNetwork())) {
                publicNetworkName = vmwareNetwork.getNetworkName();
            } else {
                privateNetworkName = vmwareNetwork.getNetworkName();
            }
        }

        List<String> networkNames = new ArrayList<String>();
        if (StringUtils.isNotEmpty(publicNetworkName)) {
            networkNames.add(publicNetworkName);
        }
        if (StringUtils.isNotEmpty(privateNetworkName)) {
            networkNames.add(privateNetworkName);
        }

        vmwareProcessClient.waitForRunning(vmwareInstance.getMachineName(), networkNames);

        vmwareProcessClient.shutdownGuest(vmwareInstance.getMachineName());

        if (log.isInfoEnabled()) {
            log.info(MessageUtils.getMessage("IPROCESS-100465", vmwareInstance.getMachineName()));
        }
    }

}
 
Example #26
Source File: VmwareCloudIntegrationTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
@TestFor(issues = "TW-61456")
public void recover_if_cant_connect_on_start() throws MalformedURLException {
  final AtomicBoolean failure = new AtomicBoolean(false);
  final AtomicLong lastApiCallTime = new AtomicLong(0);
  myFakeApi = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID){
    @Override
    protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected <T extends ManagedEntity> Pair<T,Datacenter> findEntityByIdNameOld(final String name, final Class<T> instanceType) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.findEntityByIdNameOld(name, instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull Collection<String> names, @Nullable Datacenter dc) throws VmwareCheckedCloudException {
      lastApiCallTime.set(System.currentTimeMillis());
      if (failure.get()){
        throw new VmwareCheckedCloudException("Cannot connect");
      }
      return super.searchVMsByNames(names, dc);
    }
  };
  failure.set(true);
  recreateClient(250);
  new WaitFor(1000){
    @Override
    protected boolean condition() {
      return myClient.isInitialized();
    }
  };
  myClient.getImages().forEach(img-> assertNotNull(img.getErrorInfo()));
  failure.set(false);
  new WaitFor(1000){
    @Override
    protected boolean condition() {
      AtomicBoolean result = new AtomicBoolean(true);
      myClient.getImages().forEach(img-> result.compareAndSet(true, img.getErrorInfo()==null));
      return result.get();
    }
  };
  myClient.getImages().forEach(img-> assertNull(img.getErrorInfo()));

}
 
Example #27
Source File: VmwarePooledUpdateInstanceTaskTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void check_cleared_after_dispose_2() throws MalformedURLException {
  final AtomicBoolean canBeCalled = new AtomicBoolean();
  final AtomicInteger callsCount = new AtomicInteger();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {
    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }

    private void processChecks() {
      if (!canBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertTrue(callsCount.get() < 2);
      callsCount.incrementAndGet();
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      processChecks();
      return Collections.emptyMap();
    }
  };

  final CloudClientParameters clientParameters1 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,"[{sourceVmName:'image1', behaviour:'START_STOP'}]"));
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]"));

  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);
  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);


  canBeCalled.set(true);
  callsCount.set(0);
  task1.run();
  assertTrue(callsCount.get() > 0);

  client1.dispose();
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  canBeCalled.set(true);
  callsCount.set(0);
  task2.run();
  assertTrue(callsCount.get() > 0);


}
 
Example #28
Source File: VmwarePooledUpdateInstanceTaskTest.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
public void check_called_once() throws MalformedURLException {
  final AtomicBoolean listAllCanBeCalled = new AtomicBoolean();
  final AtomicBoolean listAllCalledOnce = new AtomicBoolean();

  final AtomicBoolean getByNameCanBeCalled = new AtomicBoolean();
  final AtomicBoolean getByNameCalledOnce = new AtomicBoolean();

  myFakeApiConnector = new FakeApiConnector(TEST_SERVER_UUID, PROFILE_ID, null) {

    @Override
    protected <T extends ManagedEntity> Map<String, T> findAllEntitiesAsMapOld(final Class<T> instanceType) throws VmwareCheckedCloudException {
      if (!listAllCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(listAllCalledOnce.get());
      listAllCalledOnce.set(true);
      return super.findAllEntitiesAsMapOld(instanceType);
    }

    @Override
    protected Map<String, VirtualMachine> searchVMsByNames(@NotNull final Collection<String> names, @Nullable final Datacenter dc) throws VmwareCheckedCloudException {
      if (!getByNameCanBeCalled.get()) {
        fail("Shouldn't be called");
      }
      assertFalse(getByNameCalledOnce.get());
      getByNameCalledOnce.set(true);
      return super.searchVMsByNames(names, dc);
    }
  };

  final CloudClientParameters clientParameters1 = VmwareTestUtils.getClientParameters(PROJECT_ID, "[{sourceVmName:'image1', behaviour:'START_STOP'}]");
  final VMWareCloudClient client1 = new MyClient(clientParameters1, null);


  final CloudClientParameters clientParameters2 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{sourceVmName:'image2',snapshot:'snap*',folder:'cf',pool:'rp'," +
    "maxInstances:3,behaviour:'ON_DEMAND_CLONE',customizationSpec:'someCustomization'}]"));
  final VMWareCloudClient client2 = new MyClient(clientParameters2, null);

  final CloudClientParameters clientParameters3 = new CloudClientParametersImpl(
    Collections.emptyMap(), VmwareTestUtils.getImageParameters(PROJECT_ID,
    "[{'source-id':'image_template',sourceVmName:'image_template', snapshot:'" + VmwareConstants.CURRENT_STATE +
    "',folder:'cf',pool:'rp',maxInstances:3,behaviour:'FRESH_CLONE', customizationSpec: 'linux'}]"));
  final VMWareCloudClient client3 = new MyClient(clientParameters3, null);

  final VmwareUpdateInstanceTask task1 = myTaskManager.createUpdateTask(myFakeApiConnector, client1);
  final VmwareUpdateInstanceTask task2 = myTaskManager.createUpdateTask(myFakeApiConnector, client2);
  final VmwareUpdateInstanceTask task3 = myTaskManager.createUpdateTask(myFakeApiConnector, client3);

  listAllCanBeCalled.set(true);
  listAllCalledOnce.set(false);
  getByNameCalledOnce.set(false);
  getByNameCanBeCalled.set(true);
  task1.run();
  task2.run();
  task3.run();
  assertTrue(listAllCalledOnce.get());
  assertTrue(getByNameCalledOnce.get());
}
 
Example #29
Source File: VmwareMachineProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
/**
 * TODO: メソッドコメントを記述
 *
 * @param vmwareProcessClient
 * @param instanceNo
 */
public void getGuestInfo(VmwareProcessClient vmwareProcessClient, Long instanceNo) {
    Instance instance = instanceDao.read(instanceNo);
    VmwareInstance vmwareInstance = vmwareInstanceDao.read(instanceNo);
    List<VmwareNetwork> vmwareNetworks = vmwareNetworkDao.readByFarmNo(instance.getFarmNo());

    // ネットワーク名の取得
    Platform platform = platformDao.read(instance.getPlatformNo());
    PlatformVmware platformVmware = platformVmwareDao.read(instance.getPlatformNo());
    String publicNetworkName = platformVmware.getPublicNetwork();
    String privateNetworkName = platformVmware.getPrivateNetwork();
    for (VmwareNetwork vmwareNetwork : vmwareNetworks) {
        if (BooleanUtils.isTrue(vmwareNetwork.getPublicNetwork())) {
            publicNetworkName = vmwareNetwork.getNetworkName();
        } else {
            privateNetworkName = vmwareNetwork.getNetworkName();
        }
    }

    String publicIpAddress = null;
    String privateIpAddress = null;

    VirtualMachine machine = vmwareProcessClient.getVirtualMachine(vmwareInstance.getMachineName());
    for (GuestNicInfo nicInfo : machine.getGuest().getNet()) {
        // NIC情報からIPv4のアドレスを取得
        NetIpConfigInfoIpAddress[] tmpAddresses = nicInfo.getIpConfig().getIpAddress();
        if (tmpAddresses == null) {
            continue;
        }

        String ipAddress = null;
        for (NetIpConfigInfoIpAddress tmpAdress : tmpAddresses) {
            try {
                InetAddress inetAddress = InetAddress.getByName(tmpAdress.getIpAddress());
                if (inetAddress instanceof Inet4Address) {
                    ipAddress = tmpAdress.getIpAddress();
                    break;
                }
            } catch (UnknownHostException ignore) {
            }
        }

        // NIC情報がPublicかPrivateかの判定
        if (StringUtils.isNotEmpty(publicNetworkName) && publicNetworkName.equals(nicInfo.getNetwork())) {
            publicIpAddress = ipAddress;
        } else if (privateNetworkName.equals(nicInfo.getNetwork())) {
            privateIpAddress = ipAddress;
        }
    }

    if (StringUtils.isNotEmpty(publicNetworkName) && publicIpAddress == null) {
        // パブリックIPを取得できない場合
        throw new AutoException("EPROCESS-000510", vmwareInstance.getMachineName());
    } else if (privateIpAddress == null) {
        // プライベートIPを取得できない場合
        throw new AutoException("EPROCESS-000511", vmwareInstance.getMachineName());
    }

    // イベントログ出力
    processLogger.debug(null, instance, "VmwareInstanceStartFinish",
            new Object[] { platform.getPlatformName(), vmwareInstance.getMachineName() });

    // データベースに格納
    vmwareInstance = vmwareInstanceDao.read(instanceNo);
    vmwareInstance.setIpAddress(publicIpAddress);
    vmwareInstance.setPrivateIpAddress(privateIpAddress);
    vmwareInstanceDao.update(vmwareInstance);

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100432", vmwareInstance.getMachineName()));
    }
}
 
Example #30
Source File: VMWareApiConnector.java    From teamcity-vmware-plugin with Apache License 2.0 4 votes vote down vote up
@Nullable
InstanceStatus getInstanceStatus(@NotNull final VirtualMachine vm);