/// <summary> /// Returns ComputerSystem lacking any NICs and VOLUMEs /// </summary> public ComputerSystem AddUserData(ComputerSystem vm, string userData) { // Obtain controller for Hyper-V virtualisation subsystem VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); // Create object to hold the data. KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance(); kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey; kvpItem.LateBoundObject["Data"] = userData; kvpItem.LateBoundObject["Source"] = 0; logger.Debug("VM " + vm.Name + " gets userdata " + userData); // Update the resource settings for the VM. System.Management.ManagementBaseObject kvpMgmtObj = kvpItem.LateBoundObject; System.Management.ManagementPath jobPath; String kvpStr = kvpMgmtObj.GetText(System.Management.TextFormat.CimDtd20); uint ret_val = vmMgmtSvc.AddKvpItems(new String[] { kvpStr }, vm.Path, out jobPath); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", vm.ElementName, vm.Name, ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return vm; }
/// <summary> /// Create Msvm_StorageAllocationSettingData corresponding to the ISO image, and /// associate this with the VM's DVD drive. /// </summary> private void AttachIso(ComputerSystem vm, string isoPath) { // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. VirtualSystemSettingData vmSettings = GetVmSettings(vm); var driveWmiObj = GetDvdDriveSettings(vmSettings); InsertDiskImage(vm, isoPath, ISO_DISK, driveWmiObj.Path); }
private ManagementPath[] AddVirtualResource(string[] resourceSettings, ComputerSystem vm ) { var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); ManagementPath jobPath; ManagementPath[] resourcePaths; var ret_val = virtSysMgmtSvc.AddResourceSettings( vm.Path, resourceSettings, out jobPath, out resourcePaths); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to add resources to VM {0} (GUID {1}) due to {2}", vm.ElementName, vm.Name, ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return resourcePaths; }
/// <summary> /// Adds storage images to coputer system (disk image, iso image). /// </summary> /// <param name="storageSettings">Msvm_StorageAllocationSettings with HostResource configured with image /// file and Parent set to a controller associated with the ComputerSystem</param> /// <param name="vm">VM to which the disk image will be attached.</param> // Add new private ManagementPath[] AddStorageResource(string[] storageSettings, ComputerSystem vm) { return AddVirtualResource(storageSettings, vm); }
/// </summary> /// <param name="vm"></param> /// <param name="cntrllerAddr"></param> /// <param name="driveResourceType">IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE</param> public ManagementPath AddDiskDriveToIdeController(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType) { logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}", vm.ElementName, vm.Name, vhdfile); // Determine disk type for drive and assert drive type valid string diskResourceSubType = null; switch(driveResourceType) { case HARDDISK_DRIVE: diskResourceSubType = HARDDISK_DISK; break; case ISO_DRIVE: diskResourceSubType = ISO_DISK; break; default: var errMsg = string.Format( "Unrecognised disk drive type {0} for VM {1} (GUID {2})", string.IsNullOrEmpty(driveResourceType) ? "NULL": driveResourceType, vm.ElementName, vm.Name); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } ManagementPath newDrivePath = AttachNewDrive(vm, cntrllerAddr, driveResourceType); // If there's not disk to insert, we are done. if (String.IsNullOrEmpty(vhdfile)) { logger.DebugFormat("No disk to be added to drive, disk drive {0} is complete", newDrivePath.Path); } else { InsertDiskImage(vm, vhdfile, diskResourceSubType, newDrivePath); } return newDrivePath; }
private ManagementPath GetDiskDriveOnScsiController(ComputerSystem vm, string addrOnController) { VirtualSystemSettingData vmSettings = GetVmSettings(vm); var wmiObjCollection = GetResourceAllocationSettings(vmSettings); foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection) { if (wmiObj.ResourceSubType == HARDDISK_DRIVE) { ResourceAllocationSettingData parent = new ResourceAllocationSettingData(new ManagementObject(wmiObj.Parent)); if (parent.ResourceSubType == SCSI_CONTROLLER && wmiObj.AddressOnParent == addrOnController) { return wmiObj.Path; } } } return null; }
/// <summary> /// Removes a disk image from a drive, but does not remove the drive itself. /// </summary> /// <param name="vm"></param> /// <param name="diskFileName"></param> private void RemoveStorageImage(ComputerSystem vm, string diskFileName) { // Obtain StorageAllocationSettingData for disk StorageAllocationSettingData.StorageAllocationSettingDataCollection storageSettingsObjs = StorageAllocationSettingData.GetInstances(); StorageAllocationSettingData imageToRemove = null; foreach (StorageAllocationSettingData item in storageSettingsObjs) { if (item.HostResource == null || item.HostResource.Length != 1) { continue; } string hostResource = item.HostResource[0]; if (Path.Equals(hostResource, diskFileName)) { imageToRemove = item; break; } } // assert if (imageToRemove == null) { var errMsg = string.Format( "Failed to remove disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", diskFileName, vm.ElementName, vm.Name); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } RemoveStorageResource(imageToRemove.Path, vm); logger.InfoFormat("Removed disk image {0} from VM {1} (GUID {2}): the disk image is not attached.", diskFileName, vm.ElementName, vm.Name); }
public VirtualSystemSettingData GetVmSettings(ComputerSystem vm) { // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the // VirtualSystemSettingData, but generated wrappers do not expose a ASSOCIATOR OF query as a method. // Instead, we use the System.Management to code the equivalant of // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); // var wmiObjQuery = new RelatedObjectQuery(vm.Path.Path, VirtualSystemSettingData.CreatedClassName); // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain // the virtualisation objects. var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); var wmiObjCollection = new VirtualSystemSettingData.VirtualSystemSettingDataCollection(wmiObjectSearch.Get()); // When snapshots are taken into account, there can be multiple settings objects // take the first one that isn't a snapshot foreach (VirtualSystemSettingData wmiObj in wmiObjCollection) { if (wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Realized" || wmiObj.VirtualSystemType == "Microsoft:Hyper-V:System:Planned") { return wmiObj; } } var errMsg = string.Format("No VirtualSystemSettingData for VM {0}, path {1}", vm.ElementName, vm.Path.Path); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; }
public void SetState(ComputerSystem vm, ushort requiredState) { logger.InfoFormat( "Changing state of {0} (GUID {1}) to {2}", vm.ElementName, vm.Name, RequiredState.ToString(requiredState)); ManagementPath jobPath; // DateTime is unused var ret_val = vm.RequestStateChange(requiredState, new DateTime(), out jobPath); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val == 32775) { // TODO: check logger.InfoFormat("RequestStateChange returned 32775, which means vm in wrong state for requested state change. Treating as if requested state was reached"); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to change state of VM {0} (GUID {1}) to {2} due to {3}", vm.ElementName, vm.Name, RequiredState.ToString(requiredState), ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } logger.InfoFormat( "Successfully changed vm state of {0} (GUID {1} to requested state {2}", vm.ElementName, vm.Name, requiredState); }
public SyntheticEthernetPortSettingData[] GetEthernetPortSettings(ComputerSystem vm) { // An ASSOCIATOR object provides the cross reference from the ComputerSettings and the // SyntheticEthernetPortSettingData, via the VirtualSystemSettingData. // However, generated wrappers do not expose a ASSOCIATOR OF query as a method. // Instead, we use the System.Management to code the equivalant of // // string query = string.Format( "ASSOCIATORS OF {{{0}}} WHERE ResultClass = {1}", vm.path, resultclassName); // VirtualSystemSettingData vmSettings = GetVmSettings(vm); var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, SyntheticEthernetPortSettingData.CreatedClassName); // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain // the virtualisation objects. var wmiObjectSearch = new ManagementObjectSearcher(vm.Scope, wmiObjQuery); var wmiObjCollection = new SyntheticEthernetPortSettingData.SyntheticEthernetPortSettingDataCollection(wmiObjectSearch.Get()); List<SyntheticEthernetPortSettingData> results = new List<SyntheticEthernetPortSettingData>(wmiObjCollection.Count); foreach (SyntheticEthernetPortSettingData item in wmiObjCollection) { results.Add(item); } return results.ToArray(); }
public StorageAllocationSettingData[] GetStorageSettings(ComputerSystem vm) { // ComputerSystem -> VirtualSystemSettingData -> EthernetPortAllocationSettingData VirtualSystemSettingData vmSettings = GetVmSettings(vm); var wmiObjQuery = new RelatedObjectQuery(vmSettings.Path.Path, StorageAllocationSettingData.CreatedClassName); // NB: default scope of ManagementObjectSearcher is '\\.\root\cimv2', which does not contain // the virtualisation objects. var wmiObjectSearch = new ManagementObjectSearcher(vmSettings.Scope, wmiObjQuery); var wmiObjCollection = new StorageAllocationSettingData.StorageAllocationSettingDataCollection(wmiObjectSearch.Get()); var result = new List<StorageAllocationSettingData>(wmiObjCollection.Count); foreach (StorageAllocationSettingData item in wmiObjCollection) { result.Add(item); } return result.ToArray(); }
public void ShutdownVm(ComputerSystem vm) { ShutdownComponent sc = GetShutdownComponent(vm); if (sc != null) { var ret_val = sc.InitiateShutdown(true, "need to shutdown"); if (ret_val != ReturnCode.Completed) { logger.Info("Shutting down of system failed, may be shutdown integration services are missing"); } else { // shutdown job is not returned so checking for shutdown completion by checking the current state of system. // poll every one second and timeout after 10 minutes for (int period = 0 ; period < 600 && (GetComputerSystem(vm.ElementName).EnabledState != EnabledState.Disabled); period++) { System.Threading.Thread.Sleep(1000); } } } else { logger.Info("Shutting down of system failed; may be shutdown integration services are missing"); } }
public ShutdownComponent GetShutdownComponent(ComputerSystem vm) { var wmiQuery = String.Format("SystemName=\"{0}\"", vm.Name); ShutdownComponent.ShutdownComponentCollection vmCollection = ShutdownComponent.GetInstances(wmiQuery); // Return the first one foreach (ShutdownComponent sc in vmCollection) { return sc; } return null; }
public void TestStartCommand() { ComputerSystem system = new ComputerSystem(); wmiCallsV2.DeployVirtualMachine(Arg.Any<Object>(), Arg.Any<string>()).Returns(system); // Arrange HypervResourceController rsrcServer = new HypervResourceController(); HypervResourceController.wmiCallsV2 = wmiCallsV2; String sample = getSampleStartCommand(); dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); // Act dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); // Assert Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); }
private ManagementPath AttachNewDrive(ComputerSystem vm, string cntrllerAddr, string driveType) { // Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it. VirtualSystemSettingData vmSettings = GetVmSettings(vm); var ctrller = GetIDEControllerSettings(vmSettings, cntrllerAddr); // A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", driveType); var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery); // Set IDE controller and address on the controller for the new drive newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString(); newDiskDriveSettings.LateBoundObject["AddressOnParent"] = "0"; newDiskDriveSettings.CommitObject(); // Add this new disk drive to the VM logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}", newDiskDriveSettings.ResourceSubType, newDiskDriveSettings.Parent, newDiskDriveSettings.AddressOnParent); string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm); // assert if (newDrivePaths.Length != 1) { var errMsg = string.Format( "Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}", vm.ElementName, vm.Name, newDrivePaths.Length, driveType); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } logger.DebugFormat("New disk drive type {0} WMI path is {1}s", newDiskDriveSettings.ResourceSubType, newDrivePaths[0].Path); return newDrivePaths[0]; }
public Boolean TagVm(ComputerSystem vm) { VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService(); VirtualSystemSettingData vmSettings = GetVmSettings(vm); vmSettings.LateBoundObject["Notes"] = new string[] { "Created by CloudStack, do not edit. \n" }; ModifySystemSetting(vmMgmtSvc, vmSettings.LateBoundObject.GetText(TextFormat.CimDtd20)); return true; }
private EthernetPortAllocationSettingData AttachNicToPort(ComputerSystem newVm, SyntheticEthernetPortSettingData newAdapter, String vSwitchName) { // Get the virtual switch VirtualEthernetSwitch vSwitch = GetExternalVirtSwitch(vSwitchName); //check the the recevied vSwitch is the same as vSwitchName. if (!vSwitchName.Equals("") && !vSwitch.ElementName.Equals(vSwitchName)) { var errMsg = string.Format("Internal error, coudl not find Virtual Switch with the name : " +vSwitchName); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } // Create port for adapter var defaultEthernetPortSettings = EthernetPortAllocationSettingData.GetInstances(vSwitch.Scope, "InstanceID LIKE \"%Default\""); // assert if (defaultEthernetPortSettings.Count != 1) { var errMsg = string.Format("Internal error, coudl not find default EthernetPortAllocationSettingData instance"); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } var defaultEthernetPortSettingsObj = defaultEthernetPortSettings.OfType<EthernetPortAllocationSettingData>().First(); var newEthernetPortSettings = new EthernetPortAllocationSettingData((ManagementBaseObject)defaultEthernetPortSettingsObj.LateBoundObject.Clone()); newEthernetPortSettings.LateBoundObject["Parent"] = newAdapter.Path.Path; newEthernetPortSettings.LateBoundObject["HostResource"] = new string[] { vSwitch.Path.Path }; // Insert NIC into vm string[] newResources = new string[] { newEthernetPortSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; ManagementPath[] newResourcePaths = AddVirtualResource(newResources, newVm); // assert if (newResourcePaths.Length != 1) { var errMsg = string.Format( "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", newVm.ElementName, newVm.Name, newResourcePaths.Length); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return new EthernetPortAllocationSettingData(newResourcePaths[0]); }
private static ComputerSystem CreateDefaultVm(VirtualSystemManagementService vmMgmtSvc, string name) { // Tweak default settings by basing new VM on default global setting object // with designed display name. UInt16 startupAction = 2; // Do nothing. UInt16 stopAction = 4; // Shutdown. VirtualSystemSettingData vs_gs_data = VirtualSystemSettingData.CreateInstance(); vs_gs_data.LateBoundObject["ElementName"] = name; vs_gs_data.LateBoundObject["AutomaticStartupAction"] = startupAction.ToString(); vs_gs_data.LateBoundObject["AutomaticShutdownAction"] = stopAction.ToString(); vs_gs_data.LateBoundObject["Notes"] = new string[] { "CloudStack creating VM, do not edit. \n" }; System.Management.ManagementPath jobPath; System.Management.ManagementPath defined_sys; var ret_val = vmMgmtSvc.DefineSystem( null, new string[0], vs_gs_data.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20), out jobPath, out defined_sys); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to create VM {0} due to {1} (DefineVirtualSystem call)", name, ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } logger.DebugFormat(CultureInfo.InvariantCulture, "Created VM {0}", name); // Is the defined_system real? var vm = new ComputerSystem(defined_sys); // Assertion if (vm.ElementName.CompareTo(name) != 0) { var errMsg = string.Format( "New VM created with wrong name (is {0}, should be {1}, GUID {2})", vm.ElementName, name, vm.Name); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return vm; }
private void InsertDiskImage(ComputerSystem vm, string diskImagePath, string diskResourceSubType, ManagementPath drivePath) { // A description of the disk is created by modifying a clone of the default ResourceAllocationSettingData for that disk type string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", diskResourceSubType); var newDiskSettings = CloneStorageAllocationSetting(defaultDiskQuery); // Set file containing the disk image newDiskSettings.LateBoundObject["Parent"] = drivePath.Path; // V2 API uses HostResource to specify image, see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx newDiskSettings.LateBoundObject["HostResource"] = new string[] { diskImagePath }; newDiskSettings.CommitObject(); // Add the new Msvm_StorageAllocationSettingData object as a virtual hard disk to the vm. string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; ManagementPath[] newDiskPaths = AddStorageResource(newDiskResource, vm); // assert if (newDiskPaths.Length != 1) { var errMsg = string.Format( "Failed to add disk image type {3} to VM {0} (GUID {1}): number of resource created {2}", vm.ElementName, vm.Name, newDiskPaths.Length, diskResourceSubType); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ", vm.ElementName, vm.Name, newDiskPaths[0].Path, diskImagePath); }
private static void ModifyVmResources(VirtualSystemManagementService vmMgmtSvc, ComputerSystem vm, string[] resourceSettings) { // Resource settings are changed through the management service System.Management.ManagementPath jobPath; System.Management.ManagementPath[] results; var ret_val = vmMgmtSvc.ModifyResourceSettings( resourceSettings, out jobPath, out results); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted", vm.ElementName, vm.Name, ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } }
/// < summary> /// Removes a storage resource from a computer system. /// </summary> /// <param name="storageSettings">Path that uniquely identifies the resource.</param> /// <param name="vm">VM to which the disk image will be attached.</param> private void RemoveStorageResource(ManagementPath resourcePath, ComputerSystem vm) { var virtSysMgmtSvc = GetVirtualisationSystemManagementService(); ManagementPath jobPath; var ret_val = virtSysMgmtSvc.RemoveResourceSettings( new ManagementPath[] { resourcePath }, out jobPath); // If the Job is done asynchronously if (ret_val == ReturnCode.Started) { JobCompleted(jobPath); } else if (ret_val != ReturnCode.Completed) { var errMsg = string.Format( "Failed to remove resource {0} from VM {1} (GUID {2}) due to {3}", resourcePath.Path, vm.ElementName, vm.Name, ReturnCode.ToString(ret_val)); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } }
private ManagementPath AddScsiController(ComputerSystem vm) { // A description of the controller is created by modifying a clone of the default ResourceAllocationSettingData for scsi controller string scsiQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", SCSI_CONTROLLER); var scsiSettings = CloneResourceAllocationSetting(scsiQuery); scsiSettings.LateBoundObject["ElementName"] = "SCSI Controller"; scsiSettings.CommitObject(); // Insert SCSI controller into vm string[] newResources = new string[] { scsiSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) }; ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm); // assert if (newResourcePaths.Length != 1) { var errMsg = string.Format( "Failed to add scsi controller to VM {0} (GUID {1}): number of resource created {2}", vm.ElementName, vm.Name, newResourcePaths.Length); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } logger.DebugFormat("New controller type {0} WMI path is {1}s", scsiSettings.ResourceSubType, newResourcePaths[0].Path); return newResourcePaths[0]; }
/// <summary> /// Create a (synthetic) nic, and attach it to the vm /// </summary> /// <param name="vm"></param> /// <param name="mac"></param> /// <param name="vlan"></param> /// <returns></returns> public SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac) { logger.DebugFormat("Creating nic for VM {0} (GUID {1})", vm.ElementName, vm.Name); // Obtain controller for Hyper-V networking subsystem var vmNetMgmtSvc = GetVirtualSwitchManagementService(); // Create NIC resource by cloning the default NIC var synthNICsSettings = SyntheticEthernetPortSettingData.GetInstances(vmNetMgmtSvc.Scope, "InstanceID LIKE \"%Default\""); // Assert if (synthNICsSettings.Count != 1) { var errMsg = string.Format("Internal error, coudl not find default SyntheticEthernetPort instance"); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } var defaultSynthNICSettings = synthNICsSettings.OfType<SyntheticEthernetPortSettingData>().First(); var newSynthNICSettings = new SyntheticEthernetPortSettingData((ManagementBaseObject)defaultSynthNICSettings.LateBoundObject.Clone()); // Assign configuration to new NIC string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' }))); newSynthNICSettings.LateBoundObject["ElementName"] = vm.ElementName; newSynthNICSettings.LateBoundObject["Address"] = normalisedMAC; newSynthNICSettings.LateBoundObject["StaticMacAddress"] = "TRUE"; newSynthNICSettings.LateBoundObject["VirtualSystemIdentifiers"] = new string[] { "{" + Guid.NewGuid().ToString() + "}" }; newSynthNICSettings.CommitObject(); // Insert NIC into vm string[] newResources = new string[] { newSynthNICSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20)}; ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm ); // assert if (newResourcePaths.Length != 1) { var errMsg = string.Format( "Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}", vm.ElementName, vm.Name, newResourcePaths.Length); var ex = new WmiException(errMsg); logger.Error(errMsg, ex); throw ex; } return new SyntheticEthernetPortSettingData(newResourcePaths[0]); }
private ManagementPath GetDiskDriveToScsiController(ComputerSystem vm, string addrOnController) { VirtualSystemSettingData vmSettings = GetVmSettings(vm); var ctrller = GetScsiControllerSettings(vmSettings); return null; }