public VMInfo UpdateVirtualMachine(VMInfo vm)
 {
     try
     {
         Log.WriteStart("'{0}' UpdateVirtualMachine", ProviderSettings.ProviderName);
         VMInfo result = VirtualizationForPC.UpdateVirtualMachine(vm);
         Log.WriteEnd("'{0}' UpdateVirtualMachine", ProviderSettings.ProviderName);
         return result;
     }
     catch (Exception ex)
     {
         Log.WriteError(String.Format("'{0}' UpdateVirtualMachine", ProviderSettings.ProviderName), ex);
         throw;
     }
 }
예제 #2
0
		/// <summary>
		/// Gets a virtual machine information by its identificator.
		/// </summary>
		/// <param name="vmId">Virtual machine id, represented by Guid (for example "4664215D-D195-4E35-BB6F-BFC1F17666EB").</param>
		/// <returns>Virtual machine information, such as Name, HostName, Id, State, count of CPUs assigned, 
		/// CreationTime, ComputerName, Owner, Domain name (if assigned), CPU utilization, CPU performance utilization, RAM</returns>
		public VMInfo GetVirtualMachine(string vmId)
		{
			VMInfo vm = new VMInfo();
			//
			var vmInfo = default(VirtualMachineInfo);
			
			using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
			{
				vmInfo = client.GetVirtualMachineByName(vmId);
				//
				client.Close();
			}

			if (vmInfo == null)
				throw new InvalidDataException(String.Format("GetVirtualMachineByName for VM {0} return NULL value.", vmId));

			vm.logMessage = String.Format("Current state VM {0} is {1}.", vmInfo.Name, vmInfo.Status);

			vm.Name = vmInfo.Name;
			vm.HostName = vmInfo.HostName;
			vm.VmGuid = vmInfo.Id;
			vm.State = (Virtualization.VMComputerSystemStateInfo)vmInfo.Status;
			vm.CPUCount = vmInfo.CPUCount;
			vm.CreatedDate = vmInfo.CreationTime;
			vm.ComputerName = vmInfo.ComputerName;
			vm.Owner = vmInfo.Owner;
			vm.JoinDomain = (vmInfo.VMHost == null ? string.Empty : vmInfo.VMHost.DomainName);
			vm.CPUUtilization = vmInfo.CPUUtilization;
			vm.PerfCPUUtilization = vmInfo.perfCPUUtilization;
			vm.ModifiedTime = "00:00:00";
			vm.Memory = vmInfo.Memory;
			vm.ProcessMemory = vmInfo.Memory;

			if ((vmInfo.VirtualHardDisks != null)
			 && (vmInfo.VirtualHardDisks.Length > 0))
			{
				vm.HddLogicalDisks = new LogicalDisk[vmInfo.VirtualHardDisks.Length];
				for (int i = 0; i < vmInfo.VirtualHardDisks.Length; i++)
				{
					vm.HddLogicalDisks[i] = new LogicalDisk();
					var d = vmInfo.VirtualHardDisks[i];
					if (d != null)
					{
						vm.HddLogicalDisks[i].Size = (int)(d.MaximumSize / ByteToGbByte);
						vm.HddLogicalDisks[i].FreeSpace = (int)(((long)d.MaximumSize - vmInfo.VirtualHardDisks[i].Size) / ByteToGbByte);
						vm.HddLogicalDisks[i].DriveLetter = d.Name;
					}
				}
			}

			vm.ProvisioningStatus = VirtualMachineProvisioningStatus.OK;

			return vm;
		}
