public VirtualDeviceConfigSpec createVirtualDisk(String volName, int diskCtlrKey, ManagedObjectReference datastoreRef, int diskSizeMB) { String volumeName = getVolumeName(volName); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); diskSpec.fileOperation = VirtualDeviceConfigSpecFileOperation.create; diskSpec.fileOperationSpecified = true; diskSpec.operation = VirtualDeviceConfigSpecOperation.add; diskSpec.operationSpecified = true; VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.fileName = volumeName; diskfileBacking.diskMode = "persistent"; disk.key = 0; disk.controllerKey = diskCtlrKey; disk.unitNumber = 0; disk.backing = diskfileBacking; disk.capacityInKB = diskSizeMB; disk.controllerKeySpecified = true; disk.unitNumberSpecified = true; diskSpec.device = disk; return(diskSpec); }
private List <VirtualDeviceConfigSpec> UpdateVMNetworkDevices(VirtualMachine virtualMachine, ManagedObjectReference host) { List <VirtualDeviceConfigSpec> nicConfigSpecs = new List <VirtualDeviceConfigSpec>(); var nics = virtualMachine.Config.Hardware.Device.Where(x => x.GetType().IsSubclassOf(typeof(VirtualEthernetCard))); foreach (VirtualEthernetCard nic in nics) { if (nic.Backing is VirtualEthernetCardNetworkBackingInfo) { nic.Backing = GetNetworkByVlanId(nic, host); } if (nic.Backing == null) { continue; } var spec = new VirtualDeviceConfigSpec { Operation = VirtualDeviceConfigSpecOperation.edit, Device = nic }; nic.DeviceInfo = new Description { Summary = ((VirtualEthernetCardNetworkBackingInfo)nic.Backing).DeviceName, Label = nic.DeviceInfo.Label }; Logger.Info("{0}: NIC Summary: {1}", virtualMachine.Name, nic.DeviceInfo.Summary); nicConfigSpecs.Add(spec); } return(nicConfigSpecs); }
public VirtualDeviceConfigSpec Controller(int _bus_number, int _unit_number, int _controller_key) { VirtualLsiLogicController scsi = new VirtualLsiLogicController(); VirtualDeviceConnectInfo ci = new VirtualDeviceConnectInfo(); ci.startConnected = false; scsi.key = _controller_key; scsi.controllerKey = 100; scsi.controllerKeySpecified = true; scsi.busNumber = _bus_number; scsi.hotAddRemove = true; scsi.hotAddRemoveSpecified = true; scsi.scsiCtlrUnitNumber = 7; scsi.scsiCtlrUnitNumberSpecified = true; scsi.sharedBus = VirtualSCSISharing.noSharing; scsi.unitNumber = _unit_number; scsi.unitNumberSpecified = true; scsi.connectable = ci; VirtualDeviceConfigSpec dcs = new VirtualDeviceConfigSpec(); dcs.device = scsi; dcs.operation = VirtualDeviceConfigSpecOperation.add; dcs.operationSpecified = true; return(dcs); }
public VirtualDeviceConfigSpec Controller(bool Is2012) { VirtualSCSIController scsi = new VirtualSCSIController(); if (Is2012) { scsi = new VirtualLsiLogicSASController(); } else { scsi = new VirtualLsiLogicController(); } VirtualDeviceConnectInfo ci = new VirtualDeviceConnectInfo(); ci.startConnected = false; scsi.key = 1000; scsi.controllerKey = 100; scsi.controllerKeySpecified = true; scsi.busNumber = 0; scsi.hotAddRemove = true; scsi.hotAddRemoveSpecified = true; scsi.scsiCtlrUnitNumber = 7; scsi.scsiCtlrUnitNumberSpecified = true; scsi.sharedBus = VirtualSCSISharing.noSharing; scsi.unitNumber = 2; scsi.unitNumberSpecified = true; scsi.connectable = ci; VirtualDeviceConfigSpec dcs = new VirtualDeviceConfigSpec(); dcs.device = scsi; dcs.operation = VirtualDeviceConfigSpecOperation.add; dcs.operationSpecified = true; return(dcs); }
private static VirtualDeviceConfigSpec GetDisk(ref int key, string path, int controllerKey, int unitnumber) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualDiskFlatVer2BackingInfo diskbacking = new VirtualDiskFlatVer2BackingInfo(); diskbacking.fileName = path; diskbacking.diskMode = "persistent"; VirtualDisk disk = new VirtualDisk(); disk.key = key--; disk.backing = diskbacking; disk.controllerKey = controllerKey; disk.controllerKeySpecified = true; disk.connectable = new VirtualDeviceConnectInfo(); disk.connectable.connected = true; disk.connectable.startConnected = true; disk.unitNumber = unitnumber; disk.unitNumberSpecified = true; devicespec = new VirtualDeviceConfigSpec(); devicespec.device = disk; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
private static VirtualDeviceConfigSpec GetFloppy(ref int key, string name) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualFloppyImageBackingInfo diskbacking = new VirtualFloppyImageBackingInfo(); diskbacking.fileName = name; VirtualFloppy disk = new VirtualFloppy(); disk.key = key--; disk.backing = diskbacking; disk.connectable = new VirtualDeviceConnectInfo(); disk.connectable.connected = true; disk.connectable.startConnected = true; //disk.unitNumber = unitnumber; //disk.unitNumberSpecified = true; devicespec = new VirtualDeviceConfigSpec(); devicespec.device = disk; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
// private static VirtualDeviceConfigSpec GetNetworkSerialPort(ref int key, string name) // { // VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); // VirtualSerialPortURIBackingInfo backing = new VirtualSerialPortURIBackingInfo(); // backing.direction = "server"; // backing.serviceURI = "vSPC.py"; // backing.proxyURI = name; // VirtualSerialPort device = new VirtualSerialPort(); // device.key = key--; // device.backing = backing; // device.connectable = new VirtualDeviceConnectInfo(); // device.connectable.connected = true; // device.connectable.startConnected = true; // //disk.unitNumber = unitnumber; // //disk.unitNumberSpecified = true; // devicespec = new VirtualDeviceConfigSpec(); // devicespec.device = device; // devicespec.operation = VirtualDeviceConfigSpecOperation.add; // devicespec.operationSpecified = true; // return devicespec; // } private static VirtualDeviceConfigSpec GetVideoController(ref int key, int ramKB) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualMachineVideoCard card = new VirtualMachineVideoCard(); card.key = key--; if (ramKB > 0) { card.videoRamSizeInKB = ramKB * 1024; card.videoRamSizeInKBSpecified = true; } else { card.useAutoDetect = true; card.useAutoDetectSpecified = true; } devicespec = new VirtualDeviceConfigSpec(); devicespec.device = card; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
public void ChangeVMNetworkAdapterPortGroup(string vmName, string oldNetworkName, string newNetworkName) { try { VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault(); if (vm != null) { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); VirtualEthernetCard nic = null; VirtualDevice[] nics = vm.Config.Hardware.Device.Where(device => device is VMware.Vim.VirtualEthernetCard).Select(vnic => vnic as VirtualEthernetCard).ToArray(); nicSpec.Operation = VirtualDeviceConfigSpecOperation.edit; nic = (VirtualEthernetCard)nics.Where(vnic => vnic.DeviceInfo.Summary.Equals(oldNetworkName)).FirstOrDefault(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); Network vNic = new Network(vSphereClient, vm.Runtime.Host); nicBacking.Network = vNic.MoRef; nicBacking.DeviceName = newNetworkName; if (nic != null) { nic.Backing = nicBacking; nicSpec.Device = nic; } VirtualDeviceConfigSpec[] nicSpecArray = { nicSpec }; vmConfigSpec.DeviceChange = nicSpecArray; vm.ReconfigVM_Task(vmConfigSpec); } } catch (VimException e) { lock (m_lock) { WriteLogText(logWriter, e.Message.ToString()); } } }
public void RemoveNetworkAdapterFromVM(string vmName, string networkName) { try { VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault(); if (vm != null) { VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); VirtualEthernetCard nic = null; VirtualDevice[] nics = vm.Config.Hardware.Device.Where(device => device is VMware.Vim.VirtualEthernetCard).Select(vnic => vnic as VirtualEthernetCard).ToArray(); nicSpec.Operation = VirtualDeviceConfigSpecOperation.remove; nic = (VirtualEthernetCard)nics.Where(vnic => vnic.DeviceInfo.Summary.Equals(networkName)).FirstOrDefault(); if (nic != null) { nicSpec.Device = nic; } VirtualDeviceConfigSpec[] nicSpecArray = { nicSpec }; vmConfigSpec.DeviceChange = nicSpecArray; vm.ReconfigVM_Task(vmConfigSpec); } } catch (VimException e) { lock (m_lock) { WriteLogText(logWriter, e.Message.ToString()); } } }
private static VirtualDeviceConfigSpec GetCdrom(ref int key, int controllerkey, string iso) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); // CD ROM VirtualCdrom cdrom = new VirtualCdrom(); cdrom.key = key--; VirtualCdromIsoBackingInfo isobacking = new VirtualCdromIsoBackingInfo(); isobacking.fileName = iso; cdrom.backing = isobacking; cdrom.controllerKey = controllerkey; cdrom.controllerKeySpecified = true; cdrom.connectable = new VirtualDeviceConnectInfo(); cdrom.connectable.startConnected = true; devicespec = new VirtualDeviceConfigSpec(); devicespec.device = cdrom; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
private static VirtualDeviceConfigSpec GetEthernetAdapter(ref int key, VmNet nic, string dvsuuid) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualEthernetCard eth = new VirtualE1000(); if (nic.Type == "pcnet32") { eth = new VirtualPCNet32(); } if (nic.Type == "vmx3") { eth = new VirtualVmxnet3(); } if (nic.Type == "e1000e") { eth = new VirtualE1000e(); } eth.key = key--; if (nic.Mac.HasValue()) { eth.addressType = "Manual"; eth.macAddress = nic.Mac; } if (nic.Net.StartsWith("nsx.")) { eth.backing = new VirtualEthernetCardOpaqueNetworkBackingInfo { opaqueNetworkId = nic.Key.Tag(), opaqueNetworkType = nic.Key.Untagged() }; } else if (dvsuuid.HasValue()) { eth.backing = new VirtualEthernetCardDistributedVirtualPortBackingInfo { port = new DistributedVirtualSwitchPortConnection { switchUuid = dvsuuid, portgroupKey = nic.Key.AsReference().Value } }; } else { eth.backing = new VirtualEthernetCardNetworkBackingInfo { deviceName = nic.Key }; } devicespec = new VirtualDeviceConfigSpec(); devicespec.device = eth; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
private VirtualDeviceConfigSpec getCDDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec cdSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); if (ops.Equals("add")) { cdSpec.operation = VirtualDeviceConfigSpecOperation.add; cdSpec.operationSpecified = true; VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); DatastoreSummary dsum = getDataStoreSummary(); cdDeviceBacking.datastore = dsum.datastore; cdDeviceBacking.fileName = "[" + dsum.name + "] " + cb.get_option("value") + ".iso"; VirtualDevice vd = getIDEController(); cdrom.backing = cdDeviceBacking; cdrom.controllerKey = vd.key; cdrom.controllerKeySpecified = true; cdrom.unitNumber = -1; cdrom.unitNumberSpecified = true; cdrom.key = -100; cdSpec.device = cdrom; return(cdSpec); } else { VirtualCdrom cdRemove = null; VirtualDevice [] test = vmConfigInfo.hardware.device; cdSpec.operation = VirtualDeviceConfigSpecOperation.remove; cdSpec.operationSpecified = true; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( cb.get_option("value"))) { cdRemove = (VirtualCdrom)test[k]; } } if (cdRemove != null) { cdSpec.device = cdRemove; } else { Console.WriteLine("No device available " + cb.get_option("value")); return(null); } } return(cdSpec); }
public VirtualDeviceConfigSpec Disk(VMWare oVMWare, string _name, string _datastore, string _size, int _unit_number, int _controller_key, string _suffix) { // Get Datastores ManagedObjectReference datastoreRef = null; PropertySpec[] psDCarray = new PropertySpec[] { new PropertySpec() }; psDCarray[0].all = false; psDCarray[0].allSpecified = true; psDCarray[0].pathSet = new string[] { "datastore" }; psDCarray[0].type = "Datacenter"; PropertyFilterSpec spec = new PropertyFilterSpec(); spec.propSet = psDCarray; spec.objectSet = new ObjectSpec[] { new ObjectSpec() }; spec.objectSet[0].obj = oVMWare.GetDataCenter(); spec.objectSet[0].skip = true; ObjectContent[] ocary = oVMWare.GetService().RetrieveProperties(oVMWare.GetSic().propertyCollector, new PropertyFilterSpec[] { spec }); ManagedObjectReference[] datastores = null; foreach (ObjectContent oc in ocary) { datastores = (ManagedObjectReference[])oc.propSet[0].val; } if (datastores != null) { datastoreRef = datastores[0]; } // Create disk VirtualDisk disk = new VirtualDisk(); disk.key = 2000; disk.controllerKey = _controller_key; disk.controllerKeySpecified = true; disk.unitNumber = _unit_number; disk.unitNumberSpecified = true; VirtualDiskFlatVer2BackingInfo diskBack = new VirtualDiskFlatVer2BackingInfo(); diskBack.diskMode = "persistent"; diskBack.fileName = "[" + _datastore + "] " + _name.ToLower() + "/" + _name.ToLower() + _suffix + ".vmdk"; diskBack.datastore = datastoreRef; diskBack.thinProvisioned = false; diskBack.thinProvisionedSpecified = true; diskBack.writeThrough = false; diskBack.writeThroughSpecified = true; disk.backing = diskBack; disk.capacityInKB = long.Parse(_size); VirtualDeviceConfigSpec dcs = new VirtualDeviceConfigSpec(); dcs.device = disk; dcs.fileOperation = VirtualDeviceConfigSpecFileOperation.create; dcs.fileOperationSpecified = true; dcs.operation = VirtualDeviceConfigSpecOperation.add; dcs.operationSpecified = true; return(dcs); }
private VirtualDeviceConfigSpec getNICDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); if (ops.Equals("add")) { String networkName = getNetworkName(); if (networkName != null) { nicSpec.operation = VirtualDeviceConfigSpecOperation.add; nicSpec.operationSpecified = true; VirtualEthernetCard nic = new VirtualPCNet32(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.deviceName = networkName; nic.addressType = "generated"; nic.backing = nicBacking; nic.key = 4; nicSpec.device = nic; } else { return(null); } } else if (ops.Equals("remove")) { VirtualEthernetCard nic = null; VirtualDevice [] test = vmConfigInfo.hardware.device; nicSpec.operation = VirtualDeviceConfigSpecOperation.remove; nicSpec.operationSpecified = true; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( cb.get_option("value"))) { nic = (VirtualEthernetCard)test[k]; } } if (nic != null) { nicSpec.device = nic; } else { Console.WriteLine("No device available " + cb.get_option("value")); return(null); } } return(nicSpec); }
private static VirtualDeviceConfigSpec GetEthernetAdapter(ref int key, VmNet nic, string dvsuuid) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualEthernetCard eth = new VirtualE1000(); if (nic.Type == "pcnet32") { eth = new VirtualPCNet32(); } if (nic.Type == "vmx3") { eth = new VirtualVmxnet3(); } if (nic.Type == "e1000e") { eth = new VirtualE1000e(); } // VirtualEthernetCardNetworkBackingInfo ethbacking = new VirtualEthernetCardNetworkBackingInfo(); // ethbacking.deviceName = nic.Net; eth.key = key--; if (dvsuuid.HasValue()) { eth.backing = new VirtualEthernetCardDistributedVirtualPortBackingInfo { port = new DistributedVirtualSwitchPortConnection { switchUuid = dvsuuid, portgroupKey = nic.Net } } } ; else { eth.backing = new VirtualEthernetCardNetworkBackingInfo { deviceName = nic.Net } }; devicespec = new VirtualDeviceConfigSpec(); devicespec.device = eth; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
public void AddNetworkAdapterToVM(string vmName, string networkName) { try { VirtualMachine vm = this.GetVirtualMachines().Where(_vm => _vm.Name == vmName).FirstOrDefault(); if (vm != null) { Network vNic = new Network(vSphereClient, vm.Runtime.Host); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); if (networkName != null) { nicSpec.Operation = VirtualDeviceConfigSpecOperation.add; VirtualEthernetCard nic = new VirtualVmxnet(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.Network = vNic.MoRef; nicBacking.DeviceName = networkName; nic.AddressType = "generated"; nic.Backing = nicBacking; nic.Key = 4; nicSpec.Device = nic; } VirtualDeviceConfigSpec[] specs = { nicSpec }; VirtualMachineConfigSpec vmConfSpec = new VirtualMachineConfigSpec(); vmConfSpec.DeviceChange = specs; vm.ReconfigVM_Task(vmConfSpec); } } catch (VimException e) { lock (m_lock) { WriteLogText(logWriter, e.Message.ToString()); } } catch (Exception e) { lock (m_lock) { WriteLogText(logWriter, e.Message.ToString()); } } }
// private static VirtualDeviceConfigSpec GetIDEController(int key) // { // VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); // devicespec.device = new VirtualIDEController(); // devicespec.device.key = key; // devicespec.operation = VirtualDeviceConfigSpecOperation.add; // devicespec.operationSpecified = true; // return devicespec; // } private static VirtualDeviceConfigSpec GetSCSIController(ref int key, string type) { VirtualDeviceConfigSpec devicespec = new VirtualDeviceConfigSpec(); VirtualDevice device = null; // DISK CONTROLLER if (type.ToLower().EndsWith("sas")) { VirtualLsiLogicSASController sas = new VirtualLsiLogicSASController(); sas.busNumber = 0; sas.sharedBus = VirtualSCSISharing.noSharing; sas.key = key--; device = sas; } if (type.ToLower() == "lsilogic") { VirtualLsiLogicController controller = new VirtualLsiLogicController(); controller.busNumber = 0; controller.sharedBus = VirtualSCSISharing.noSharing; controller.key = key--; device = controller; } if (type.ToLower() == "buslogic") { VirtualBusLogicController bus = new VirtualBusLogicController(); bus.busNumber = 0; bus.sharedBus = VirtualSCSISharing.noSharing; bus.controllerKey = key--; device = bus; } devicespec.device = device; devicespec.operation = VirtualDeviceConfigSpecOperation.add; devicespec.operationSpecified = true; return(devicespec); }
private VirtualDeviceConfigSpec getCDDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec cdSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine,"config"); if(ops.Equals("add")) { cdSpec.operation = VirtualDeviceConfigSpecOperation.add; cdSpec.operationSpecified = true; VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); DatastoreSummary dsum = getDataStoreSummary(); cdDeviceBacking.datastore= dsum.datastore; cdDeviceBacking.fileName="["+dsum.name+"] "+cb.get_option("value")+".iso"; VirtualDevice vd = getIDEController(); cdrom.backing =cdDeviceBacking; cdrom.controllerKey = vd.key; cdrom.controllerKeySpecified = true; cdrom.unitNumber= -1; cdrom.unitNumberSpecified = true; cdrom.key= -100; cdSpec.device=cdrom; return cdSpec; } else { VirtualCdrom cdRemove = null; VirtualDevice [] test = vmConfigInfo.hardware.device; cdSpec.operation=VirtualDeviceConfigSpecOperation.remove; cdSpec.operationSpecified = true; for(int k=0;k<test.Length;k++){ if(test[k].deviceInfo.label.Equals( cb.get_option("value"))){ cdRemove = (VirtualCdrom)test[k]; } } if(cdRemove != null) { cdSpec.device=cdRemove; } else { Console.WriteLine("No device available " + cb.get_option("value")); return null; } } return cdSpec; }
protected void cmdProvision_Click(object sender, EventArgs e) { // // Ready to provision // // // Need a random number to pick a random virtual host to place the new vm on // Random rand = new Random(); // // Validate user entries // // // Do we have a value for the target vm? // if (txtTargetVm.Text == null || txtTargetVm.Text == "") { txtErrors.Text = "Please enter a name for the virtual machine."; Error_Panel.Visible = true; return; } // // Has a valid IP address been entered? // IPAddress theIp; bool ipResult = IPAddress.TryParse(txtIpAddress.Text, out theIp); if (ipResult != true) { txtErrors.Text = "Please enter a valid IP Address."; Error_Panel.Visible = true; return; } // // This does some basic checking on a subnet // IPAddress theMask; bool mskResult = IPAddress.TryParse(txtSubnet.Text, out theMask); if (mskResult != true) { txtErrors.Text = "Please enter a valid Subnet Mask."; Error_Panel.Visible = true; return; } // // Has a valid IP been entered for the gateway? // IPAddress theGateway; bool gwResult = IPAddress.TryParse(txtGateway.Text, out theGateway); if (gwResult != true) { txtErrors.Text = "Please entera valid IP Address for the default gateway."; Error_Panel.Visible = true; return; } // // Does a vm by this name already exist? // VimClient vimClient = ConnectServer(Globals.sViServer, Globals.sUsername, Globals.sPassword); List<VirtualMachine> chkVirtualMachines = GetVirtualMachines(vimClient, null, txtTargetVm.Text); if (chkVirtualMachines != null) { vimClient.Disconnect(); txtErrors.Text = "virtual machine " + txtTargetVm.Text + " already exists"; Error_Panel.Visible = true; return; } // // Need to parse the value of the dropdown // char[] splitChar = { '.' }; string[] specType = cboCustomizations.SelectedValue.Split(splitChar); // // Connect to selected datacenter // List<ClusterComputeResource> lstClusters = GetClusters(vimClient, cboClusters.SelectedItem.Text); List<Datacenter> lstDatacenters = GetDcFromCluster(vimClient, lstClusters[0].Parent.Value); Datacenter itmDatacenter = lstDatacenters[0]; // // Get a list of hosts in the selected cluster // List<HostSystem> lstHosts = GetHosts(vimClient, cboClusters.SelectedValue); // // Randomly pick host // HostSystem selectedHost = lstHosts[rand.Next(0, lstHosts.Count)]; txtResults.Text = "Host : " + selectedHost.Name + "\r\n"; // // Connect to selected vm to clone // List<VirtualMachine> lstVirtualMachines = GetVirtualMachines(vimClient, null, cboSourceVms.SelectedItem.Text); VirtualMachine itmVirtualMachine = lstVirtualMachines[0]; // // Make sure the spec file type matches the guest os // // // The commented code could be used to poweron a vm, check it's guestfamily and then turn it off. // //string GuestFamily = null; //if (itmVirtualMachine.Runtime.PowerState == VirtualMachinePowerState.poweredOff) //{ // // // // We can power on the vm to get the guestfamily property // // // itmVirtualMachine.PowerOnVM(null); // // // // Set the GuestFamily var // // // while (itmVirtualMachine.Guest.GuestFamily == null) // { // // // // Need to grab the current guest status from the vm // // // itmVirtualMachine.Reload(); // GuestFamily = itmVirtualMachine.Guest.GuestFamily; // } // // // // Turn the VM back off // // // itmVirtualMachine.PowerOffVM(); //} // // Added this test to accomodate cloning templates to vm's, per Ryan Lawrence. // if (!(chkTemplate.Checked)) { if (itmVirtualMachine.Guest.GuestFamily != null) { if ((itmVirtualMachine.Guest.GuestFamily).Contains(specType[specType.GetUpperBound(0)]) == false) { vimClient.Disconnect(); txtErrors.Text = "You specified a " + specType[specType.GetUpperBound(0)] + " spec file to clone a " + itmVirtualMachine.Guest.GuestFamily + " virtual machine."; Error_Panel.Visible = true; return; } } else { // // Sometimes the GuestFamily property isn't populated // vimClient.Disconnect(); txtErrors.Text = "The virtual machine " + itmVirtualMachine.Name.ToString() + " has no GuestFamily property populated, please power on this VM and verify that it's a supported Guest Os."; Error_Panel.Visible = true; return; } } txtResults.Text += "Source : " + itmVirtualMachine.Name + "\r\n"; // // Connect to the selected datastore // List<Datastore> lstDatastores = GetDataStore(vimClient, null, cboDatastores.SelectedItem.Text); Datastore itmDatastore = lstDatastores[0]; txtResults.Text += "Datastore : " + itmDatastore.Name + "\r\n"; // // Connect to portgroup // List<DistributedVirtualPortgroup> lstDvPortGroups = GetDVPortGroups(vimClient, itmDatacenter, cboPortGroups.SelectedItem.Text); DistributedVirtualPortgroup itmDvPortGroup = lstDvPortGroups[0]; txtResults.Text += "Portgroup : " + itmDvPortGroup.Name + "\r\n"; // // Connect to the customizationspec // CustomizationSpecItem itmSpecItem = GetCustomizationSpecItem(vimClient, cboCustomizations.SelectedItem.Text); txtResults.Text += "Spec : " + cboCustomizations.SelectedItem.Text + "\r\n"; // // Create a new VirtualMachineCloneSpec // VirtualMachineCloneSpec mySpec = new VirtualMachineCloneSpec(); mySpec.Location = new VirtualMachineRelocateSpec(); mySpec.Location.Datastore = itmDatastore.MoRef; mySpec.Location.Host = selectedHost.MoRef; // // Get resource pool for selected cluster // List<ResourcePool> lstResPools = GetResPools(vimClient, cboClusters.SelectedValue); ResourcePool itmResPool = lstResPools[0]; // // Assign resource pool to specitem // mySpec.Location.Pool = itmResPool.MoRef; // // Add selected CloneSpec customizations to this CloneSpec // mySpec.Customization = itmSpecItem.Spec; // // Handle hostname for either windows or linux // if (specType[specType.GetUpperBound(0)] == "Windows") { // // Create a windows sysprep object // CustomizationSysprep winIdent = (CustomizationSysprep)itmSpecItem.Spec.Identity; CustomizationFixedName hostname = new CustomizationFixedName(); hostname.Name = txtTargetVm.Text; winIdent.UserData.ComputerName = hostname; // // Store identity in this CloneSpec // mySpec.Customization.Identity = winIdent; } if (specType[specType.GetUpperBound(0)] == "Linux") { // // Create a Linux "sysprep" object // CustomizationLinuxPrep linIdent = (CustomizationLinuxPrep)itmSpecItem.Spec.Identity; CustomizationFixedName hostname = new CustomizationFixedName(); hostname.Name = txtTargetVm.Text; linIdent.HostName = hostname; // // Uncomment the line below to add a suffix to linux vm's // // linIdent.Domain = WebConfigurationManager.AppSettings["dnsSuffix"].ToString(); // // Store identity in this CloneSpec // mySpec.Customization.Identity = linIdent; } // // Create a new ConfigSpec // mySpec.Config = new VirtualMachineConfigSpec(); // // Set number of CPU's // int numCpus = new int(); numCpus = Convert.ToInt16(cboCpus.SelectedValue); mySpec.Config.NumCPUs = numCpus; txtResults.Text += "CPU : " + numCpus + "\r\n"; // // Set amount of RAM // long memoryMb = new long(); memoryMb = (long)(Convert.ToInt16(cboRam.SelectedValue) * 1024); mySpec.Config.MemoryMB = memoryMb; txtResults.Text += "Ram : " + memoryMb + "\r\n"; // // Only handle the first network card // mySpec.Customization.NicSettingMap = new CustomizationAdapterMapping[1]; mySpec.Customization.NicSettingMap[0] = new CustomizationAdapterMapping(); // // Read in the DNS from web.config and assign // string[] ipDns = new string[1]; ipDns[0] = txtDnsServer.Text; mySpec.Customization.GlobalIPSettings = new CustomizationGlobalIPSettings(); mySpec.Customization.GlobalIPSettings.DnsServerList = ipDns; txtResults.Text += "DNS : " + ipDns[0] + "\r\n"; // // Create a new networkDevice // VirtualDevice networkDevice = new VirtualDevice(); foreach (VirtualDevice vDevice in itmVirtualMachine.Config.Hardware.Device) { // // get nic on vm // if (vDevice.DeviceInfo.Label.Contains("Network")) { networkDevice = vDevice; } } // // Create a DeviceSpec // VirtualDeviceConfigSpec[] devSpec = new VirtualDeviceConfigSpec[0]; mySpec.Config.DeviceChange = new VirtualDeviceConfigSpec[1]; mySpec.Config.DeviceChange[0] = new VirtualDeviceConfigSpec(); mySpec.Config.DeviceChange[0].Operation = VirtualDeviceConfigSpecOperation.edit; mySpec.Config.DeviceChange[0].Device = networkDevice; // // Define network settings for the new vm // // // Assign IP Address // CustomizationFixedIp ipAddress = new CustomizationFixedIp(); ipAddress.IpAddress = txtIpAddress.Text; mySpec.Customization.NicSettingMap[0].Adapter = new CustomizationIPSettings(); txtResults.Text += "IP : " + txtIpAddress.Text + "\r\n"; // // Assign subnet mask // mySpec.Customization.NicSettingMap[0].Adapter.Ip = ipAddress; mySpec.Customization.NicSettingMap[0].Adapter.SubnetMask = txtSubnet.Text; txtResults.Text += "Subnet : " + txtSubnet.Text + "\r\n"; // // Assign default gateway // string[] ipGateway = new string[1]; ipGateway[0] = txtGateway.Text; mySpec.Customization.NicSettingMap[0].Adapter.Gateway = ipGateway; txtResults.Text += "Gateway : " + txtGateway.Text + "\r\n"; // // Create network backing information // VirtualEthernetCardDistributedVirtualPortBackingInfo nicBack = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); nicBack.Port = new DistributedVirtualSwitchPortConnection(); // // Connect to the virtual switch // VmwareDistributedVirtualSwitch dvSwitch = GetDvSwitch(vimClient, itmDvPortGroup.Config.DistributedVirtualSwitch); // // Assign the proper switch port // nicBack.Port.SwitchUuid = dvSwitch.Uuid; // // Connect the network card to proper port group // nicBack.Port.PortgroupKey = itmDvPortGroup.MoRef.Value; mySpec.Config.DeviceChange[0].Device.Backing = nicBack; // // Enable the network card at bootup // mySpec.Config.DeviceChange[0].Device.Connectable = new VirtualDeviceConnectInfo(); mySpec.Config.DeviceChange[0].Device.Connectable.StartConnected = true; mySpec.Config.DeviceChange[0].Device.Connectable.AllowGuestControl = true; mySpec.Config.DeviceChange[0].Device.Connectable.Connected = true; // // Get the vmfolder from the datacenter // // // Perform the clone // ManagedObjectReference taskMoRef = itmVirtualMachine.CloneVM_Task(itmDatacenter.VmFolder, txtTargetVm.Text, mySpec); Task cloneVmTask = new Task(vimClient, taskMoRef); // // The following will make the browser appear to hang, I need to hide this panel, and show a working panel // ManagedObjectReference clonedMorRef = (ManagedObjectReference)vimClient.WaitForTask(cloneVmTask.MoRef); // // Connect to the VM in order to set the custom fields // List<VirtualMachine> clonedVMs = GetVirtualMachines(vimClient, null, txtTargetVm.Text); VirtualMachine clonedVM = clonedVMs[0]; NameValueCollection vmFilter = new NameValueCollection(); vmFilter.Add("name",txtTargetVm.Text); EntityViewBase vmViewBase = vimClient.FindEntityView(typeof(VirtualMachine),null,vmFilter,null); ManagedEntity vmEntity = new ManagedEntity(vimClient, clonedVM.MoRef); CustomFieldsManager fieldManager = new CustomFieldsManager(vimClient, clonedVM.MoRef); // // One or more custom field names could be stored in the web.config and processed in some fashion // foreach (CustomFieldDef thisField in clonedVM.AvailableField) { if (thisField.Name.Equals("CreatedBy")) { fieldManager.SetField(clonedVM.MoRef, 1, txtUsername.Text); } } vimClient.Disconnect(); // // Hide the vm controls and show the result box // Vm_Panel.Visible = false; Results_Panel.Visible = true; }
private void reConfig() { String deviceType = cb.get_option("device"); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); if (deviceType.Equals("memory")) { Console.WriteLine("Reconfiguring The Virtual Machine For Memory Update " + cb.get_option("vmname")); try { vmConfigSpec.memoryAllocation = getShares(); } catch (Exception nfe) { Console.WriteLine("Value of Memory update must " + "be either Custom or Integer"); return; } } else if (deviceType.Equals("cpu")) { Console.WriteLine("Reconfiguring The Virtual Machine For CPU Update " + cb.get_option("vmname")); try { vmConfigSpec.cpuAllocation = getShares(); } catch (Exception nfe) { Console.WriteLine("Value of CPU update must " + "be either Custom or Integer"); return; } } else if (deviceType.Equals("disk")) { Console.WriteLine("Reconfiguring The Virtual Machine For Disk Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec vdiskSpec = getDiskDeviceConfigSpec(); if (vdiskSpec != null) { VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); int ckey = -1; VirtualDevice[] test = vmConfigInfo.hardware.device; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( "SCSI Controller 0")) { ckey = test[k].key; } } if (ckey == -1) { int diskCtlrKey = 1; VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec(); scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add; scsiCtrlSpec.operationSpecified = true; VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController(); scsiCtrl.busNumber = 0; scsiCtrlSpec.device = scsiCtrl; scsiCtrl.key = diskCtlrKey; scsiCtrl.sharedBus = VirtualSCSISharing.physicalSharing; String ctlrType = scsiCtrl.GetType().Name; vdiskSpec.device.controllerKey = scsiCtrl.key; VirtualDeviceConfigSpec[] vdiskSpecArray = { scsiCtrlSpec, vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } else { vdiskSpec.device.controllerKey = ckey; VirtualDeviceConfigSpec[] vdiskSpecArray = { vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } } else { return; } } else if (deviceType.Equals("nic")) { Console.WriteLine("Reconfiguring The Virtual Machine For NIC Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec nicSpec = getNICDeviceConfigSpec(); if (nicSpec != null) { VirtualDeviceConfigSpec [] nicSpecArray = { nicSpec }; vmConfigSpec.deviceChange = nicSpecArray; } else { return; } } else if (deviceType.Equals("cd")) { Console.WriteLine("Reconfiguring The Virtual Machine For CD Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec cdSpec = getCDDeviceConfigSpec(); if (cdSpec != null) { VirtualDeviceConfigSpec [] cdSpecArray = { cdSpec }; vmConfigSpec.deviceChange = cdSpecArray; } else { return; } } else { Console.WriteLine("Invlaid device type [memory|cpu|disk|nic|cd]"); return; } ManagedObjectReference tmor = cb.getConnection()._service.ReconfigVM_Task( _virtualMachine, vmConfigSpec); monitorTask(tmor); }
public static VirtualMachineConfigSpec TemplateToVmSpec(VmTemplate template, string datastore, string dvsuuid) { int key = -101, idekey = 200; VirtualMachineConfigSpec vmcs = new VirtualMachineConfigSpec(); List <VirtualDeviceConfigSpec> devices = new List <VirtualDeviceConfigSpec>(); vmcs.name = template.Name; vmcs.extraConfig = GetExtraConfig(template); vmcs.AddRam(template.Ram); vmcs.AddCpu(template.Cpu); vmcs.AddBootOption(Math.Max(template.Delay, 10)); vmcs.version = (template.Version.HasValue()) ? template.Version : null; vmcs.guestId = (template.Guest.HasValue() ? template.Guest : "other"); if (!vmcs.guestId.EndsWith("Guest")) { vmcs.guestId += "Guest"; } if (datastore.HasValue()) { vmcs.files = new VirtualMachineFileInfo { vmPathName = $"{datastore}/{template.Name}/{template.Name}.vmx" }; } //can't actually be applied via ExtraConfig if (template.GuestSettings.Length > 0 && template.GuestSettings.Any(s => s.Key == "vhv.enable" && s.Value == "true")) { vmcs.nestedHVEnabled = true; vmcs.nestedHVEnabledSpecified = true; } //video card devices.Add(GetVideoController(ref key, template.VideoRam)); //floppy disk if (template.Floppy.HasValue()) { devices.Add(GetFloppy(ref key, template.Floppy)); } //nics foreach (VmNet nic in template.Eth) { devices.Add(GetEthernetAdapter(ref key, nic, dvsuuid)); } // //network serial port // if (!String.IsNullOrEmpty(template.FindOne("nsp").Value())) // devices.Add(GetNetworkSerialPort(ref key, template.FindOne("nsp").Value())); //controller int controllerKey = 0, count = 0; foreach (VmDisk disk in template.Disks) { if (controllerKey == 0) { if (disk.Controller == "ide") { controllerKey = idekey; } else { VirtualDeviceConfigSpec controller = GetSCSIController(ref key, disk.Controller); controllerKey = controller.device.key; devices.Add(controller); } } devices.Add(GetDisk(ref key, disk.Path, controllerKey, count++)); } //iso devices.Add(GetCdrom(ref key, idekey, (template.Iso.HasValue() ? template.Iso : "[iso] null.iso"))); //add all devices to spec vmcs.deviceChange = devices.ToArray(); return(vmcs); }
private VirtualDeviceConfigSpec getDiskDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); if (ops.Equals("add")) { VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); String dsName = getDataStoreName(int.Parse(cb.get_option("disksize"))); int ckey = -1; int unitNumber = 0; VirtualDevice [] test = vmConfigInfo.hardware.device; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( "SCSI Controller 0")) { ckey = test[k].key; } } unitNumber = test.Length + 1; String fileName = "[" + dsName + "] " + cb.get_option("vmname") + "/" + cb.get_option("value") + ".vmdk"; diskfileBacking.fileName = fileName; diskfileBacking.diskMode = cb.get_option("diskmode"); disk.controllerKey = ckey; disk.unitNumber = unitNumber; disk.controllerKeySpecified = true; disk.unitNumberSpecified = true; disk.backing = diskfileBacking; int size = 1024 * (int.Parse(cb.get_option("disksize"))); disk.capacityInKB = size; disk.key = 0; diskSpec.operation = VirtualDeviceConfigSpecOperation.add; diskSpec.fileOperation = VirtualDeviceConfigSpecFileOperation.create; diskSpec.fileOperationSpecified = true; diskSpec.operationSpecified = true; diskSpec.device = disk; } else if (ops.Equals("remove")) { VirtualDisk disk = null; VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); VirtualDevice [] test = vmConfigInfo.hardware.device; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( cb.get_option("value"))) { disk = (VirtualDisk)test[k]; } } if (disk != null) { diskSpec.operation = VirtualDeviceConfigSpecOperation.remove; diskSpec.operationSpecified = true; diskSpec.fileOperation = VirtualDeviceConfigSpecFileOperation.destroy; diskSpec.fileOperationSpecified = true; diskSpec.device = disk; } else { Console.WriteLine("No device found " + cb.get_option("value")); return(null); } } return(diskSpec); }
protected void cmdProvision_Click(object sender, EventArgs e) { // // Ready to provision // // // Populate the moRef objects with actual values // Globals.mySourceVM = new ManagedObjectReference(cboSourceVms.SelectedItem.Value); Globals.myCustomization = new ManagedObjectReference(cboCustomizations.SelectedItem.Value); Globals.myCluster = new ManagedObjectReference(cboClusters.SelectedItem.Value); Globals.myDatastore = new ManagedObjectReference(cboDatastores.SelectedItem.Value); Globals.myPortGroup = new ManagedObjectReference(cboPortGroups.SelectedItem.Value); // // The idea of using the page to do more than one VM failed rather miserably // I'll remove this code as I migrate to using moRefs for everything. // char[] splitChar; string targetVM = txtTargetVm.Text; Results_Panel.Visible = false; string targetIP = txtIpAddress.Text; // // Need a random number to pick a random virtual host to place the new vm on // Random rand = new Random(); // // Validate user entries // // // Do we have a value for the target vm? // if (targetVM == null || targetVM == "") { txtErrors.Text = "Please enter a name for the virtual machine."; Error_Panel.Visible = true; return; } // // Make sure that we don't create a machine with a longer name than what netbios supports // if (targetVM.Length > 15) { txtErrors.Text = "Please enter a NetBIOS name shorter than 15 characters for the virtual machine."; Error_Panel.Visible = true; return; } // // http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2009820 // if (targetVM.Contains("_")) { txtErrors.Text = "Underscore characters not supported for cloning."; Error_Panel.Visible = true; return; } // // Has a valid IP address been entered? // IPAddress theIp; bool ipResult = IPAddress.TryParse(targetIP, out theIp); if (ipResult != true) { txtErrors.Text = "Please enter a valid IP Address."; Error_Panel.Visible = true; return; } // // This does some basic checking on a subnet // IPAddress theMask; bool mskResult = IPAddress.TryParse(txtSubnet.Text, out theMask); if (mskResult != true) { txtErrors.Text = "Please enter a valid Subnet Mask."; Error_Panel.Visible = true; return; } // // Has a valid IP been entered for the gateway? // IPAddress theGateway; bool gwResult = IPAddress.TryParse(txtGateway.Text, out theGateway); if (gwResult != true) { txtErrors.Text = "Please entera valid IP Address for the default gateway."; Error_Panel.Visible = true; return; } // // Does a vm by this name already exist? // VimClient vimClient = functions.ConnectServer(Globals.sViServer, Globals.sUsername, Globals.sPassword); NameValueCollection filter = new NameValueCollection(); filter.Add("name", targetVM); VirtualMachine chkVirtualMachine = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null); filter.Remove("name"); if (chkVirtualMachine != null) { vimClient.Disconnect(); txtErrors.Text = "virtual machine " + targetVM + " already exists"; Error_Panel.Visible = true; return; } // // Need to parse the value of the dropdown // splitChar = new char[] { '.' }; string[] specType = cboCustomizations.SelectedValue.Split(splitChar); // // Connect to selected datacenter // ClusterComputeResource itmCluster = functions.GetObject<ClusterComputeResource>(vimClient, Globals.myCluster, null); filter.Add("hostFolder", itmCluster.Parent.Value); Datacenter itmDatacenter = functions.GetEntity<Datacenter>(vimClient, null, filter, null); filter.Remove("hostFolder"); // // Get a list of hosts in the selected cluster // ManagedObjectReference[] lstHosts = itmCluster.Host; // // Randomly pick host // HostSystem selectedHost = functions.GetObject<HostSystem>(vimClient, lstHosts[rand.Next(0, lstHosts.Count())], null); txtResults.Text = "Host : " + selectedHost.Name + "\r\n"; // // Connect to selected vm to clone // filter.Add("name", cboSourceVms.SelectedItem.Text); VirtualMachine itmVirtualMachine = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null); filter.Remove("name"); // // Make sure the spec file type matches the guest os // // // The commented code could be used to poweron a vm, check it's guestfamily and then turn it off. // //string GuestFamily = null; //if (itmVirtualMachine.Runtime.PowerState == VirtualMachinePowerState.poweredOff) //{ // // // // We can power on the vm to get the guestfamily property // // // itmVirtualMachine.PowerOnVM(null); // // // // Set the GuestFamily var // // // while (itmVirtualMachine.Guest.GuestFamily == null) // { // // // // Need to grab the current guest status from the vm // // // itmVirtualMachine.Reload(); // GuestFamily = itmVirtualMachine.Guest.GuestFamily; // } // // // // Turn the VM back off // // // itmVirtualMachine.PowerOffVM(); //} // // Added this test to accomodate cloning templates to vm's, per Ryan Lawrence. // if (!(chkTemplate.Checked)) { if (itmVirtualMachine.Guest.GuestFamily != null) { string GuestFamily = itmVirtualMachine.Guest.GuestFamily.ToLower(); string TargetType = specType[specType.GetUpperBound(0)].ToLower(); if (GuestFamily.Contains(TargetType) == false) { vimClient.Disconnect(); txtErrors.Text = "You specified a " + specType[specType.GetUpperBound(0)] + " spec file to clone a " + itmVirtualMachine.Guest.GuestFamily + " virtual machine."; Error_Panel.Visible = true; return; } } else { // // Sometimes the GuestFamily property isn't populated // vimClient.Disconnect(); txtErrors.Text = "The virtual machine " + itmVirtualMachine.Name.ToString() + " has no GuestFamily property populated, please power on this VM and verify that it's a supported Guest Os."; Error_Panel.Visible = true; return; } } txtResults.Text += "Source : " + itmVirtualMachine.Name + "\r\n"; // // Connect to the selected datastore // filter.Add("name", cboDatastores.SelectedItem.Text); Datastore itmDatastore = functions.GetEntity<Datastore>(vimClient, null, filter, null); filter.Remove("name"); txtResults.Text += "Datastore : " + itmDatastore.Name + "\r\n"; // // Connect to portgroup // filter.Add("name", cboPortGroups.SelectedItem.Text); DistributedVirtualPortgroup itmDvPortGroup = functions.GetEntity<DistributedVirtualPortgroup>(vimClient, null, filter, null); filter.Remove("name"); txtResults.Text += "Portgroup : " + itmDvPortGroup.Name + "\r\n"; // // Connect to the customizationspec // CustomizationSpecManager specManager = functions.GetObject<CustomizationSpecManager>(vimClient, vimClient.ServiceContent.CustomizationSpecManager, null); CustomizationSpecItem itmCustomizationSpecItem = specManager.GetCustomizationSpec(cboCustomizations.SelectedItem.Text); txtResults.Text += "Spec : " + cboCustomizations.SelectedItem.Text + "\r\n"; // // Create a new VirtualMachineCloneSpec // VirtualMachineCloneSpec mySpec = new VirtualMachineCloneSpec(); mySpec.Location = new VirtualMachineRelocateSpec(); mySpec.Location.Datastore = itmDatastore.MoRef; mySpec.Location.Host = selectedHost.MoRef; // // Get resource pool for selected cluster // filter.Add("parent", itmCluster.Parent.ToString()); ResourcePool itmResPool = functions.GetObject<ResourcePool>(vimClient, itmCluster.ResourcePool, null); filter.Remove("parent"); // // Assign resource pool to specitem // mySpec.Location.Pool = itmResPool.MoRef; // // Add selected CloneSpec customizations to this CloneSpec // mySpec.Customization = itmCustomizationSpecItem.Spec; // // Handle hostname for either windows or linux // if (specType[specType.GetUpperBound(0)] == "Windows") { // // Create a windows sysprep object // CustomizationSysprep winIdent = (CustomizationSysprep)itmCustomizationSpecItem.Spec.Identity; CustomizationFixedName hostname = new CustomizationFixedName(); hostname.Name = targetVM; winIdent.UserData.ComputerName = hostname; // // Store identity in this CloneSpec // mySpec.Customization.Identity = winIdent; } if (specType[specType.GetUpperBound(0)] == "Linux") { // // Create a Linux "sysprep" object // CustomizationLinuxPrep linIdent = (CustomizationLinuxPrep)itmCustomizationSpecItem.Spec.Identity; CustomizationFixedName hostname = new CustomizationFixedName(); hostname.Name = targetVM; linIdent.HostName = hostname; // // Uncomment the line below to add a suffix to linux vm's // // linIdent.Domain = WebConfigurationManager.AppSettings["dnsSuffix"].ToString(); // // Store identity in this CloneSpec // mySpec.Customization.Identity = linIdent; } // // Create a new ConfigSpec // mySpec.Config = new VirtualMachineConfigSpec(); // // Set number of CPU's // int numCpus = new int(); numCpus = Convert.ToInt16(cboCpus.SelectedValue); mySpec.Config.NumCPUs = numCpus; txtResults.Text += "CPU : " + numCpus + "\r\n"; // // Set amount of RAM // long memoryMb = new long(); memoryMb = (long)(Convert.ToInt16(cboRam.SelectedValue) * 1024); mySpec.Config.MemoryMB = memoryMb; txtResults.Text += "Ram : " + memoryMb + "\r\n"; // // Only handle the first network card // mySpec.Customization.NicSettingMap = new CustomizationAdapterMapping[1]; mySpec.Customization.NicSettingMap[0] = new CustomizationAdapterMapping(); // // Read in the DNS from web.config and assign // string[] ipDns = new string[1]; ipDns[0] = txtDnsServer.Text; mySpec.Customization.GlobalIPSettings = new CustomizationGlobalIPSettings(); mySpec.Customization.GlobalIPSettings.DnsServerList = ipDns; txtResults.Text += "DNS : " + ipDns[0] + "\r\n"; // // Create a new networkDevice // VirtualDevice networkDevice = new VirtualDevice(); foreach (VirtualDevice vDevice in itmVirtualMachine.Config.Hardware.Device) { // // get nic on vm // if (vDevice.DeviceInfo.Label.Contains("Network")) { networkDevice = vDevice; } } // // Create a DeviceSpec // VirtualDeviceConfigSpec[] devSpec = new VirtualDeviceConfigSpec[0]; mySpec.Config.DeviceChange = new VirtualDeviceConfigSpec[1]; mySpec.Config.DeviceChange[0] = new VirtualDeviceConfigSpec(); mySpec.Config.DeviceChange[0].Operation = VirtualDeviceConfigSpecOperation.edit; mySpec.Config.DeviceChange[0].Device = networkDevice; // // Define network settings for the new vm // // // Assign IP Address // CustomizationFixedIp ipAddress = new CustomizationFixedIp(); ipAddress.IpAddress = targetIP; mySpec.Customization.NicSettingMap[0].Adapter = new CustomizationIPSettings(); txtResults.Text += "IP : " + targetIP + "\r\n"; // // Assign subnet mask // mySpec.Customization.NicSettingMap[0].Adapter.Ip = ipAddress; mySpec.Customization.NicSettingMap[0].Adapter.SubnetMask = txtSubnet.Text; txtResults.Text += "Subnet : " + txtSubnet.Text + "\r\n"; // // Assign default gateway // string[] ipGateway = new string[1]; ipGateway[0] = txtGateway.Text; mySpec.Customization.NicSettingMap[0].Adapter.Gateway = ipGateway; txtResults.Text += "Gateway : " + txtGateway.Text + "\r\n"; // // Create network backing information // VirtualEthernetCardDistributedVirtualPortBackingInfo nicBack = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); nicBack.Port = new DistributedVirtualSwitchPortConnection(); // // Connect to the virtual switch // VmwareDistributedVirtualSwitch dvSwitch = functions.GetObject<VmwareDistributedVirtualSwitch>(vimClient, itmDvPortGroup.Config.DistributedVirtualSwitch, null); // // Assign the proper switch port // nicBack.Port.SwitchUuid = dvSwitch.Uuid; // // Connect the network card to proper port group // nicBack.Port.PortgroupKey = itmDvPortGroup.MoRef.Value; mySpec.Config.DeviceChange[0].Device.Backing = nicBack; // // Enable the network card at bootup // mySpec.Config.DeviceChange[0].Device.Connectable = new VirtualDeviceConnectInfo(); mySpec.Config.DeviceChange[0].Device.Connectable.StartConnected = true; mySpec.Config.DeviceChange[0].Device.Connectable.AllowGuestControl = true; mySpec.Config.DeviceChange[0].Device.Connectable.Connected = true; // // Get the vmfolder from the datacenter // // // Perform the clone // txtWorking.Text = "Currently cloning " + targetVM + " please wait."; Working_Panel.Visible = true; Globals.myTask = itmVirtualMachine.CloneVM_Task(itmDatacenter.VmFolder, targetVM, mySpec); Task cloneVmTask = new Task(vimClient, Globals.myTask); // // The following will make the browser appear to hang, I need to hide this panel, and show a working panel // Globals.myClone = (ManagedObjectReference)vimClient.WaitForTask(cloneVmTask.MoRef); //// //// Connect to the VM in order to set the custom fields //// Custom Fields are only available when connecting to Vsphere, and not to an individual esxi host //// //filter.Add("name", targetVM); //VirtualMachine clonedVM = functions.GetEntity<VirtualMachine>(vimClient, null, filter, null); //filter.Remove("name"); //// //// We need to get a list of the Custom Fields from vsphere, that information is stored in ServiceContent.CustomFieldsManager //// //CustomFieldsManager fieldManager = functions.GetObject<CustomFieldsManager>(vimClient, vimClient.ServiceContent.CustomFieldsManager, null); //// //// One or more custom field names could be stored in the web.config and processed in some fashion //// //foreach (CustomFieldDef thisField in fieldManager.Field) //{ // // // // These fields exist in my test environment, you will need to use your own inside the quotes // // // if (thisField.Name.Equals("CreatedBy")) // { // fieldManager.SetField(clonedVM.MoRef, thisField.Key, txtUsername.Text); // } // if (thisField.Name.Equals("CreatedOn")) // { // fieldManager.SetField(clonedVM.MoRef, thisField.Key, System.DateTime.Now.ToString()); // } //} vimClient.Disconnect(); // // Hide the vm controls and show the result box // Working_Panel.Visible = false; Vm_Panel.Visible = false; Results_Panel.Visible = true; }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); string strName = "healytest2"; string strCluster = "CDALVMTEST01"; string strDatastore1 = "dt01-ibm-lun1"; string strDatastore2 = ""; string strVLAN = "VLAN52"; string strPortGroupName = "dvPortGroup255"; string strMACAddress = ""; string strResourcePool = ""; string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_ENT"; string strMDTbuildDB = "ServerShare"; double dblDriveC = 27.5; double dblDrive2 = 2.5; string strVMguestOS = "winNetEnterprise64Guest"; intEnvironment = 999; string strConnect = oVMWare.ConnectDEBUG("https://wdsvt100a/sdk", intEnvironment, "PNC"); if (Request.QueryString["old"] != null) { strName = "healytest"; strCluster = "ohcinxcv4003"; strDatastore1 = "CINDSSVCN40063"; strVLAN = "vlan250net"; intEnvironment = 3; strConnect = oVMWare.ConnectDEBUG("https://ohcinutl4003/sdk", intEnvironment, "Dalton"); } if (Request.QueryString["w"] != null) { strName = "healytest2"; strCluster = "CLEVDTLAB01"; strDatastore1 = "VDItest"; strDatastore2 = "pagefile01"; strPortGroupName = "dvPortGroup"; strResourcePool = "VDI"; strMDTos = "DesktopWABEx86"; strMDTtask = "VDIXP"; strMDTbuildDB = "DesktopDeploymentShare"; strVMguestOS = "windows7_64Guest"; strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", intEnvironment, "PNC-TestLab"); } if (Request.QueryString["t"] != null) { strName = "healyTest2012"; strCluster = "CLESVTLAB01"; dblDriveC = 45.00; strDatastore1 = "CTVXN00008"; strDatastore2 = "CTVXN00008"; dblDrive2 = 10.00; strPortGroupName = "dvPortGroup5"; // DHCP enabled strMDTos = "WABEx64"; strMDTtask = "W2K8R2_STD"; strMDTbuildDB = "ServerShare"; strVMguestOS = "windows8Server64Guest"; strConnect = oVMWare.ConnectDEBUG("https://wcsvt013a.pnceng.pvt/sdk", (int)CurrentEnvironment.PNCENG, "PNC"); } Variables oVariable = new Variables(intEnvironment); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); int intStep = 0; Int32.TryParse(Request.QueryString["s"], out intStep); string strUUID = ""; ManagedObjectReference oComputer = null; if (intStep == 100 || intStep == 1) { if (oComputer != null && oComputer.Value != "") { // Destroy computer ManagedObjectReference _task_power = _service.Destroy_Task(oComputer); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine " + strName.ToUpper() + " Destroyed<br/>"; } else { strError = "Virtual Machine was not destroyed"; } } if (strError == "") { // Create computer oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; oConfig.firmware = "efi"; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore1 + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } } } if (intStep > 1) { oComputer = oVMWare.GetVM(strName); } if ((intStep == 100 || intStep == 2) && strError == "") { // 2) SCSI Controller VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(true); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller Created<br/>"; } else { strError = "SCSI Controller Was Not Created"; } } if ((intStep == 100 || intStep == 3) && strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore1, dblDriveC.ToString(), 0, ""); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive Was Not Created"; } } if ((intStep == 100 || intStep == 33) && strError == "") { if (strDatastore2 != "") { // 33) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore2, dblDrive2.ToString(), 1, (strDatastore1 == strDatastore2 ? "_1" : "")); // 10485760 KB = 10 GB = 10 x 1024 x 1024 _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDrive2.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } } if ((intStep == 100 || intStep == 4) && strError == "") { // 4) Create Network Adapter bool boolISVmware4 = true; if (boolISVmware4 == false) { VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardNetworkBackingInfo vecnbi = new VirtualEthernetCardNetworkBackingInfo(); vecnbi.deviceName = strVLAN; VirtualEthernetCard newethdev; //newethdev = new VirtualE1000(); newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecnbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; } else { strError = "Network Adapter Was Not Created"; } } else { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } } if ((intStep == 100 || intStep == 5) && strError == "") { VirtualMachineConfigSpec _cs_swap = new VirtualMachineConfigSpec(); _cs_swap.swapPlacement = "hostLocal"; ManagedObjectReference _task_swap = _service.ReconfigVM_Task(oComputer, _cs_swap); TaskInfo _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); while (_info_swap.state == TaskInfoState.running) { _info_swap = (TaskInfo)oVMWare.getObjectProperty(_task_swap, "info"); } if (_info_swap.state == TaskInfoState.success) { strResult += "Swap File Configured<br/>"; } else { strError = "Swap File Was Not Configured"; } /* * // 5) Attach Floppy Drive * VirtualMachineConfigSpec _cs_floppy = new VirtualMachineConfigSpec(); * VirtualDeviceConfigSpec _dcs_floppy = new VirtualDeviceConfigSpec(); * _dcs_floppy.operation = VirtualDeviceConfigSpecOperation.add; * _dcs_floppy.operationSpecified = true; * VirtualDeviceConnectInfo _ci_floppy = new VirtualDeviceConnectInfo(); * _ci_floppy.startConnected = false; * VirtualFloppy floppy = new VirtualFloppy(); * VirtualFloppyRemoteDeviceBackingInfo floppyBack = new VirtualFloppyRemoteDeviceBackingInfo(); * floppyBack.deviceName = ""; * floppy.backing = floppyBack; * floppy.key = 8000; * floppy.controllerKey = 400; * floppy.controllerKeySpecified = true; * floppy.connectable = _ci_floppy; * _dcs_floppy.device = floppy; * _cs_floppy.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_floppy }; * ManagedObjectReference _task_floppy = _service.ReconfigVM_Task(oComputer, _cs_floppy); * TaskInfo _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * while (_info_floppy.state == TaskInfoState.running) * _info_floppy = (TaskInfo)oVMWare.getObjectProperty(_task_floppy, "info"); * if (_info_floppy.state == TaskInfoState.success) * strResult += "Floppy Drive Created<br/>"; * else * strError = "Floppy Drive Was Not Created"; */ } if ((intStep == 100 || intStep == 6) && strError == "") { // 6) Attach CD-ROM Drive VirtualMachineConfigSpec _cs_cd = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec _dcs_cd = new VirtualDeviceConfigSpec(); _dcs_cd.operation = VirtualDeviceConfigSpecOperation.add; _dcs_cd.operationSpecified = true; VirtualDeviceConnectInfo _ci_cd = new VirtualDeviceConnectInfo(); _ci_cd.startConnected = false; VirtualCdrom cd = new VirtualCdrom(); VirtualCdromRemotePassthroughBackingInfo cdBack = new VirtualCdromRemotePassthroughBackingInfo(); cdBack.exclusive = false; cdBack.deviceName = ""; cd.backing = cdBack; cd.key = 3000; cd.controllerKey = 200; cd.controllerKeySpecified = true; cd.connectable = _ci_cd; _dcs_cd.device = cd; _cs_cd.deviceChange = new VirtualDeviceConfigSpec[] { _dcs_cd }; ManagedObjectReference _task_cd = _service.ReconfigVM_Task(oComputer, _cs_cd); TaskInfo _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); while (_info_cd.state == TaskInfoState.running) { _info_cd = (TaskInfo)oVMWare.getObjectProperty(_task_cd, "info"); } if (_info_cd.state == TaskInfoState.success) { strResult += "CD-ROM Was Created<br/>"; } else { strError = "CD-ROM Was Not Created"; } } if ((intStep == 100 || intStep == 7) && strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if ((intStep == 100 || intStep == 8) && strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if ((intStep == 100 || intStep == 9) && strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if ((intStep == 100 || intStep == 10) && strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
public VirtualMachineConfigSpec createVmConfigSpec(String vmName, String datastoreName, int diskSizeMB, ManagedObjectReference computeResMor, ManagedObjectReference hostMor) { ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor); VirtualDevice[] defaultDevices = getDefaultDevices(computeResMor, hostMor); VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec(); String networkName = null; if (configTarget.network != null) { for (int i = 0; i < configTarget.network.Length; i++) { VirtualMachineNetworkInfo netInfo = configTarget.network[i]; NetworkSummary netSummary = netInfo.network; if (netSummary.accessible) { networkName = netSummary.name; break; } } } ManagedObjectReference datastoreRef = null; if (datastoreName != null) { Boolean flag = false; for (int i = 0; i < configTarget.datastore.Length; i++) { VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i]; DatastoreSummary dsSummary = vdsInfo.datastore; if (dsSummary.name.Equals(datastoreName)) { flag = true; if (dsSummary.accessible) { datastoreName = dsSummary.name; datastoreRef = dsSummary.datastore; } else { throw new Exception("Specified Datastore is not accessible"); } break; } } if (!flag) { throw new Exception("Specified Datastore is not Found"); } } else { Boolean flag = false; for (int i = 0; i < configTarget.datastore.Length; i++) { VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i]; DatastoreSummary dsSummary = vdsInfo.datastore; if (dsSummary.accessible) { datastoreName = dsSummary.name; datastoreRef = dsSummary.datastore; flag = true; break; } } if (!flag) { throw new Exception("No Datastore found on host"); } } String datastoreVolume = getVolumeName(datastoreName); VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo(); vmfi.vmPathName = datastoreVolume; configSpec.files = vmfi; // Add a scsi controller int diskCtlrKey = 1; VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec(); scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add; scsiCtrlSpec.operationSpecified = true; VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController(); scsiCtrl.busNumber = 0; scsiCtrlSpec.device = scsiCtrl; scsiCtrl.key = diskCtlrKey; scsiCtrl.sharedBus = VirtualSCSISharing.noSharing; String ctlrType = scsiCtrl.GetType().Name; // Find the IDE controller VirtualDevice ideCtlr = null; for (int di = 0; di < defaultDevices.Length; di++) { if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController")) { ideCtlr = defaultDevices[di]; break; } } // Add a floppy VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec(); floppySpec.operation = VirtualDeviceConfigSpecOperation.add; floppySpec.operationSpecified = true; VirtualFloppy floppy = new VirtualFloppy(); VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo(); flpBacking.deviceName = "/dev/fd0"; floppy.backing = flpBacking; floppy.key = 3; floppySpec.device = floppy; // Add a cdrom based on a physical device VirtualDeviceConfigSpec cdSpec = null; if (ideCtlr != null) { cdSpec = new VirtualDeviceConfigSpec(); cdSpec.operation = VirtualDeviceConfigSpecOperation.add; cdSpec.operationSpecified = true; VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); cdDeviceBacking.datastore = datastoreRef; cdDeviceBacking.fileName = datastoreVolume + "testcd.iso"; cdrom.backing = cdDeviceBacking; cdrom.key = 20; cdrom.controllerKey = ideCtlr.key; cdrom.controllerKeySpecified = true; cdrom.unitNumberSpecified = true; cdrom.unitNumber = 0; cdSpec.device = 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.operation = VirtualDeviceConfigSpecOperation.add; nicSpec.operationSpecified = true; VirtualEthernetCard nic = new VirtualPCNet32(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.deviceName = networkName; nic.addressType = "generated"; nic.backing = nicBacking; nic.key = 4; nicSpec.device = nic; } var deviceConfigSpec = new List <VirtualDeviceConfigSpec>(); deviceConfigSpec.Add(scsiCtrlSpec); deviceConfigSpec.Add(floppySpec); deviceConfigSpec.Add(diskSpec); deviceConfigSpec.Add(nicSpec); if (ideCtlr != null) { deviceConfigSpec.Add(cdSpec); } configSpec.deviceChange = deviceConfigSpec.ToArray(); return(configSpec); }
protected void Page_Load(object sender, EventArgs e) { string strResult = ""; string strError = ""; Servers oServer = new Servers(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); IPAddresses oIPAddresses = new IPAddresses(0, dsnIP, dsn); oVMWare = new VMWare(0, dsn); Variables oVariable = new Variables(999); string strName = "healyTest"; string strCluster = "CLESVTLAB01"; double dblDriveC = 60.00; string strDatastore = "CTVXN00007"; double dblDrive2 = 10.00; double dblDrive3 = 10.00; string strPortGroupName = "dvPortGroup5"; // DHCP enabled string strMDTos = "WABEx64"; string strMDTtask = "W2K8R2_STD"; string strMDTbuildDB = "ServerShare"; string strVMguestOS = "windows7Server64Guest"; string strMACAddress = ""; string strResourcePool = ""; string strConnect = oVMWare.ConnectDEBUG("https://vwsvt102/sdk", 999, "PNC-TestLab"); if (strConnect == "") { VimService _service = oVMWare.GetService(); ServiceContent _sic = oVMWare.GetSic(); ManagedObjectReference datacenterRef = oVMWare.GetDataCenter(); ManagedObjectReference vmFolderRef = oVMWare.GetVMFolder(datacenterRef); ManagedObjectReference clusterRef = oVMWare.GetCluster(strCluster); ManagedObjectReference resourcePoolRootRef = (ManagedObjectReference)oVMWare.getObjectProperty(clusterRef, "resourcePool"); if (strResourcePool != "") { resourcePoolRootRef = oVMWare.GetResourcePool(clusterRef, strResourcePool); } VirtualMachineConfigSpec oConfig = new VirtualMachineConfigSpec(); // Create computer ManagedObjectReference oComputer = null; oConfig.annotation = "Blah, Blah, Blah" + Environment.NewLine + "Next Line"; oConfig.guestId = strVMguestOS; string strRamConfig = "2048"; oConfig.memoryMB = long.Parse(strRamConfig); oConfig.memoryMBSpecified = true; int intCpuConfig = 1; oConfig.numCPUs = intCpuConfig; oConfig.numCPUsSpecified = true; oConfig.name = strName.ToLower(); oConfig.files = new VirtualMachineFileInfo(); oConfig.files.vmPathName = "[" + strDatastore + "] " + strName.ToLower() + "/" + strName.ToLower() + ".vmx"; ManagedObjectReference _task = _service.CreateVM_Task(vmFolderRef, oConfig, resourcePoolRootRef, null); TaskInfo oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); while (oInfo.state == TaskInfoState.running) { oInfo = (TaskInfo)oVMWare.getObjectProperty(_task, "info"); } if (oInfo.state == TaskInfoState.success) { oComputer = (ManagedObjectReference)oInfo.result; VirtualMachineConfigInfo _temp = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); strResult += "Virtual Machine " + strName.ToUpper() + " Created (" + _temp.uuid + ")<br/>"; } else { strError = "Virtual Machine was not created"; } if (strError == "") { // 2) SCSI Controller 1 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(0, 2, 1000); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 3) Create Hard Disk 1 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDriveC = dblDriveC * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDriveC.ToString(), 0, 1000, ""); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 1 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 1 Was Not Created"; } } if (strError == "") { // 4) Create Hard Disk 2 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive2 = dblDrive2 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive2.ToString(), 1, 1000, "_2"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 2 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 2 Was Not Created"; } } if (strError == "") { // 5) SCSI Controller 2 VirtualMachineConfigSpec _cs_scsi = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec controlVMSpec = Controller(1, 3, 1001); _cs_scsi.deviceChange = new VirtualDeviceConfigSpec[] { controlVMSpec }; ManagedObjectReference _task_scsi = _service.ReconfigVM_Task(oComputer, _cs_scsi); TaskInfo _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); while (_inf_scsi.state == TaskInfoState.running) { _inf_scsi = (TaskInfo)oVMWare.getObjectProperty(_task_scsi, "info"); } if (_inf_scsi.state == TaskInfoState.success) { strResult += "SCSI Controller # 1 Created<br/>"; } else { strError = "SCSI Controller # 1 Was Not Created"; } } if (strError == "") { // 6) Create Hard Disk 3 VirtualMachineConfigSpec _cs_hdd1 = new VirtualMachineConfigSpec(); dblDrive3 = dblDrive3 * 1024.00 * 1024.00; VirtualDeviceConfigSpec diskVMSpec1 = Disk(oVMWare, strName, strDatastore, dblDrive3.ToString(), 0, 1001, "_3"); _cs_hdd1.deviceChange = new VirtualDeviceConfigSpec[] { diskVMSpec1 }; ManagedObjectReference _task_hdd1 = _service.ReconfigVM_Task(oComputer, _cs_hdd1); TaskInfo _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); while (_info_hdd1.state == TaskInfoState.running) { _info_hdd1 = (TaskInfo)oVMWare.getObjectProperty(_task_hdd1, "info"); } if (_info_hdd1.state == TaskInfoState.success) { strResult += "Hard Drive # 3 Created (" + dblDriveC.ToString() + ")<br/>"; } else { strError = "Hard Drive # 3 Was Not Created"; } } if (String.IsNullOrEmpty(Request.QueryString["build"]) == false) { if (strError == "") { bool boolCompleted = false; string strPortGroupKey = ""; ManagedObjectReference[] oNetworks = (ManagedObjectReference[])oVMWare.getObjectProperty(datacenterRef, "network"); foreach (ManagedObjectReference oNetwork in oNetworks) { if (boolCompleted == true) { break; } try { if (strPortGroupName == "" || strPortGroupName == oVMWare.getObjectProperty(oNetwork, "name").ToString()) { object oPortConfig = oVMWare.getObjectProperty(oNetwork, "config"); if (oPortConfig != null) { DVPortgroupConfigInfo oPort = (DVPortgroupConfigInfo)oPortConfig; if (oPort.key != strPortGroupKey) { strPortGroupKey = oPort.key; ManagedObjectReference oSwitch = oPort.distributedVirtualSwitch; string strSwitchUUID = (string)oVMWare.getObjectProperty(oSwitch, "uuid"); Response.Write("Trying..." + strPortGroupKey + "(" + strSwitchUUID + ")" + "<br/>"); VirtualDeviceConfigSpec[] configspecarr = configspecarr = new VirtualDeviceConfigSpec[1]; VirtualEthernetCardDistributedVirtualPortBackingInfo vecdvpbi = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection connection = new DistributedVirtualSwitchPortConnection(); connection.portgroupKey = strPortGroupKey; connection.switchUuid = strSwitchUUID; vecdvpbi.port = connection; //VirtualEthernetCard newethdev = new VirtualE1000(); VirtualEthernetCard newethdev = new VirtualVmxnet3(); // ******** OTHER WAY = newethdev = new VirtualPCNet32(); newethdev.backing = vecdvpbi; newethdev.key = 5000; VirtualDeviceConfigSpec newethdevicespec = new VirtualDeviceConfigSpec(); newethdevicespec.device = newethdev; newethdevicespec.operation = VirtualDeviceConfigSpecOperation.add; newethdevicespec.operationSpecified = true; configspecarr[0] = newethdevicespec; VirtualMachineConfigSpec vmconfigspec = new VirtualMachineConfigSpec(); vmconfigspec.deviceChange = configspecarr; ManagedObjectReference _task_net = _service.ReconfigVM_Task(oComputer, vmconfigspec); TaskInfo _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); while (_info_net.state == TaskInfoState.running) { _info_net = (TaskInfo)oVMWare.getObjectProperty(_task_net, "info"); } if (_info_net.state == TaskInfoState.success) { strResult += "Network Adapter Created<br/>"; boolCompleted = true; } //break; } } } } catch (Exception ex) { // Only hits here if it is not a "DistributedVirtualPortgroup" (meaning it is a standard NETWORK object) } } if (boolCompleted == false) { strError = "Network Adapter Was Not Created ~ Could not find a port group"; } } if (strError == "") { // 7) Boot Delay VirtualMachineBootOptions oBootOptions = new VirtualMachineBootOptions(); oBootOptions.bootDelay = 10000; oBootOptions.bootDelaySpecified = true; VirtualMachineConfigSpec _cs_boot_options = new VirtualMachineConfigSpec(); _cs_boot_options.bootOptions = oBootOptions; ManagedObjectReference _task_boot_options = _service.ReconfigVM_Task(oComputer, _cs_boot_options); TaskInfo _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); while (_info_boot_options.state == TaskInfoState.running) { _info_boot_options = (TaskInfo)oVMWare.getObjectProperty(_task_boot_options, "info"); } if (_info_boot_options.state == TaskInfoState.success) { strResult += "Boot delay changed to 10 seconds<br/>"; } else { strError = "Boot delay NOT changed"; } } if (strError == "") { // 8) Get MAC Address VirtualMachineConfigInfo _vminfo = (VirtualMachineConfigInfo)oVMWare.getObjectProperty(oComputer, "config"); VirtualDevice[] _device = _vminfo.hardware.device; for (int ii = 0; ii < _device.Length; ii++) { // 4/29/2009: Change to only one NIC for PNC if (_device[ii].deviceInfo.label.ToUpper() == "NETWORK ADAPTER 1") { VirtualEthernetCard nic = (VirtualEthernetCard)_device[ii]; strMACAddress = nic.macAddress; break; } } if (strMACAddress != "") { strResult += "MAC Address = " + strMACAddress + "<br/>"; } else { strError = "No MAC Address"; } } if (strError == "") { // 9) Configure WebService System.Net.NetworkCredential oCredentials = new System.Net.NetworkCredential(oVariable.ADUser(), oVariable.ADPassword(), oVariable.Domain()); BuildSubmit oMDT = new BuildSubmit(); oMDT.Credentials = oCredentials; oMDT.Url = "http://wcrdp100a.pnceng.pvt/wabebuild/BuildSubmit.asmx"; string[] strExtendedMDT = new string[] { "PNCBACKUPSOFTWARE:NONE", "IISInstall:NO", "HWConfig:DEFAULT", "ESMInstall:NO", "ClearViewInstall:YES", "Teamed2:DEFAULT", "HIDSInstall:NO" }; string strExtendedMDTs = ""; foreach (string extendedMDT in strExtendedMDT) { if (strExtendedMDTs != "") { strExtendedMDTs += ", "; } strExtendedMDTs += extendedMDT; } string strOutput = oMDT.automatedBuild2(strName.ToUpper(), strMACAddress, strMDTos, "provision", "PNCNT", strMDTtask, strMDTbuildDB, strExtendedMDT); strResult += "WebService Configured " + strOutput + "<br/>"; } if (strError == "") { // 10) Power On GuestInfo ginfo_power = (GuestInfo)oVMWare.getObjectProperty(oComputer, "guest"); if (ginfo_power.guestState.ToUpper() == "NOTRUNNING" || ginfo_power.guestState.ToUpper() == "UNKNOWN") { ManagedObjectReference _task_power = _service.PowerOnVM_Task(oComputer, null); TaskInfo _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); while (_info_power.state == TaskInfoState.running) { _info_power = (TaskInfo)oVMWare.getObjectProperty(_task_power, "info"); } if (_info_power.state == TaskInfoState.success) { strResult += "Virtual Machine Powered On"; } else { strError = "Virtual Machine Was Not Powered On"; } } else { strResult += "Virtual Machine Was Already Powered On (" + ginfo_power.guestState + ")"; } } } // Logout if (_service != null) { _service.Abort(); if (_service.Container != null) { _service.Container.Dispose(); } try { _service.Logout(_sic.sessionManager); } catch { } _service.Dispose(); _service = null; _sic = null; } Response.Write("RESULT(s): " + strResult); Response.Write("ERROR: " + strError); } else { Response.Write("LOGIN error"); } }
public VirtualDeviceConfigSpec createVirtualDisk(String volName, int diskCtlrKey, ManagedObjectReference datastoreRef, int diskSizeMB) { String volumeName = getVolumeName(volName); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); diskSpec.fileOperation = VirtualDeviceConfigSpecFileOperation.create; diskSpec.fileOperationSpecified = true; diskSpec.operation = VirtualDeviceConfigSpecOperation.add; diskSpec.operationSpecified = true; VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); diskfileBacking.fileName = volumeName; diskfileBacking.diskMode = "persistent"; disk.key = 0; disk.controllerKey = diskCtlrKey; disk.unitNumber = 0; disk.backing = diskfileBacking; disk.capacityInKB = diskSizeMB; disk.controllerKeySpecified = true; disk.unitNumberSpecified = true; diskSpec.device = disk; return diskSpec; }
public VirtualMachineConfigSpec createVmConfigSpec(String vmName, String datastoreName, int diskSizeMB, ManagedObjectReference computeResMor, ManagedObjectReference hostMor) { ConfigTarget configTarget = getConfigTargetForHost(computeResMor, hostMor); VirtualDevice[] defaultDevices = getDefaultDevices(computeResMor, hostMor); VirtualMachineConfigSpec configSpec = new VirtualMachineConfigSpec(); String networkName = null; if (configTarget.network != null) { for (int i = 0; i < configTarget.network.Length; i++) { VirtualMachineNetworkInfo netInfo = configTarget.network[i]; NetworkSummary netSummary = netInfo.network; if (netSummary.accessible) { networkName = netSummary.name; break; } } } ManagedObjectReference datastoreRef = null; if (datastoreName != null) { Boolean flag = false; for (int i = 0; i < configTarget.datastore.Length; i++) { VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i]; DatastoreSummary dsSummary = vdsInfo.datastore; if (dsSummary.name.Equals(datastoreName)) { flag = true; if (dsSummary.accessible) { datastoreName = dsSummary.name; datastoreRef = dsSummary.datastore; } else { throw new Exception("Specified Datastore is not accessible"); } break; } } if (!flag) { throw new Exception("Specified Datastore is not Found"); } } else { Boolean flag = false; for (int i = 0; i < configTarget.datastore.Length; i++) { VirtualMachineDatastoreInfo vdsInfo = configTarget.datastore[i]; DatastoreSummary dsSummary = vdsInfo.datastore; if (dsSummary.accessible) { datastoreName = dsSummary.name; datastoreRef = dsSummary.datastore; flag = true; break; } } if (!flag) { throw new Exception("No Datastore found on host"); } } String datastoreVolume = getVolumeName(datastoreName); VirtualMachineFileInfo vmfi = new VirtualMachineFileInfo(); vmfi.vmPathName = datastoreVolume; configSpec.files = vmfi; // Add a scsi controller int diskCtlrKey = 1; VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec(); scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add; scsiCtrlSpec.operationSpecified = true; VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController(); scsiCtrl.busNumber = 0; scsiCtrlSpec.device = scsiCtrl; scsiCtrl.key = diskCtlrKey; scsiCtrl.sharedBus = VirtualSCSISharing.noSharing; String ctlrType = scsiCtrl.GetType().Name; // Find the IDE controller VirtualDevice ideCtlr = null; for (int di = 0; di < defaultDevices.Length; di++) { if (defaultDevices[di].GetType().Name.Equals("VirtualIDEController")) { ideCtlr = defaultDevices[di]; break; } } // Add a floppy VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec(); floppySpec.operation = VirtualDeviceConfigSpecOperation.add; floppySpec.operationSpecified = true; VirtualFloppy floppy = new VirtualFloppy(); VirtualFloppyDeviceBackingInfo flpBacking = new VirtualFloppyDeviceBackingInfo(); flpBacking.deviceName = "/dev/fd0"; floppy.backing = flpBacking; floppy.key = 3; floppySpec.device = floppy; // Add a cdrom based on a physical device VirtualDeviceConfigSpec cdSpec = null; if (ideCtlr != null) { cdSpec = new VirtualDeviceConfigSpec(); cdSpec.operation = VirtualDeviceConfigSpecOperation.add; cdSpec.operationSpecified = true; VirtualCdrom cdrom = new VirtualCdrom(); VirtualCdromIsoBackingInfo cdDeviceBacking = new VirtualCdromIsoBackingInfo(); cdDeviceBacking.datastore = datastoreRef; cdDeviceBacking.fileName = datastoreVolume + "testcd.iso"; cdrom.backing = cdDeviceBacking; cdrom.key = 20; cdrom.controllerKey = ideCtlr.key; cdrom.controllerKeySpecified = true; cdrom.unitNumberSpecified = true; cdrom.unitNumber = 0; cdSpec.device = 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.operation = VirtualDeviceConfigSpecOperation.add; nicSpec.operationSpecified = true; VirtualEthernetCard nic = new VirtualPCNet32(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.deviceName = networkName; nic.addressType = "generated"; nic.backing = nicBacking; nic.key = 4; nicSpec.device = nic; } var deviceConfigSpec = new List<VirtualDeviceConfigSpec>(); deviceConfigSpec.Add(scsiCtrlSpec); deviceConfigSpec.Add(floppySpec); deviceConfigSpec.Add(diskSpec); deviceConfigSpec.Add(nicSpec); if (ideCtlr != null) { deviceConfigSpec.Add(cdSpec); } configSpec.deviceChange = deviceConfigSpec.ToArray(); return configSpec; }
private VirtualDeviceConfigSpec getDiskDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine,"config"); if(ops.Equals("add")) { VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); String dsName = getDataStoreName(int.Parse(cb.get_option("disksize"))); int ckey = -1; int unitNumber = 0; VirtualDevice [] test = vmConfigInfo.hardware.device; for(int k=0;k<test.Length;k++){ if(test[k].deviceInfo.label.Equals( "SCSI Controller 0")){ ckey = test[k].key; } } unitNumber = test.Length + 1; String fileName = "["+dsName+"] "+ cb.get_option("vmname") + "/"+cb.get_option("value")+".vmdk"; diskfileBacking.fileName=fileName; diskfileBacking.diskMode=cb.get_option("diskmode"); disk.controllerKey = ckey; disk.unitNumber=unitNumber; disk.controllerKeySpecified = true; disk.unitNumberSpecified = true; disk.backing= diskfileBacking; int size = 1024 * (int.Parse(cb.get_option("disksize"))); disk.capacityInKB= size; disk.key= 0; diskSpec.operation=VirtualDeviceConfigSpecOperation.add; diskSpec.fileOperation=VirtualDeviceConfigSpecFileOperation.create; diskSpec.fileOperationSpecified = true; diskSpec.operationSpecified = true; diskSpec.device=disk; } else if(ops.Equals("remove")) { VirtualDisk disk = null; VirtualDiskFlatVer2BackingInfo diskfileBacking = new VirtualDiskFlatVer2BackingInfo(); VirtualDevice [] test = vmConfigInfo.hardware.device; for(int k=0;k<test.Length;k++){ if(test[k].deviceInfo.label.Equals( cb.get_option("value"))){ disk = (VirtualDisk)test[k]; } } if(disk != null) { diskSpec.operation=VirtualDeviceConfigSpecOperation.remove; diskSpec.operationSpecified = true; diskSpec.fileOperation=VirtualDeviceConfigSpecFileOperation.destroy; diskSpec.fileOperationSpecified = true; diskSpec.device=disk; } else { Console.WriteLine("No device found " + cb.get_option("value")); return null; } } return diskSpec; }
private VirtualDeviceConfigSpec getNICDeviceConfigSpec() { String ops = cb.get_option("operation"); VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine,"config"); if(ops.Equals("add")) { String networkName = getNetworkName(); if(networkName != null) { nicSpec.operation=VirtualDeviceConfigSpecOperation.add; nicSpec.operationSpecified = true; VirtualEthernetCard nic = new VirtualPCNet32(); VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.deviceName = networkName; nic.addressType="generated"; nic.backing= nicBacking; nic.key= 4; nicSpec.device=nic; } else { return null; } } else if(ops.Equals("remove")) { VirtualEthernetCard nic = null; VirtualDevice [] test = vmConfigInfo.hardware.device; nicSpec.operation=VirtualDeviceConfigSpecOperation.remove; nicSpec.operationSpecified = true; for(int k=0;k<test.Length;k++){ if(test[k].deviceInfo.label.Equals( cb.get_option("value"))){ nic = (VirtualEthernetCard)test[k]; } } if(nic != null) { nicSpec.device=nic; } else { Console.WriteLine("No device available " + cb.get_option("value")); return null; } } return nicSpec; }
public void ConnectIso( string isoLocation ) { const string remotePath = "/Temp"; UploadArtifact( isoLocation, remotePath ); _virtualMachine.UpdateViewData(); VirtualCdrom cd = _virtualMachine.Config.Hardware.Device.FirstOrDefault( d => d is VirtualCdrom ) as VirtualCdrom; if ( cd == null ) { throw new ApplicationException( "CD is null" ); } VirtualCdromIsoBackingInfo newBacking = new VirtualCdromIsoBackingInfo { FileName = string.Format( "[{0}] {1}", "datastore1", remotePath ) }; cd.Backing = newBacking; cd.Connectable.StartConnected = true; cd.Connectable.Connected = true; VirtualDeviceConfigSpec deviceSpec = new VirtualDeviceConfigSpec { Device = cd, Operation = VirtualDeviceConfigSpecOperation.edit }; VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec { DeviceChange = new[] {deviceSpec} }; _virtualMachine.ReconfigVM( vmSpec ); }
public void DeployAndConnectIso( string localPath, string remotePath ) { UploadArtifact( localPath, remotePath ); _vm.UpdateViewData(); VirtualCdrom cd = _vm.Config.Hardware.Device.FirstOrDefault( d => d is VirtualCdrom ) as VirtualCdrom; if ( cd == null ) { throw new ApplicationException( "CD is null" ); } VirtualCdromIsoBackingInfo newBacking = new VirtualCdromIsoBackingInfo { FileName = string.Format( "[{0}] {1}", _vmWareConfiguration.DataStoreName, remotePath ) }; cd.Backing = newBacking; cd.Connectable.StartConnected = true; cd.Connectable.Connected = true; VirtualDeviceConfigSpec deviceSpec = new VirtualDeviceConfigSpec { Device = cd, Operation = VirtualDeviceConfigSpecOperation.edit }; VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec { DeviceChange = new[] {deviceSpec} }; _vm.ReconfigVM( vmSpec ); }
private void reConfig() { String deviceType = cb.get_option("device"); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); if(deviceType.Equals("memory")) { Console.WriteLine("Reconfiguring The Virtual Machine For Memory Update " + cb.get_option("vmname")); try { vmConfigSpec.memoryAllocation = getShares(); } catch(Exception nfe) { Console.WriteLine("Value of Memory update must " +"be either Custom or Integer"); return; } } else if(deviceType.Equals("cpu")) { Console.WriteLine("Reconfiguring The Virtual Machine For CPU Update " + cb.get_option("vmname")); try { vmConfigSpec.cpuAllocation=getShares(); } catch(Exception nfe) { Console.WriteLine("Value of CPU update must " +"be either Custom or Integer"); return; } } else if(deviceType.Equals("disk")) { Console.WriteLine("Reconfiguring The Virtual Machine For Disk Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec vdiskSpec = getDiskDeviceConfigSpec(); if(vdiskSpec != null) { VirtualMachineConfigInfo vmConfigInfo = (VirtualMachineConfigInfo)cb.getServiceUtil().GetDynamicProperty( _virtualMachine, "config"); int ckey = -1; VirtualDevice[] test = vmConfigInfo.hardware.device; for (int k = 0; k < test.Length; k++) { if (test[k].deviceInfo.label.Equals( "SCSI Controller 0")) { ckey = test[k].key; } } if (ckey == -1) { int diskCtlrKey = 1; VirtualDeviceConfigSpec scsiCtrlSpec = new VirtualDeviceConfigSpec(); scsiCtrlSpec.operation = VirtualDeviceConfigSpecOperation.add; scsiCtrlSpec.operationSpecified = true; VirtualLsiLogicController scsiCtrl = new VirtualLsiLogicController(); scsiCtrl.busNumber = 0; scsiCtrlSpec.device = scsiCtrl; scsiCtrl.key = diskCtlrKey; scsiCtrl.sharedBus = VirtualSCSISharing.physicalSharing; String ctlrType = scsiCtrl.GetType().Name; vdiskSpec.device.controllerKey = scsiCtrl.key; VirtualDeviceConfigSpec[] vdiskSpecArray = { scsiCtrlSpec, vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } else { vdiskSpec.device.controllerKey = ckey; VirtualDeviceConfigSpec[] vdiskSpecArray = { vdiskSpec }; vmConfigSpec.deviceChange = vdiskSpecArray; } } else { return; } } else if(deviceType.Equals("nic")) { Console.WriteLine("Reconfiguring The Virtual Machine For NIC Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec nicSpec = getNICDeviceConfigSpec(); if(nicSpec != null) { VirtualDeviceConfigSpec [] nicSpecArray = {nicSpec}; vmConfigSpec.deviceChange=nicSpecArray; } else { return; } } else if(deviceType.Equals("cd")) { Console.WriteLine("Reconfiguring The Virtual Machine For CD Update " + cb.get_option("vmname")); VirtualDeviceConfigSpec cdSpec = getCDDeviceConfigSpec(); if(cdSpec != null) { VirtualDeviceConfigSpec [] cdSpecArray = {cdSpec}; vmConfigSpec.deviceChange=cdSpecArray; } else { return; } } else { Console.WriteLine("Invlaid device type [memory|cpu|disk|nic|cd]"); return; } ManagedObjectReference tmor = cb.getConnection()._service.ReconfigVM_Task( _virtualMachine, vmConfigSpec); monitorTask(tmor); }