예제 #3
0
		public VMInfo CreateVMFromVM(string sourceName, VMInfo vmTemplate, Guid taskGuid)
		{
			string paramCreate = String.Empty;
			//
			var steps = new StringBuilder();

			try
			{
				steps.AppendLine("Start Connect to ScVMM (new VirtualMachineManagementServiceClient)");
				//
				using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
				{
					steps.AppendLine("Connected to ScVMM");
					//
					#region Hardware profiles
					steps.AppendLine("Start select Hardware Profle (GetHardwareProfles())");
					HardwareProfileInfo[] hProfiles = client.GetHardwareProfles();

					if (hProfiles == null || hProfiles.Length == 0)
						throw new Exception("No hardware profile found can't continue.");
					steps.AppendLine("Hardware Profle selected");
					#endregion

					steps.AppendLine("Start Get template VM info (GetVirtualMachineByName())");
					//
					VirtualMachineInfo sourceVM = client.GetVirtualMachineByName(sourceName);
					//
					steps.AppendLine("Done Get template VM info");
					//
					if (sourceVM.Status == SVMMService.VMComputerSystemStateInfo.CreationFailed
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.CustomizationFailed
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.UpdateFailed
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.Deleting
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.TemplateCreationFailed
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.UnderCreation
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.UnderTemplateCreation
						&& sourceVM.Status == SVMMService.VMComputerSystemStateInfo.UnderUpdate)
					{
						throw new Exception(String.Format("Creation Failed. Template state = {0}.", sourceVM.Status));
					}

					if (sourceVM.Status != SVMMService.VMComputerSystemStateInfo.PowerOff
						&& sourceVM.Status != SVMMService.VMComputerSystemStateInfo.Stored
						&& sourceVM.Status != SVMMService.VMComputerSystemStateInfo.Saved)
					{
						//
						steps.AppendLine("Template VM Stopping (ShutdownVirtualMachine())");
						//
						client.ShutdownVirtualMachine(sourceVM.Id);

						while (sourceVM.Status != SVMMService.VMComputerSystemStateInfo.Stored
							&& sourceVM.Status != SVMMService.VMComputerSystemStateInfo.PowerOff
							&& sourceVM.Status != SVMMService.VMComputerSystemStateInfo.UpdateFailed)
						{
							System.Threading.Thread.Sleep(5000);
							sourceVM = client.GetVirtualMachineByName(sourceName);
						}

						if (sourceVM.Status == WebsitePanel.Providers.VirtualizationForPC.SVMMService.VMComputerSystemStateInfo.UpdateFailed)
						{
							throw new Exception(String.Format("Creation Failed. Template not stoped. Current state = {0}", sourceVM.Status));
						}
						//
						steps.AppendLine("Template VM Stoped");
					}

					#region Library
					steps.AppendLine("Start Select library (GetLibraryServers())");
					LibraryServerInfo[] arrLi = client.GetLibraryServers();
					if (arrLi.Length == 0)
						throw new InvalidOperationException("Get library servers returns empty list");

					LibraryServerInfo li = null;

					foreach (var cur in arrLi)
					{
						if (LibraryPath.ToLower().Contains(cur.ComputerName.ToLower()))
						{
							li = cur;
							break;
						}
					}

					if (li == null)
						throw new Exception(string.Format("Library server for share {0} not found.", LibraryPath));

					if (li.Status != ComputerStateInfo.Responding && li.Status != ComputerStateInfo.Pending && li.Status != ComputerStateInfo.Updating)
						throw new InvalidOperationException(string.Format("Library server {0} in invalid state {1}", li.ComputerName, li.Status));

					steps.AppendLine("Library selected");
					#endregion

					paramCreate = String.Format("Params: SourceVM ID: {0}\n New VM Name: {1}\n Owner Name : {2}\n Library : {3}\n Liblary Path:{4}\n Hardware profile:{5}\n"
						, sourceVM.Id, vmTemplate.Name, sourceVM.Owner, (li != null ? li.Name : "unknown"), LibraryPath, hProfiles[0].Name);

					steps.AppendLine("Start Create VM (NewVirtualMachineFromVM())");

					taskGuid = (((taskGuid == null) || (taskGuid == Guid.Empty)) ? Guid.NewGuid() : taskGuid);

					#region GetMovement params
					HostInfo hostInfo = null;
					if (ServerType.Equals("cluster"))
					{
						steps.AppendLine("Start Get Host by Rating (GetVMHostRatingsByCluster())");
						var ratings = client.GetVMHostRatingsByCluster(sourceVM.Id, true, ServerNameSettings).OrderByDescending(item => item.Rating).ToList();
						if (ratings.Count == 0)
							throw new InvalidOperationException("got empty ratings list");

						hostInfo = ratings.ToArray()[0].VMHost;
						steps.AppendLine("Done Get Host by Rating");
					}
					else
					{
						steps.AppendLine("Start Get Host (GetHostByName())");
						hostInfo = client.GetHostByName(ServerNameSettings);
						steps.AppendLine("Done Get Host");
					}
					#endregion
					//
					steps.AppendLine("start NewVirtualMachineFromVM");
					//
					VirtualMachineInfo newVM = client.NewVirtualMachineFromVM(sourceVM.Id
																			, vmTemplate.Name
																			, string.Format("Clone of {0}", sourceVM.Name)
																			, sourceVM.Owner
																			, li
																			, LibraryPath
																			, hProfiles[0]
																			, taskGuid);
					//
					steps.AppendLine("end NewVirtualMachineFromVM");
					//
					steps.AppendFormat("start MoveVirtualMachine {0} to {1} - {2}", newVM.Name, hostInfo.ComputerName, hostInfo.VMPaths[0]).AppendLine();
					//
					client.MoveVirtualMachine(newVM.Id, hostInfo.Id, hostInfo.VMPaths[0], false, true, false, taskGuid);
					//
					steps.AppendLine("end MoveVirtualMachine");

					vmTemplate.VmGuid = newVM.Id;
					vmTemplate.ComputerName = newVM.ComputerName;
					vmTemplate.State = (Virtualization.VMComputerSystemStateInfo)newVM.Status;
					vmTemplate.ProvisioningStatus = VirtualMachineProvisioningStatus.InProgress;
					//
					steps.AppendLine("VM created");
				}
			}
			catch (System.TimeoutException)
			{
				vmTemplate.ProvisioningStatus = VirtualMachineProvisioningStatus.InProgress;
			}
			catch (Exception ex)
			{
				vmTemplate.ProvisioningStatus = VirtualMachineProvisioningStatus.Error;
				// TO-DO: Possibly we should avoid exposing such detailed exceptions to the end-user
				vmTemplate.exMessage = ex.Message + "\n";
				//
				Log.WriteError(ex);
			}
			// 
			vmTemplate.logMessage = paramCreate + steps;

			//// Переносим виртуалку
			//Providers.Virtualization.VMComputerSystemStateInfo state = vmTemplate.State;

			//while (state == Providers.Virtualization.VMComputerSystemStateInfo.UnderCreation)
			//{
			//    System.Threading.Thread.Sleep(10000);
			//    VMInfo stateVmInfo = GetVirtualMachine(vmTemplate.Name);
			//    state = stateVmInfo.State;
			//}

			//if ((state == Providers.Virtualization.VMComputerSystemStateInfo.PowerOff)
			//    || (state == Providers.Virtualization.VMComputerSystemStateInfo.Stored)
			//    || (state == Providers.Virtualization.VMComputerSystemStateInfo.Saved)
			//    || String.IsNullOrEmpty(vmTemplate.exMessage))
			//{
			//    vmTemplate = MoveVM(vmTemplate);
			//}

			return vmTemplate;
		}
		/// <remarks/>
		public void UpdateVirtualMachineAsync(VMInfo vm)
		{
			this.UpdateVirtualMachineAsync(vm, null);
		}
예제 #5
0
		public void ConfigureCreatedVMNetworkAdapters(VMInfo vmInfo)
		{
			//
			var vm = default(VirtualMachineInfo);
			// Retrieve current VM details
			using (var client = GetVMMSClient())
			{
				vm = client.GetVirtualMachineByName(vmInfo.Name);
			}
			// Validate VM status
			if (vm.Status != SVMMService.VMComputerSystemStateInfo.PowerOff && vm.Status != SVMMService.VMComputerSystemStateInfo.Stored)
			{
				throw new ApplicationException("Virtual machine should has status PowerOff to configure network adapters");
			}
			// Remove exists Network adapters
			DeleteNetworkAdapters(vm.Id);
			// Find out if external nic should be added
			//if (vmInfo.ExternalNetworkEnabled)
			//{
			//    using (var ps = PowerShell.Create())
			//    {
			//        ps.NewVirtualNetworkAdapter(vm.Id, vmInfo.ExternalVirtualNetwork, null);
			//    }
			//}
			//// Find out if private nic should be added
			//if (vmInfo.PrivateNetworkEnabled)
			//{
			//    using (var ps = PowerShell.Create())
			//    {
			//        ps.NewVirtualNetworkAdapter(vm.Id, vmInfo.PrivateVirtualNetwork, vmInfo.PrivateVLanID);
			//    }
			//}
		}
		/// <remarks/>
		public void CreateVMFromVMAsync(string sourceName, VMInfo vmTemplate, System.Guid taskGuid)
		{
			this.CreateVMFromVMAsync(sourceName, vmTemplate, taskGuid, null);
		}
		public VMInfo UpdateVirtualMachine(VMInfo vm)
		{
			object[] results = this.Invoke("UpdateVirtualMachine", new object[] {
                        vm});
			return ((VMInfo)(results[0]));
		}
		public void ConfigureCreatedVMNetworkAdapters(VMInfo vmInfo)
		{
			this.Invoke("ConfigureCreatedVMNetworkAdapters", new object[] {
                        vmInfo});
		}
		/// <remarks/>
		public System.IAsyncResult BeginConfigureCreatedVMNetworkAdapters(VMInfo vmInfo, System.AsyncCallback callback, object asyncState)
		{
			return this.BeginInvoke("ConfigureCreatedVMNetworkAdapters", new object[] {
                        vmInfo}, callback, asyncState);
		}
 public ResultObject CreateVMFromVM(int packageId, VMInfo vmTemplate, string vmName)
 {
     return VirtualizationServerControllerForPrivateCloud.CreateVMFromVM(packageId, vmTemplate, vmName);
 }
 public void ConfigureCreatedVMNetworkAdapters(VMInfo vmInfo)
 {
     VirtualizationServerControllerForPrivateCloud.ConfigureCreatedVMNetworkAdapters(vmInfo);
 }
예제 #12
0
		public VMInfo UpdateVirtualMachine(VMInfo vm)
		{
			string vmId = vm.Name;

			using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
			{

				VirtualMachineInfo vmi = client.GetVirtualMachineByName(vm.Name);

				#region This code is intended to update a VM settings only in Host mode but it does not support Cluster mode
				// get VM object
				ManagementObject objVM = GetVirtualMachineObject(vmId);

				//// update general settings
				//UpdateVirtualMachineGeneralSettings(vmId, objVM,
				//    vm.CpuCores,
				//    vm.RamSize,
				//    vm.BootFromCD,
				//    vm.NumLockEnabled);

				// check DVD drive
				ManagementObject objDvdDrive = wmi.GetWmiObject(
					"Msvm_ResourceAllocationSettingData", "ResourceSubType = 'Microsoft Synthetic DVD Drive'"
						+ " and InstanceID like 'Microsoft:{0}%' and Address = 0", vmId);

				if (vm.DvdDriver && objDvdDrive == null)
					AddVirtualMachineDvdDrive(vmId, objVM);
				else if (!vm.DvdDriver && objDvdDrive != null)
					RemoveVirtualMachineResources(objVM, objDvdDrive);

				// External NIC
				if (!vm.ExternalNetworkEnabled
					&& !String.IsNullOrEmpty(vm.ExternalNicMacAddress))
				{
					// delete adapter
					//                DeleteNetworkAdapter(objVM, vm.ExternalNicMacAddress);

					// reset MAC
					vm.ExternalNicMacAddress = null;
				}
				else if (vm.ExternalNetworkEnabled
					&& !String.IsNullOrEmpty(vm.ExternalNicMacAddress))
				{
					// add external adapter
					//AddNetworkAdapter(objVM, vm.ExternalSwitchId, vm.Name, vm.ExternalNicMacAddress, EXTERNAL_NETWORK_ADAPTER_NAME, vm.LegacyNetworkAdapter);
				}


				// Private NIC
				if (!vm.PrivateNetworkEnabled
					&& !String.IsNullOrEmpty(vm.PrivateNicMacAddress))
				{
					// delete adapter
					//                DeleteNetworkAdapter(objVM, vm.PrivateNicMacAddress);

					// reset MAC
					vm.PrivateNicMacAddress = null;
				}
				else if (vm.PrivateNetworkEnabled
					&& !String.IsNullOrEmpty(vm.PrivateNicMacAddress))
				{
					// add private adapter
					//AddNetworkAdapter(objVM, vm.PrivateSwitchId, vm.Name, vm.PrivateNicMacAddress, PRIVATE_NETWORK_ADAPTER_NAME, vm.LegacyNetworkAdapter);
				}
				#endregion
			}

			return vm;
		}
예제 #13
0
		public VMInfo CreateVirtualMachine(VMInfo vm)
		{
			// Evaluate paths
			try
			{
				using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
				{
					TemplateInfo selTemplate = client.GetTemplateById(vm.TemplateId);

					HostInfo hostInfo = null;

					if (ServerType.Equals("cluster"))
					{
						HostClusterInfo selCluster = client.GetHostClusterByName(ServerNameSettings);

						if (selCluster.Nodes != null)
						{
							foreach (HostInfo curr in selCluster.Nodes)
							{
								if (curr.AvailableForPlacement)
								{
									hostInfo = curr;
									break;
								}
							}
						}
					}

					if (hostInfo == null)
					{
						try
						{
							hostInfo = client.GetHostByName(String.IsNullOrWhiteSpace(ServerNameSettings)
								? selTemplate.HostName : ServerNameSettings);
						}
						catch (Exception ex)
						{
							hostInfo = null;
							//
							Log.WriteError(ex);
						}
					}

					selTemplate.CPUCount = Convert.ToByte(vm.CPUCount);
					selTemplate.Memory = vm.Memory;
					selTemplate.TotalVHDCapacity = (ulong)(vm.HddSize * ByteToGbByte);

					if (!vm.DvdDriver)
					{
						selTemplate.VirtualDVDDrives = null;
					}

					try
					{
						GuestOSProfileInfo gos = new GuestOSProfileInfo();

						VirtualMachineInfo newVM = client.NewVirtualMachineFromTemplate(selTemplate
															 , vm.Name
															 , null
															 , selTemplate.Owner
															 , hostInfo
															 , hostInfo.VMPaths[0]
															 , null
															 , gos
															 , vm.AdminUserName
															 , vm.AdminPassword
															 , selTemplate.SysprepScript
															 , new Guid(vm.CurrentTaskId)
															 , vm.ComputerName
															 , null
															 , vm.JoinDomain
															 , vm.JoinDomainUserName
															 , vm.MergeAnswerFile
															 , selTemplate.OperatingSystem
															 , selTemplate.GuiRunOnceCommands
															 , vm.JoinDomainPassword
															 , (String.IsNullOrWhiteSpace(vm.JoinDomain) ?
																   selTemplate.JoinWorkgroup : null)
															 , null
															 , (selTemplate.ProductKeyHasValue ? null : vm.ProductKey)
															 , null);


						vm.VmGuid = newVM.Id;
						vm.TemplateName = selTemplate.Name;
						vm.ComputerName = newVM.ComputerName;
						vm.State = (Virtualization.VMComputerSystemStateInfo)newVM.Status;
						vm.ProvisioningStatus = VirtualMachineProvisioningStatus.InProgress;

						vm.CurrentJob = new ConcreteJob();
						vm.CurrentJob.Id = vm.Name;
						vm.CurrentJob.JobState = ConcreteJobState.Running;
						vm.CurrentJob.TargetState = Virtualization.VMComputerSystemStateInfo.PowerOff;

						// Warning: 5 seconds thread sleep
						System.Threading.Thread.Sleep(5000);

						VirtualMachineInfo vmWait = client.GetVirtualMachineByName(vm.Name);

						while (vmWait.Status == SVMMService.VMComputerSystemStateInfo.UnderCreation)
						{
							System.Threading.Thread.Sleep(30000);
							vmWait = client.GetVirtualMachineByName(vm.Name);
						}

						if (vmWait.Status != SVMMService.VMComputerSystemStateInfo.CreationFailed)
						{
							if ((vmWait.Status != SVMMService.VMComputerSystemStateInfo.PowerOff)
							 && (vmWait.Status != SVMMService.VMComputerSystemStateInfo.Stored))
							{
								client.ShutdownVirtualMachine(vmWait.Id);

								while (vmWait.Status != SVMMService.VMComputerSystemStateInfo.Stored
									&& vmWait.Status != SVMMService.VMComputerSystemStateInfo.PowerOff
									&& vmWait.Status != SVMMService.VMComputerSystemStateInfo.UpdateFailed)
								{
									System.Threading.Thread.Sleep(5000);
									vmWait = client.GetVirtualMachineByName(vmWait.Name);
								}

							}

							ConfigureCreatedVMNetworkAdapters(vm);
						}
					}
					catch (Exception ex)
					{
						vm.ProvisioningStatus = VirtualMachineProvisioningStatus.Error;
						throw;
					}
				}
			}
			catch (Exception ex)
			{
				vm.ProvisioningStatus = VirtualMachineProvisioningStatus.Error;
				// TODO: Possibly we should avoid exposing such detailed exceptions to the end-user
				vm.exMessage = ex.Message;
				// Log the exception occured
				Log.WriteError(ex);
			}
			//
			return vm;
		}
예제 #14
0
		public void ConfigureCreatedVMNetworkAdapters(VMInfo vmInfo)
		{
			using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
			{
				VirtualMachineInfo vm = client.GetVirtualMachineByName(vmInfo.Name);

				if (vm.Status != SVMMService.VMComputerSystemStateInfo.PowerOff && vm.Status != SVMMService.VMComputerSystemStateInfo.Stored)
				{
					throw new ApplicationException("Virtual machine should has status PowerOff to configure network adapters");
				}
				// Remove exists Network adapters
				VirtualNetworkAdapterInfo[] existsNetworkAdapters = vm.VirtualNetworkAdapters;
				foreach (VirtualNetworkAdapterInfo adapter in existsNetworkAdapters)
					client.RemoveVirtualNetworkAdapter(adapter, false, new Guid(vmInfo.CurrentTaskId));

				// Add external network
				if (vmInfo.ExternalNetworkEnabled)
				{
					client.NewVMVirtualNetworkAdapter(
						vm.Id,
						string.IsNullOrEmpty(vmInfo.ExternalNicMacAddress) ? MacAddressHelper.GetNewMacAddress() : vmInfo.ExternalNicMacAddress,
						EthernetAddressTypeInfo.Static,
						vmInfo.ExternalVirtualNetwork);
				}

				// Add private network
				if (vmInfo.PrivateNetworkEnabled)
				{
					VirtualNetworkAdapterInfo adapter = client.NewVMVirtualNetworkAdapter(
						vm.Id,
						string.IsNullOrEmpty(vmInfo.PrivateNicMacAddress) ? MacAddressHelper.GetNewMacAddress() : vmInfo.PrivateNicMacAddress,
						EthernetAddressTypeInfo.Static,
						vmInfo.PrivateVirtualNetwork
						);

					// Update vLanID
					client.SetVirtualNetworkAdapter(
						adapter,
						null,
						null,
						null,
						null,
						null,
						true,
						vmInfo.PrivateVLanID,
						false,
						new Guid(vmInfo.CurrentTaskId)
						);
				}
			}
		}
		public VMInfo CreateVMFromVM(string sourceName, VMInfo vmTemplate, System.Guid taskGuid)
		{
			object[] results = this.Invoke("CreateVMFromVM", new object[] {
                        sourceName,
                        vmTemplate,
                        taskGuid});
			return ((VMInfo)(results[0]));
		}
		/// <remarks/>
		public void ConfigureCreatedVMNetworkAdaptersAsync(VMInfo vmInfo)
		{
			this.ConfigureCreatedVMNetworkAdaptersAsync(vmInfo, null);
		}
		/// <remarks/>
		public System.IAsyncResult BeginCreateVMFromVM(string sourceName, VMInfo vmTemplate, System.Guid taskGuid, System.AsyncCallback callback, object asyncState)
		{
			return this.BeginInvoke("CreateVMFromVM", new object[] {
                        sourceName,
                        vmTemplate,
                        taskGuid}, callback, asyncState);
		}
		/// <remarks/>
		public void ConfigureCreatedVMNetworkAdaptersAsync(VMInfo vmInfo, object userState)
		{
			if ((this.ConfigureCreatedVMNetworkAdaptersOperationCompleted == null))
			{
				this.ConfigureCreatedVMNetworkAdaptersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnConfigureCreatedVMNetworkAdaptersOperationCompleted);
			}
			this.InvokeAsync("ConfigureCreatedVMNetworkAdapters", new object[] {
                        vmInfo}, this.ConfigureCreatedVMNetworkAdaptersOperationCompleted, userState);
		}
		/// <remarks/>
		public void CreateVMFromVMAsync(string sourceName, VMInfo vmTemplate, System.Guid taskGuid, object userState)
		{
			if ((this.CreateVMFromVMOperationCompleted == null))
			{
				this.CreateVMFromVMOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateVMFromVMOperationCompleted);
			}
			this.InvokeAsync("CreateVMFromVM", new object[] {
                        sourceName,
                        vmTemplate,
                        taskGuid}, this.CreateVMFromVMOperationCompleted, userState);
		}
		public VMInfo MoveVM(VMInfo vmForMove)
		{
			object[] results = this.Invoke("MoveVM", new object[] {
                        vmForMove});
			return ((VMInfo)(results[0]));
		}
		/// <remarks/>
		public System.IAsyncResult BeginUpdateVirtualMachine(VMInfo vm, System.AsyncCallback callback, object asyncState)
		{
			return this.BeginInvoke("UpdateVirtualMachine", new object[] {
                        vm}, callback, asyncState);
		}
		/// <remarks/>
		public System.IAsyncResult BeginMoveVM(VMInfo vmForMove, System.AsyncCallback callback, object asyncState)
		{
			return this.BeginInvoke("MoveVM", new object[] {
                        vmForMove}, callback, asyncState);
		}
		/// <remarks/>
		public void UpdateVirtualMachineAsync(VMInfo vm, object userState)
		{
			if ((this.UpdateVirtualMachineOperationCompleted == null))
			{
				this.UpdateVirtualMachineOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateVirtualMachineOperationCompleted);
			}
			this.InvokeAsync("UpdateVirtualMachine", new object[] {
                        vm}, this.UpdateVirtualMachineOperationCompleted, userState);
		}
		/// <remarks/>
		public void MoveVMAsync(VMInfo vmForMove)
		{
			this.MoveVMAsync(vmForMove, null);
		}
예제 #25
0
		public VMInfo UpdateVirtualMachine(VMInfo vm)
		{
			throw new NotImplementedException();
		}
		/// <remarks/>
		public void MoveVMAsync(VMInfo vmForMove, object userState)
		{
			if ((this.MoveVMOperationCompleted == null))
			{
				this.MoveVMOperationCompleted = new System.Threading.SendOrPostCallback(this.OnMoveVMOperationCompleted);
			}
			this.InvokeAsync("MoveVM", new object[] {
                        vmForMove}, this.MoveVMOperationCompleted, userState);
		}
예제 #27
0
		public VMInfo CreateVirtualMachine(VMInfo vm)
		{
			// Evaluate VM placement options configured
			try
			{
				//
				var jobGroup = new Guid(vm.CurrentTaskId);
				//
				var hostInfo = default(HostInfo);
				//
				#region Find out placement options, e.q. either deploy VM via cluster or directly on a host
				using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
				{
					TemplateInfo selTemplate = client.GetTemplateById(vm.TemplateId);
					//
					if (ServerType.Equals("cluster"))
					{
						HostClusterInfo selCluster = client.GetHostClusterByName(ServerNameSettings);

						if (selCluster.Nodes != null)
						{
							foreach (HostInfo curr in selCluster.Nodes)
							{
								if (curr.AvailableForPlacement)
								{
									hostInfo = curr;
									//
									break;
								}
							}
						}
					}

					if (hostInfo == null)
					{
						try
						{
                            hostInfo = client.GetHostByName(IsNullOrWhiteSpaceString(ServerNameSettings)
								? selTemplate.HostName : ServerNameSettings);
						}
						catch (Exception ex)
						{
							hostInfo = null;
							//
							Log.WriteError(ex);
						}
					}
				}
				#endregion
				//
				using (var ps = PowerShell.Create())
				{
					// Register snap-in
					ps.AddSystemCenterSnapIn();
					// Establish connection
					ps.AddConnectionScript();
					//
					ps.AddScriptWithTrace(new StringBuilder("$MyVM = @{")
						.Append("JobGroup = [System.Guid]::NewGuid();")
						.Append("HWProfileName = [System.String]::Concat(\"Profile\", [System.Guid]::NewGuid());")
						.AppendFormat("Name = \"{0}\";", vm.Name)
						.AppendFormat("TemplateId = \"{0}\";", vm.TemplateId)
						.AppendFormat("VMHostId = \"{0}\";", hostInfo.Id)
						.AppendFormat("CPUCount = {0};", vm.CPUCount)
						.AppendFormat("MemoryMB = {0};", vm.Memory)
						.AppendFormat("CPUMax = {0};", CpuLimitSettings)
						.AppendFormat("CPUReserve = {0};", CpuReserveSettings)
						.AppendFormat("RelativeWeight = {0};", CpuWeightSettings)
						.AppendFormat("NumLock = {0};", vm.NumLockEnabled ? "$true" : "$false")
						.AppendFormat("StartAction = {0};", AutomaticStartActionSettings)
						.AppendFormat("StopAction = {0};", AutomaticStopActionSettings)
						.AppendFormat("DelayStart = {0};", AutomaticStartupDelaySettings)
						.AppendFormat("HighlyAvailable = {0};", ServerType.Equals("cluster") ? "$true" : "$false")
						.Append("}")
						.ToString());
					//
					if (vm.ExternalNetworkEnabled)
					{
						//
						ps.AddScriptWithTrace(new StringBuilder("$MyVM.Nic1 = @{")
							.AppendFormat("VirtualNetwork = \"{0}\";", vm.ExternalVirtualNetwork)
							.Append("MacAddress = (New-PhysicalAddress -Commit);")
							.Append("}")
							.ToString());
						//
						ps.AddScriptWithTrace("New-VirtualNetworkAdapter -VirtualNetwork $MyVM.Nic1.VirtualNetwork -JobGroup $MyVM.JobGroup -PhysicalAddress $MyVM.Nic1.MacAddress -PhysicalAddressType Static -VLanEnabled $false");
					}
					//
					if (vm.PrivateNetworkEnabled)
					{
						//
						ps.AddScriptWithTrace(new StringBuilder("$MyVM.Nic2 = @{")
							.Append("MacAddress = (New-PhysicalAddress -Commit);")
							.AppendFormat("VirtualNetwork = \"{0}\";", vm.PrivateVirtualNetwork)
							.AppendFormat("VLanEnabled = {0};", (vm.PrivateVLanID > ushort.MinValue) ? "$true" : "$false")
							.AppendFormat("VLanId = {0};", vm.PrivateVLanID)
							.Append("}")
							.ToString());
						//
						ps.AddScriptWithTrace("New-VirtualNetworkAdapter -VirtualNetwork $MyVM.Nic2.VirtualNetwork -JobGroup $MyVM.JobGroup -PhysicalAddress $MyVM.Nic2.MacAddress -PhysicalAddressType Static -VLanEnabled $MyVM.Nic2.VLanEnabled -VLanId $MyVM.Nic2.VLanId");
					}
					//
					ps.AddScriptWithTrace("$Template = Get-Template | Where-Object {$_.ID -eq $MyVM.TemplateId}");
					// Retrieve operating system info chosen for the template
					ps.AddScriptWithTrace("$OperatingSystem = Get-OperatingSystem | Where-Object {$_.Name -eq $Template.OperatingSystem}");
					// Retrieve host info we chose for the VM placement
					ps.AddScriptWithTrace("$VMHost = Get-VMHost | Where-Object {$_.ID -eq $MyVM.VMHostId}");
					// Add SCSI Adapters to the hardware profile being created if any
					ps.AddScriptWithTrace("$Template.VirtualSCSIAdapters | ForEach-Object { New-VirtualSCSIAdapter -AdapterID $_.AdapterID  -Shared $_.Shared -JobGroup $MyVM.JobGroup }");
					// Create a hardware profile to be attached to the VM being provisoned
					ps.AddScriptWithTrace("$HardwareProfile = New-HardwareProfile -CPUType $Template.CPUType -Name $MyVM.HWProfileName -Description \"Profile used to create a VM/Template\" -HighlyAvailable $MyVM.HighlyAvailable -CPUCount $MyVM.CPUCount -MemoryMB $MyVM.MemoryMB -CPUMax $MyVM.CPUMax -CPUReserve $MyVM.CPUReserve -RelativeWeight $MyVM.RelativeWeight -NumLock $MyVM.NumLock -JobGroup $MyVM.JobGroup");
					// Create VM with the settings specified
					ps.AddScriptWithTrace("New-VM -Template $Template -Name $MyVM.Name -VMHost $VMHost -Path $VMHost.VMPaths[0] -JobGroup $MyVM.JobGroup -RunAsynchronously -HardwareProfile $HardwareProfile -ComputerName $MyVM.Name -AnswerFile $null -OperatingSystem $OperatingSystem -RunAsSystem -StartAction $MyVM.StartAction -DelayStart $MyVM.DelayStart -StopAction $MyVM.StopAction");
					// Remove the hardware profile we used to instantiate the VM
					ps.AddScriptWithTrace("Remove-HardwareProfile $HardwareProfile");
					//
					ps.InvokeAndDumpResults();
				}

				// Warning: 5 seconds thread sleep
				System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5).Milliseconds);
				//
				var vmWait = default(VirtualMachineInfo);
				//
				while (vmWait == null
					|| vmWait.Status == SVMMService.VMComputerSystemStateInfo.UnderCreation)
				{
					using (var client = GetVMMSClient())
					{
						vmWait = client.GetVirtualMachineByName(vm.Name);
					}
					// Warning: 3 seconds thread sleep
					System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30).Milliseconds);
				}
				// Expand virtual machine disk up to the size requested
				if (vmWait.Status != SVMMService.VMComputerSystemStateInfo.CreationFailed)
				{
					using (var ps = PowerShell.Create())
					{
						ps.AddSystemCenterSnapIn();
						//
						ps.AddConnectionScript();
						//
						ps.AddScript("$MyVM = Get-VM -ID \"{0}\"", vmWait.Id);
						//
						ps.AddScript("$MyVM.VirtualDiskDrives | Where-Object {($_.BusType -eq \"IDE\") -and ($_.Bus -eq 0)} | Expand-VirtualDiskDrive -Size " + vm.HddSize);
						//
						ps.AddScriptWithTrace("Start-VM -VM $MyVM -RunAsynchronously");
						//
						ps.InvokeAndDumpResults();
					}
				}
			}
			catch (Exception ex)
			{
				vm.ProvisioningStatus = VirtualMachineProvisioningStatus.Error;
				// TODO: Possibly we should avoid exposing such detailed exceptions to the end-user
				vm.exMessage = ex.Message;
				// Log the exception occured
				Log.WriteError(ex);
			}
			//
			return vm;
		}
		/// <remarks/>
		public void CreateVirtualMachineAsync(VMInfo vm)
		{
			this.CreateVirtualMachineAsync(vm, null);
		}
예제 #29
0
		public VMInfo MoveVM(VMInfo vmForMove)
		{
			var steps = new StringBuilder().AppendLine("MoveVM");
			//
			string paramsMove = String.Empty;
			try
			{
				steps.AppendLine("Start Connect to ScVNMM (new VirtualMachineManagementServiceClient)");
				using (WSPVirtualMachineManagementServiceClient client = GetVMMSClient())
				{
					steps.AppendLine("Connected to ScVNMM");
					//
					steps.AppendLine("Start Get source VM info (GetVirtualMachineByName() )");
					//
					VirtualMachineInfo sourceVM = client.GetVirtualMachineByName(vmForMove.Name);
					//
					steps.AppendLine("Done Get source VM info");

					HostInfo hostInfo = null;

					if (ServerType.Equals("cluster"))
					{
						steps.AppendLine("Start Get Cluster (GetHostClusterByName())");
						//
						HostClusterInfo selCluster = client.GetHostClusterByName(ServerNameSettings);
						//
						steps.AppendLine("Done Get Cluster (GetHostClusterByName())");
						steps.AppendLine("Start Get Host by Rating (GetVMHostRatingsByCluster())");
						//
						VMHostRatingInfo overHost = client.GetVMHostRatingsByCluster(sourceVM.Id, true, ServerNameSettings)
							   .OrderByDescending(item => item.Rating).ToArray()[0];

						if (overHost != null)
						{
							hostInfo = overHost.VMHost;
						}
						//
						steps.AppendLine("Done Get Host by Rating");
					}
					else
					{
						steps.AppendLine("Start Get Host (GetHostByName())");
						hostInfo = client.GetHostByName(ServerNameSettings);
						steps.AppendLine("Done Get Host");
					}

					if (hostInfo == null)
					{
						throw new Exception("Host not found.");
					}

					paramsMove = String.Format("VM Id: {0}\n Host Id: {1}\n VM Path: {2}\n", sourceVM.Id, hostInfo.Id, hostInfo.VMPaths[0]);
					//
					steps.AppendLine("Start Move VM (MoveVirtualMachine)");
					//
					client.MoveVirtualMachine(sourceVM.Id, hostInfo.Id, hostInfo.VMPaths[0], false, true, true, null);
					//
					steps.AppendLine("Done Move VM (MoveVirtualMachine)");
				}
			}
			catch (Exception ex)
			{
				// TO-DO: Possibly we should avoid exposing such detailed exceptions to the end-user
				vmForMove.exMessage = vmForMove.exMessage + "\n MoveVM \n" + ex.Message;
				//
				Log.WriteError(ex);
			}

			vmForMove.logMessage = vmForMove.logMessage + steps + paramsMove;
			return vmForMove;
		}
        public VMInfo CreateVMFromVM(string sourceName, VMInfo vmTemplate, Guid taskGuid)
        {
            VMInfo result = vmTemplate;
            try
            {
                Log.WriteStart("'{0}' CreateVMFromVM", ProviderSettings.ProviderName);
                result = VirtualizationForPC.CreateVMFromVM(sourceName, vmTemplate, taskGuid);
                Log.WriteEnd("'{0}' CreateVMFromVM", ProviderSettings.ProviderName);
                return result;
            }
            catch (System.TimeoutException)
            {
                return result;
            }
            catch (Exception ex)
            {
                Log.WriteError(String.Format("'{0}' CreateVMFromVM", ProviderSettings.ProviderName), ex);
                throw;
            }

        }