internal XSVNCScreen(VM source, EventHandler resizeHandler, VNCTabView parent, string elevatedUsername, string elevatedPassword) : base() { this.ResizeHandler = resizeHandler; this.parentVNCTabView = parent; this.Source = source; this.KeyHandler = parentVNCTabView.KeyHandler; ElevatedUsername = elevatedUsername; ElevatedPassword = elevatedPassword; #pragma warning disable 0219 IntPtr _ = Handle; #pragma warning restore 0219 initSubControl(); //We're going to try and catch when the IP address changes for the VM, and re-scan for ports. if (source == null) { return; } Properties.Settings.Default.PropertyChanged += Default_PropertyChanged; VM_guest_metrics guestMetrics = Source.Connection.Resolve <VM_guest_metrics>(Source.guest_metrics); if (guestMetrics == null) { return; } cachedNetworks = guestMetrics.networks; guestMetrics.PropertyChanged += new PropertyChangedEventHandler(guestMetrics_PropertyChanged); }
private void VM_PropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "name_label" || args.PropertyName == "allowed_operations" || args.PropertyName == "current_operations") { Program.Invoke(this, () => { if (sender is VM vm) { dataGridViewVms.Rows.Cast <VmPrecheckRow>() .FirstOrDefault(r => r.vm.opaque_ref == vm.opaque_ref)?.Refresh(); } }); } else if (args.PropertyName == "virtualisation_status" || args.PropertyName == "resident_on") { Rebuild(); } else if (args.PropertyName == "guest_metrics") { VM v = sender as VM; VM_guest_metrics gm = connection.Resolve(v?.guest_metrics); if (gm == null) { return; } gm.PropertyChanged -= gm_PropertyChanged; gm.PropertyChanged += gm_PropertyChanged; } }
protected override void Run() { // check the xstools sr is present, if not try and repair it foreach (SR sr in VM.Connection.Cache.SRs) { if (sr.IsToolsSR && sr.IsBroken()) { try { SrRepairAction action = new SrRepairAction(sr.Connection, sr, false); action.RunExternal(Session); } catch (Failure) { _xsToolsNotFound(); } } } // Check the version (if any) of the PV tools already on this host... VM_guest_metrics guestMetrics = Connection.Resolve(VM.guest_metrics); if (guestMetrics != null && !VM.HasNewVirtualisationStates && guestMetrics.PV_drivers_up_to_date) { this.Description = Messages.INSTALLTOOLS_EXIST; return; } // Check that the VM has a cd-rom... XenAPI.VBD cdrom = VM.FindVMCDROM(); if (cdrom == null) { Description = Messages.INSTALLTOOLS_COULDNOTFIND_CD; return; } // Find the tools ISO... XenAPI.VDI winIso = findWinISO(_searchHiddenIsOs); if (winIso == null) { // Could not find the windows PV drivers ISO. Description = Messages.INSTALLTOOLS_COULDNOTFIND_WIN; return; } Description = Messages.INSTALLTOOLS_STARTING; // Eject anything that's currently in the cd-rom... if (!cdrom.empty) { XenAPI.VBD.eject(Session, cdrom.opaque_ref); } // Insert the tools ISO... XenAPI.VBD.insert(Session, cdrom.opaque_ref, winIso.opaque_ref); // done(ish)... Description = Messages.INSTALLTOOLS_DONE; }
private void RegisterVMGuestMetrics(VM vm) { VM_guest_metrics guest_metrics = vm.Connection.Resolve(vm.guest_metrics); if (guest_metrics != null) { guest_metrics.PropertyChanged -= guest_metrics_PropertyChanged; guest_metrics.PropertyChanged += guest_metrics_PropertyChanged; } }
private void UnregisterVMHandlers(VM vm) { vm.PropertyChanged -= vm_PropertyChanged; vm.PropertyChanged -= vm_PropertyChanged_allVMs; VM_guest_metrics guest_metrics = vm.Connection.Resolve(vm.guest_metrics); if (guest_metrics != null) { guest_metrics.PropertyChanged -= guest_metrics_PropertyChanged; } }
private void DeregisterVmRowEvents(VmPrecheckRow row) { if (row.vm != null) { row.vm.PropertyChanged -= VM_PropertyChanged; VM_guest_metrics gm = connection.Resolve(row.vm.guest_metrics); if (gm == null) { return; } gm.PropertyChanged -= gm_PropertyChanged; } }
private void deregisterVMEvents() { //Deregister event handlers from these VMs foreach (VMListBoxItem vmlbi in vms.Values) { VM v = vmlbi.GetVM(); v.PropertyChanged -= new PropertyChangedEventHandler(VM_PropertyChanged); VM_guest_metrics gm = connection.Resolve(v.guest_metrics); if (gm == null) { return; } gm.PropertyChanged -= new PropertyChangedEventHandler(gm_PropertyChanged); } }
private void deregisterVMEvents() { //Deregister event handlers from these VMs foreach (var row in vms.Values) { VM v = row.vm; v.PropertyChanged -= VM_PropertyChanged; VM_guest_metrics gm = connection.Resolve(v.guest_metrics); if (gm == null) { return; } gm.PropertyChanged -= gm_PropertyChanged; } }
private void UnregisterEventListeners() { if (Source == null) { return; } Source.PropertyChanged -= new PropertyChangedEventHandler(VM_PropertyChanged); VM_guest_metrics guestMetrics = Source.Connection.Resolve <VM_guest_metrics>(Source.guest_metrics); if (guestMetrics == null) { return; } guestMetrics.PropertyChanged -= new PropertyChangedEventHandler(guestMetrics_PropertyChanged); }
private void DegregisterEventsOnXmo() { if (XenObject == null) { return; } XenObject.PropertyChanged -= Server_PropertyChanged; if (XenObject is VM) { VM vm = (VM)XenObject; VM_guest_metrics vmGuestMetrics = vm.Connection.Resolve(vm.guest_metrics); if (vmGuestMetrics != null) { vmGuestMetrics.PropertyChanged -= Server_PropertyChanged; } } }
public static string vmIPAddresses(VM vm) { VM_guest_metrics metrics = vm.Connection.Resolve(vm.guest_metrics); if (metrics == null) { return(Messages.HYPHEN); } List <string> addresses = new List <string>(metrics.networks.Values); if (addresses.Count > 0) { return(String.Join(", ", addresses.ToArray())); } else { return(Messages.HYPHEN); } }
public void GetVMParam(Session session, string VMName, string Parameter) { Logger NewLogObj = new Logger(); string LogFilePath = NewLogObj.GetLogFilePath(); NewLogObj.WriteLogFile(LogFilePath, "GetVMParam", "info"); NewLogObj.WriteLogFile(LogFilePath, "==============", "info"); NewLogObj.WriteLogFile(LogFilePath, "VMName " + VMName, "info"); List <XenRef <VM> > vmRefs = VM.get_all(session); foreach (XenRef <VM> vmRef in vmRefs) { VM vm = VM.get_record(session, vmRef); //if (string.Compare(VMName, vm.name_label) == 0) //{ NewLogObj.WriteLogFile(LogFilePath, "Required VM " + VMName + " found", "info"); XenRef <VM_guest_metrics> GuestMetrics = vm.guest_metrics; //GuestMetrics. //List<XenRef<Network>> NWRefs=XenAPI.Network.get_all(session); XenRef <VM_guest_metrics> gmsref = vm.guest_metrics; //VM_guest_metrics gms = VM_guest_metrics.get_record(session, gmsref); Dictionary <String, String> dict = null; dict = VM_guest_metrics.get_networks(session, gmsref); // dict = gms.networks; String vmIP = null; foreach (String keyStr in dict.Keys) { vmIP = (String)(dict[keyStr]); System.Console.WriteLine(vmIP); } // } System.Console.WriteLine("Name: {0}\nvCPUs: {1}\nDescription: {2}\n-", vm.name_label, vm.VCPUs_at_startup, vm.name_description); } }
private void VM_PropertyChanged(object sender, PropertyChangedEventArgs args) { if (args.PropertyName == "resident_on" || args.PropertyName == "allowed_operations" || args.PropertyName == "current_operations") { Program.Invoke(this, () => RefreshVM(sender as VM)); } else if (args.PropertyName == "virtualisation_status") { Program.Invoke(this, update); } else if (args.PropertyName == "guest_metrics") { VM v = sender as VM; VM_guest_metrics gm = connection.Resolve(v.guest_metrics); if (gm == null) { return; } gm.PropertyChanged -= new PropertyChangedEventHandler(gm_PropertyChanged); gm.PropertyChanged += new PropertyChangedEventHandler(gm_PropertyChanged); } }
private void ComposeVMData() { m_VMs = new List <VMInfo>(); var VMs = new List <XenAPI.VM>(Connection.Cache.VMs); VMs.Sort(); foreach (XenAPI.VM vm in VMs) { string OSinfo = vm.GetOSName(); string srInfo = ""; string MacInfo = ""; string running_on = Messages.HYPHEN; if (Cancelling) { throw new CancelledException(); } if (!vm.is_a_real_vm()) { PercentComplete = Convert.ToInt32((++itemIndex) * baseIndex / itemCount); continue; } ComparableList <ComparableAddress> addresses = new ComparableList <ComparableAddress>(); if (vm.guest_metrics != null && !string.IsNullOrEmpty(vm.guest_metrics.opaque_ref) && !(vm.guest_metrics.opaque_ref.ToLower().Contains("null"))) { VM_guest_metrics metrics = vm.Connection.Resolve(vm.guest_metrics); List <VIF> vifs = vm.Connection.ResolveAll(vm.VIFs); foreach (VIF vif in vifs) { MacInfo += vif.MAC + " "; foreach (var network in metrics.networks.Where(n => n.Key.StartsWith(String.Format("{0}/ip", vif.device)))) { ComparableAddress ipAddress; if (!ComparableAddress.TryParse(network.Value, false, true, out ipAddress)) { continue; } addresses.Add(ipAddress); } } } addresses = new ComparableList <ComparableAddress>(addresses.Distinct()); if (MacInfo.Length == 0) { MacInfo = Messages.HYPHEN; } foreach (XenRef <VBD> vbdRef in vm.VBDs) { var vbd = vm.Connection.Resolve(vbdRef); if (vbd != null && !vbd.IsCDROM() && !vbd.IsFloppyDrive() && vbd.bootable) { VDI vdi = vm.Connection.Resolve(vbd.VDI); srInfo += vdi.name_label + ":" + vdi.SizeText() + ";"; } } if (srInfo.Length == 0) { srInfo = Messages.HYPHEN; } if (vm.resident_on != null && !string.IsNullOrEmpty(vm.resident_on.opaque_ref) && !(vm.resident_on.opaque_ref.ToLower().Contains("null"))) { running_on = vm.Connection.Resolve(vm.resident_on).Name(); } string default_template_name = Messages.HYPHEN; if (vm.other_config.ContainsKey("base_template_name")) { default_template_name = vm.other_config["base_template_name"]; } VMInfo buf = new VMInfo(vm.Name(), vm.uuid, PropertyAccessorHelper.vmCpuUsageStringByMetric(vm, MetricUpdater), PropertyAccessorHelper.vmMemoryUsagePercentageStringByMetric(vm, MetricUpdater), srInfo, Convert.ToString(vm.VIFs.Count), Convert.ToString(addresses), MacInfo, OSinfo, Convert.ToString(vm.power_state), Convert.ToString(vm.RunningTime()), running_on, default_template_name, vm.Description()); m_VMs.Add(buf); PercentComplete = Convert.ToInt32((++itemIndex) * baseIndex / itemCount); } }
/// <summary> /// scan each ip address (from the guest agent) for an open port /// </summary> /// <param name="port"></param> public String PollPort(int port, bool vnc) { try { if (Source == null) { return(null); } VM vm = Source; XenRef <VM_guest_metrics> guestMetricsRef = vm.guest_metrics; if (guestMetricsRef == null || Helper.IsNullOrEmptyOpaqueRef(guestMetricsRef.opaque_ref)) { return(null); } VM_guest_metrics metrics = vm.Connection.Resolve(guestMetricsRef); if (metrics == null) { return(null); } Dictionary <string, string> networks = metrics.networks; if (networks == null) { return(null); } List <string> ipAddresses = new List <string>(); List <string> ipv6Addresses = new List <string>(); foreach (VIF vif in vm.Connection.ResolveAll(vm.VIFs)) { XenAPI.Network network = vif.Connection.Resolve(vif.network); XenAPI.Host host = vm.Connection.Resolve(vm.resident_on); XenAPI.PIF pif = Helpers.FindPIF(network, host); if (pif != null && pif.LinkStatus == PIF.LinkState.Connected) { foreach (var networkInfo in networks.Where(n => n.Key.StartsWith(String.Format("{0}/ip", vif.device)))) { if (networkInfo.Key.EndsWith("ip")) // IPv4 address { ipAddresses.Add(networkInfo.Value); } else { if (networkInfo.Key.Contains("ipv6")) // IPv6 address, enclose in square brackets { ipv6Addresses.Add(String.Format("[{0}]", networkInfo.Value)); } else { continue; } } } } } ipAddresses.AddRange(ipv6Addresses); // make sure IPv4 addresses are scanned first (CA-102755) foreach (String ipAddress in ipAddresses) { try { Log.DebugFormat("Poll port {0}:{1}", ipAddress, port); Stream s = connectGuest(ipAddress, port, vm.Connection); if (vnc) { Log.DebugFormat("Connected. Set Pending Vnc connection {0}:{1}", ipAddress, port); SetPendingVNCConnection(s); } else { s.Close(); } return(ipAddress); } catch (Exception exn) { Log.Debug(exn); } } } catch (WebException) { // xapi has gone away. } catch (IOException) { // xapi has gone away. } catch (Failure exn) { if (exn.ErrorDescription[0] == Failure.HANDLE_INVALID) { // HANDLE_INVALID is fine -- the guest metrics are not there yet. } else if (exn.ErrorDescription[0] == Failure.SESSION_INVALID) { // SESSION_INVALID is fine -- these will expire from time to time. // We need to invalidate the session though. lock (activeSessionLock) { activeSession = null; } } else { Log.Warn("Exception while polling VM for port " + port + ".", exn); } } catch (Exception e) { Log.Warn("Exception while polling VM for port " + port + ".", e); } return(null); }
/// <summary> /// scan each ip address (from the guest agent) for an open port /// </summary> /// <param name="port"></param> private String PollPort(int port, bool vnc) { try { Log.Debug("PollPort called"); if (m_sourceVM == null) { return(null); } VM vm = m_sourceVM; XenRef <VM_guest_metrics> guestMetricsRef = vm.guest_metrics; if (guestMetricsRef == null) { return(null); } VM_guest_metrics metrics = XenAPI.VM_guest_metrics.get_record(m_session, vm.guest_metrics); if (metrics == null) { return(null); } Dictionary <string, string> networks = metrics.networks; if (networks == null) { return(null); } List <String> ipAddresses = new List <String>(); foreach (String key in networks.Keys) { if (key.EndsWith("ip")) { ipAddresses.Add(networks[key]); } } foreach (String ipAddress in ipAddresses) { try { Stream s = connectGuest(ipAddress, port); if (vnc) { //SetPendingVNCConnection(s); } else { s.Close(); } return(ipAddress); } catch (Exception exn) { Log.Debug(exn); } } } catch (WebException) { // xapi has gone away. } catch (IOException) { // xapi has gone away. } catch (XenAPI.Failure exn) { if (exn.ErrorDescription[0] == HANDLE_INVALID) { // HANDLE_INVALID is fine -- the guest metrics are not there yet. } else if (exn.ErrorDescription[0] == SESSION_INVALID) { // SESSION_INVALID is fine -- these will expire from time to time. // We need to invalidate the session though. //lock (activeSessionLock) //{ m_session = null; //} } else { Log.Warn("Exception while polling VM for port " + port + ".", exn); } } catch (Exception e) { Log.Warn("Exception while polling VM for port " + port + ".", e); } return(null); }
private static ComparableList <ComparableAddress> IPAddressProperty(IXenObject o) { var addresses = new ComparableList <ComparableAddress>(); if (o.Connection == null) { return(addresses); } if (o is VM vm) { if (!vm.is_a_real_vm()) { return(addresses); } VM_guest_metrics metrics = vm.Connection.Resolve(vm.guest_metrics); if (metrics == null) { return(null); } List <VIF> vifs = vm.Connection.ResolveAll(vm.VIFs); foreach (VIF vif in vifs) { foreach (var value in Helpers.FindIpAddresses(metrics.networks, vif.device)) { if (ComparableAddress.TryParse(value, false, true, out var ipAddress)) { addresses.Add(ipAddress); } } } addresses = new ComparableList <ComparableAddress>(addresses.Distinct()); } else if (o is Host host) { foreach (PIF pif in host.Connection.ResolveAll(host.PIFs)) { if (ComparableAddress.TryParse(pif.IP, false, true, out var ipAddress)) { addresses.Add(ipAddress); } } } else if (o is SR sr) { string target = sr.Target(); if (!string.IsNullOrEmpty(target)) { if (ComparableAddress.TryParse(target, false, true, out var ipAddress)) { addresses.Add(ipAddress); } } } return(addresses.Count == 0 ? null : addresses); // CA-28300 }
private EnvelopeType _export(Session xenSession, string targetPath, string ovfname, string vmUuid) { EnvelopeType ovfEnv; try { auditLog.DebugFormat("Export: {0}, {1}", ovfname, targetPath); #region GET VM Reference XenRef <VM> vmRef = null; try { vmRef = VM.get_by_uuid(xenSession, vmUuid); } catch { log.WarnFormat("VM not found as uuid: {0}, trying as name-label", vmUuid); vmRef = null; } if (vmRef == null) { try { List <XenRef <VM> > vmRefs = VM.get_by_name_label(xenSession, vmUuid); vmRef = vmRefs[0]; traceLog.DebugFormat("{0} VM(s) found by label {1}", vmRefs.Count, vmUuid); if (vmRefs.Count > 1) { log.WarnFormat("Only exporting FIRST VM with name {0}", vmUuid); } } catch { log.ErrorFormat(Messages.ERROR_VM_NOT_FOUND, vmUuid); throw; } } #endregion VM vm = VM.get_record(xenSession, vmRef); if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended) { var message = string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name()); OnUpdate(new XenOvfTranportEventArgs(XenOvfTranportEventType.ExportProgress, "Export", message)); log.Info(message); throw new Exception(message); } #region CREATE ENVELOPE / ADD VIRTUAL SYSTEM ovfEnv = OVF.CreateEnvelope(ovfname); string vsId = OVF.AddVirtualSystem(ovfEnv, vm.name_label); string vhsId = OVF.AddVirtualHardwareSection(ovfEnv, vsId); #endregion #region TRY TO ID OS XenRef <VM_guest_metrics> vmgmRef = VM.get_guest_metrics(xenSession, vmRef); if (!vmgmRef.opaque_ref.ToUpper().Contains("NULL")) { VM_guest_metrics vmgm = VM_guest_metrics.get_record(xenSession, vmgmRef); //VM_metrics vmm = VM_metrics.get_record(xenSession, VM.get_metrics(xenSession, vmRef)); if (vmgm.os_version != null && vmgm.os_version.Count > 0) { foreach (string key in vmgm.os_version.Keys) { if (key.ToLower().Equals("name")) { ushort osid = ValueMaps.OperatingSystem(vmgm.os_version[key]); if (osid == 0xFFFF) { osid = 1; } // change to OTHER since search failed. string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO"); if (vmgm.os_version.ContainsKey("major") && vmgm.os_version.ContainsKey("minor")) { version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), vmgm.os_version["major"], vmgm.os_version["minor"]); } string osname = (vmgm.os_version[key].Split(new [] { '|' }))[0]; OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osname, version, osid); break; } } } } #endregion #region ADD VSSD // IS PV'd? for VirtualSystemType identification. string typeformat = @"{0}-{1}-{2}"; string vmtype = string.Format(typeformat, "hvm", "3.0", "unknown"); if (vm.HVM_boot_policy != null && vm.HVM_boot_policy == Properties.Settings.Default.xenBootOptions) { if (!string.IsNullOrEmpty(vm.domarch)) { vmtype = string.Format(typeformat, vm.domarch, "3.0", "unknown"); } } else { if (!string.IsNullOrEmpty(vm.domarch)) { vmtype = string.Format(typeformat, "xen", "3.0", vm.domarch); } else { vmtype = string.Format(typeformat, "xen", "3.0", "unknown"); } } OVF.AddVirtualSystemSettingData(ovfEnv, vsId, vhsId, vm.name_label, OVF.GetContentMessage("VSSD_CAPTION"), vm.name_description, Guid.NewGuid().ToString(), vmtype); #endregion #region ADD CPUS OVF.SetCPUs(ovfEnv, vsId, (ulong)vm.VCPUs_max); #endregion #region ADD MEMORY OVF.SetMemory(ovfEnv, vsId, (ulong)(vm.memory_dynamic_max / MB), "MB"); #endregion #region ADD NETWORKS List <XenRef <VIF> > vifs = VM.get_VIFs(xenSession, vmRef); foreach (XenRef <VIF> vifref in vifs) { VIF vif = VIF.get_record(xenSession, vifref); XenRef <Network> netRef = vif.network; Network net = Network.get_record(xenSession, netRef); // Why is the following call reference using name_label where other references use uuid? OVF.AddNetwork(ovfEnv, vsId, net.uuid, net.name_label, net.name_description, vif.MAC); } #endregion #region SET STARTUP OPTIONS OVF.AddStartupSection(ovfEnv, true, vsId, vm.order, vm.start_delay, vm.shutdown_delay); #endregion #region GET AND EXPORT DISKS using iSCSI List <XenRef <VBD> > vbdlist = VM.get_VBDs(xenSession, vmRef); _vdiRefs.Clear(); int diskIndex = 0; foreach (XenRef <VBD> vbdref in vbdlist) { VBD vbd = VBD.get_record(xenSession, vbdref); if (vbd.type == vbd_type.CD) { string rasdid = OVF.AddCDROM(ovfEnv, vsId, vbd.uuid, OVF.GetContentMessage("RASD_16_CAPTION"), OVF.GetContentMessage("RASD_16_DESCRIPTION")); OVF.SetTargetDeviceInRASD(ovfEnv, vsId, rasdid, vbd.userdevice); } else { try { XenRef <VDI> vdi = VBD.get_VDI(xenSession, vbdref); if (vdi != null && !string.IsNullOrEmpty(vdi.opaque_ref) && !(vdi.opaque_ref.ToLower().Contains("null"))) { _vdiRefs.Add(vdi); VDI lVdi = VDI.get_record(xenSession, vdi); string destinationFilename = Path.Combine(targetPath, string.Format(@"{0}.vhd", lVdi.uuid)); string diskid = Guid.NewGuid().ToString(); string diskName = lVdi.name_label; if (diskName == null) { diskName = string.Format("{0} {1}", OVF.GetContentMessage("RASD_19_CAPTION"), diskIndex); } OVF.AddDisk(ovfEnv, vsId, diskid, Path.GetFileName(destinationFilename), vbd.bootable, diskName, lVdi.name_description, (ulong)lVdi.physical_utilisation, (ulong)lVdi.virtual_size); OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskid, vbd.userdevice); diskIndex++; } } catch (Exception ex) { log.InfoFormat("Export: VBD Skipped: {0}: {1}", vbdref, ex.Message); } } } #endregion if (!MetaDataOnly) { _copydisks(ovfEnv, ovfname, targetPath); } #region ADD XEN SPECIFICS if (vm.HVM_boot_params != null) { Dictionary <string, string> _params = vm.HVM_boot_params; foreach (string key in _params.Keys) { if (key.ToLower().Equals("order")) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", _params[key], OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } } } if (!string.IsNullOrEmpty(vm.HVM_boot_policy)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_policy", vm.HVM_boot_policy, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2")); } if (vm.HVM_shadow_multiplier != 1.0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_shadow_multiplier", Convert.ToString(vm.HVM_shadow_multiplier), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.platform != null) { Dictionary <string, string> platform = vm.platform; StringBuilder sb = new StringBuilder(); foreach (string key in platform.Keys) { sb.AppendFormat(@"{0}={1};", key, platform[key]); } OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3")); } if (!string.IsNullOrEmpty(vm.PV_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_args", vm.PV_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_bootloader)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader", vm.PV_bootloader, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_bootloader_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader_args", vm.PV_bootloader_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_kernel)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_kernel", vm.PV_kernel, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_legacy_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_legacy_args", vm.PV_legacy_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_ramdisk)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_ramdisk", vm.PV_ramdisk, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.hardware_platform_version >= 0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.HasSriovRecommendation()) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "allow_network_sriov", bool.TrueString.ToLowerInvariant(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.has_vendor_device) { //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.VGPUs.Count != 0) { VGPU vgpu = VGPU.get_record(xenSession, vm.VGPUs[0]); if (vgpu != null) { var vgpuGroup = GPU_group.get_record(xenSession, vgpu.GPU_group); var vgpuType = VGPU_type.get_record(xenSession, vgpu.type); var sb = new StringBuilder(); sb.AppendFormat("GPU_types={{{0}}};", vgpuGroup.GPU_types == null || vgpuGroup.GPU_types.Length < 1 ? "" : string.Join(";", vgpuGroup.GPU_types)); sb.AppendFormat("VGPU_type_vendor_name={0};", vgpuType.vendor_name ?? ""); sb.AppendFormat("VGPU_type_model_name={0};", vgpuType.model_name ?? ""); OVF.AddOtherSystemSettingData(ovfEnv, vsId, "vgpu", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_4")); } } string pvsSiteUuid = string.Empty; var allProxies = xenSession.Connection.Cache.PVS_proxies; foreach (var p in allProxies.Where(p => p != null && p.VIF != null)) { var vif = xenSession.Connection.Resolve(p.VIF); if (vif != null) { var vmFromVif = xenSession.Connection.Resolve(vif.VM); if (vmFromVif != null && vmFromVif.uuid == vm.uuid) { var pvsSite = xenSession.Connection.Resolve(p.site); if (pvsSite != null) { pvsSiteUuid = pvsSite.uuid; } break; } } } if (!string.IsNullOrEmpty(pvsSiteUuid)) { var sb = new StringBuilder(); sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid)); OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5")); } #endregion OVF.FinalizeEnvelope(ovfEnv); } catch (Exception ex) { if (ex is OperationCanceledException) { throw; } log.Error(Messages.ERROR_EXPORT_FAILED); throw new Exception(Messages.ERROR_EXPORT_FAILED, ex); } return(ovfEnv); }
public int GetVMIP(string ServerIP, string username, string password, string VMNameLabel, int Timer) { Logger NewLogObj = new Logger(); string LogFilePath = NewLogObj.GetLogFilePath(); FileOperations FileObj = new FileOperations(); string hostname = ServerIP; int port = 80; // default int ExceptionHandlingnotReqdFlag = 0; try { Session session = new Session(hostname, port); session.login_with_password(username, password, API_Version.API_1_3); //MessageBox.Show("Conection Successfully Estabilished to the XenServer: " +Connection_XS_IP +""); List <XenRef <VM> > vmRefs = VM.get_all(session); StartSearch: foreach (XenRef <VM> vmRef in vmRefs) { //http://forums.citrix.com/thread.jspa?threadID=244784 VM vm = VM.get_record(session, vmRef); if (!vm.is_a_template && !vm.is_control_domain && !vm.is_a_snapshot && !vm.is_snapshot_from_vmpp) { //System.Console.Write("\nVM Name: {0} -> IP Address: ", vm.name_label); if (string.Compare(vm.name_label, VMNameLabel) == 0) { try { NewLogObj.WriteLogFile(LogFilePath, VMNameLabel + " found. Fetching records", "info"); bool dict_key = true; int WaitTimeout = 2400000; //40 mins //Wait till VM starts running while (!(string.Compare(vm.power_state.ToString(), "Running") == 0) && Timer < WaitTimeout) { System.Console.WriteLine("Waiting for VM " + VMNameLabel + " to poweron"); Thread.Sleep(1000); Timer = Timer + 1000; goto StartSearch; } if (!(string.Compare(vm.power_state.ToString(), "Running") == 0) && Timer >= WaitTimeout) { System.Console.WriteLine("Timeout waiting for VM " + VMNameLabel + " to poweron."); NewLogObj.WriteLogFile(LogFilePath, "Timeout waiting for VM " + VMNameLabel + " to poweron.", "fail"); return(-1); } while (dict_key == true && Timer < WaitTimeout) { try { int IPFound = 0; XenRef <VM_guest_metrics> gmsref = vm.guest_metrics; VM_guest_metrics gms = VM_guest_metrics.get_record(session, gmsref); Dictionary <String, String> dict = null; dict = gms.networks; String vmIP = null; foreach (String keyStr in dict.Keys) { dict_key = false; vmIP = (String)(dict[keyStr]); //excluding IPv6 address which contains the character : if (!vmIP.Contains(':')) { if (!vmIP.StartsWith("169")) { System.Console.WriteLine(vmIP); NewLogObj.WriteLogFile(LogFilePath, "IP address obtained for VM " + VMNameLabel + " is " + vmIP, "info"); IPFound = 1; return(1); } } } //for each keyStr if (dict_key == false || IPFound == 0) { System.Console.WriteLine("No valid IP addressfound for " + VMNameLabel); NewLogObj.WriteLogFile(LogFilePath, "No valid IP addressfound for " + VMNameLabel, "fail"); ExceptionHandlingnotReqdFlag = 1; return(-1); } } catch (Exception e) { //To avoid reduntant calls to function if (ExceptionHandlingnotReqdFlag == 1) { return(-1); } else { //System.Console.WriteLine(e.ToString() + " Waiting .."); System.Console.WriteLine(" Waiting for VM " + VMNameLabel + "to aquire IP address.."); Thread.Sleep(1000); Timer = Timer + 1000; goto StartSearch; //GetVMIP(ServerIP, username, password, VMNameLabel, Timer); } } } if (dict_key == true && Timer > WaitTimeout) { NewLogObj.WriteLogFile(LogFilePath, "Timeout waiting for the VM " + VMNameLabel + " to obtain IP address", "fail"); FileObj.ExitTestEnvironment(); return(-1); } } //try loop catch (Exception e) { System.Console.WriteLine(e.ToString()); return(-1); } } } //check and allow only VMs there by excluding templates/controldomain/snapshots/etc... } //For each... } // try to connect XenServer host. catch (Exception e1) { string exceptionText = "Server \"" + hostname + "\" cannot be contacted." + "\n\nError: " + e1.ToString(); System.Console.WriteLine(exceptionText); } //System.Console.WriteLine("Press a key to continue..."); //System.Console.ReadLine(); return(-1); }
private EnvelopeType Export(string targetDir, VM vm, Action <float> updatePercentage) { if (vm.power_state != vm_power_state.Halted && vm.power_state != vm_power_state.Suspended) { log.Error($"Cannot export VM {vm.Name()} ({vm.opaque_ref}); it is neither halted nor suspended."); throw new Exception(string.Format(Messages.ERROR_VM_NOT_HALTED, vm.Name())); } log.Info($"Exporting metadata for {vm.name_label}..."); #region CREATE ENVELOPE / ADD VIRTUAL SYSTEM EnvelopeType ovfEnv = OVF.CreateEnvelope(m_applianceFileName); string vsId = OVF.AddVirtualSystem(ovfEnv, vm.name_label); string vhsId = OVF.AddVirtualHardwareSection(ovfEnv, vsId); #endregion #region TRY TO ID OS VM_guest_metrics vmgm = Connection.Resolve(vm.guest_metrics); if (vmgm?.os_version != null && vmgm.os_version.TryGetValue("name", out string osName)) { ushort osId = ValueMaps.OperatingSystem(osName); if (osId == 0xFFFF) { osId = 1; // change to OTHER since search failed. } string version = OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_INFO"); if (vmgm.os_version.TryGetValue("major", out string major) && vmgm.os_version.TryGetValue("minor", out string minor)) { version = string.Format(OVF.GetContentMessage("SECTION_OPERATINGSYSTEM_VERSION"), major, minor); } string[] osNameParts = osName.Split('|'); if (osNameParts.Length > 0) { OVF.UpdateOperatingSystemSection(ovfEnv, vsId, osNameParts[0], version, osId); } } #endregion #region ADD VirtualSystemType identification var pv = vm.IsHVM() ? "hvm" : "xen"; var arch = string.IsNullOrEmpty(vm.domarch) ? "unknown" : vm.domarch; var vmType = string.Format("{0}-3.0-{1}", pv, arch); OVF.AddVirtualSystemSettingData(ovfEnv, vsId, vhsId, vm.name_label, OVF.GetContentMessage("VSSD_CAPTION"), vm.name_description, Guid.NewGuid().ToString(), vmType); #endregion #region ADD CPUS OVF.SetCPUs(ovfEnv, vsId, (ulong)vm.VCPUs_max); #endregion #region ADD MEMORY OVF.SetMemory(ovfEnv, vsId, (ulong)(vm.memory_dynamic_max / Util.BINARY_MEGA), "MB"); #endregion #region ADD NETWORKS foreach (XenRef <VIF> vifRef in vm.VIFs) { VIF vif = Connection.Resolve(vifRef); if (vif == null) { continue; } XenAPI.Network net = Connection.Resolve(vif.network); if (net == null) { continue; } OVF.AddNetwork(ovfEnv, vsId, net.uuid, net.name_label, net.name_description, vif.MAC); } #endregion #region SET STARTUP OPTIONS OVF.AddStartupSection(ovfEnv, true, vsId, vm.order, vm.start_delay, vm.shutdown_delay); #endregion #region EXPORT DISKS int diskIndex = 0; var vbdRefs = vm.VBDs; for (int i = 0; i < vbdRefs.Count; i++) { int curVbd = i; XenRef <VBD> vbdRef = vbdRefs[i]; VBD vbd = Connection.Resolve(vbdRef); if (vbd == null) { continue; } if (vbd.type == vbd_type.CD) { string rasdid = OVF.AddCDROM(ovfEnv, vsId, vbd.uuid, OVF.GetContentMessage("RASD_16_CAPTION"), OVF.GetContentMessage("RASD_16_DESCRIPTION")); OVF.SetTargetDeviceInRASD(ovfEnv, vsId, rasdid, vbd.userdevice); continue; } VDI vdi = Connection.Resolve(vbd.VDI); if (vdi == null) { continue; } try { var diskFilename = $"{vdi.uuid}.vhd"; var diskPath = Path.Combine(targetDir, diskFilename); if (File.Exists(diskPath)) { var oldFileName = diskFilename; diskFilename = $"{vdi.uuid}_{Thread.CurrentThread.ManagedThreadId}.vhd"; diskPath = Path.Combine(targetDir, diskFilename); log.InfoFormat("VHD Name collision, renamed {0} to {1}", oldFileName, diskFilename); } string diskName = vdi.name_label; if (string.IsNullOrEmpty(diskName)) { diskName = $"{OVF.GetContentMessage("RASD_19_CAPTION")} {diskIndex}"; } if (!MetaDataOnly) { log.Info($"Exporting disk {diskName} to {diskFilename} for {vm.name_label}..."); var taskRef = Task.create(Connection.Session, "export_raw_vdi_task", $"Exporting VDI {vdi.uuid} to {diskFilename}"); HTTP_actions.get_export_raw_vdi(b => { Description = string.Format(Messages.EXPORTING_VDI, diskName, diskFilename, Util.DiskSizeString(b, 2, "F2"), Util.DiskSizeString(vdi.virtual_size)); updatePercentage((curVbd + (float)b / vdi.virtual_size) / vbdRefs.Count); }, () => Cancelling, XenAdminConfigManager.Provider.GetProxyTimeout(true), Connection.Hostname, XenAdminConfigManager.Provider.GetProxyFromSettings(Connection), diskPath, taskRef, Connection.Session.opaque_ref, vdi.uuid, "vhd"); if (m_shouldVerify) { Description = string.Format(Messages.EXPORTING_VDI_VERIFICATION, diskFilename); using (var stream = new FileStream(diskPath, FileMode.Open, FileAccess.Read)) using (var sw = new StringWriter()) { var vhdChecker = new FileChecker(stream); var result = vhdChecker.Check(sw, ReportLevels.All); log.InfoFormat("Verifying disk {0}:\n{1}", diskFilename, sw.ToString().Replace("\0", "")); if (!result) { throw new Exception(string.Format(Messages.EXPORTING_VDI_VERIFICATION_FAILURE, diskFilename)); } } } } string diskId = Guid.NewGuid().ToString(); OVF.AddDisk(ovfEnv, vsId, diskId, diskFilename, vbd.bootable, diskName, vdi.name_description, (ulong)vdi.physical_utilisation, (ulong)vdi.virtual_size); OVF.SetTargetDeviceInRASD(ovfEnv, vsId, diskId, vbd.userdevice); diskIndex++; } catch (HTTP.CancelledException) { throw new CancelledException(); } } #endregion #region ADD XEN SPECIFICS var _params = vm.HVM_boot_params; if (_params != null && _params.Count > 0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_params", string.Join(";", _params.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_6")); } if (!string.IsNullOrEmpty(vm.HVM_boot_policy)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_boot_policy", vm.HVM_boot_policy, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_2")); } if (vm.HVM_shadow_multiplier != 1.0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "HVM_shadow_multiplier", Convert.ToString(vm.HVM_shadow_multiplier), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } var platform = vm.platform; if (platform != null && platform.Count > 0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "platform", string.Join(";", platform.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_3")); } var nvram = vm.NVRAM; if (nvram != null && nvram.Count > 0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "NVRAM", string.Join(";", nvram.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_7")); } if (!string.IsNullOrEmpty(vm.PV_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_args", vm.PV_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_bootloader)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader", vm.PV_bootloader, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_bootloader_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_bootloader_args", vm.PV_bootloader_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_kernel)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_kernel", vm.PV_kernel, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_legacy_args)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_legacy_args", vm.PV_legacy_args, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.PV_ramdisk)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "PV_ramdisk", vm.PV_ramdisk, OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.hardware_platform_version >= 0) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "hardware_platform_version", vm.hardware_platform_version.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (!string.IsNullOrEmpty(vm.recommendations)) { OVF.AddOtherSystemSettingData(ovfEnv, vsId, "recommendations", vm.recommendations.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } if (vm.has_vendor_device) { //serialise it with a different name to avoid it being deserialised automatically and getting the wrong type OVF.AddOtherSystemSettingData(ovfEnv, vsId, "VM_has_vendor_device", vm.has_vendor_device.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_1")); } foreach (XenRef <VGPU> gpuRef in vm.VGPUs) { VGPU vgpu = Connection.Resolve(gpuRef); if (vgpu != null) { var vgpuGroup = Connection.Resolve(vgpu.GPU_group); var vgpuType = Connection.Resolve(vgpu.type); var sb = new StringBuilder(); sb.AppendFormat("GPU_types={{{0}}};", vgpuGroup?.GPU_types == null || vgpuGroup.GPU_types.Length < 1 ? "" : string.Join(";", vgpuGroup.GPU_types)); sb.AppendFormat("VGPU_type_vendor_name={0};", vgpuType?.vendor_name ?? ""); sb.AppendFormat("VGPU_type_model_name={0};", vgpuType?.model_name ?? ""); OVF.AddOtherSystemSettingData(ovfEnv, vsId, "vgpu", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_4"), true); } } string pvsSiteUuid = string.Empty; var allProxies = Connection.Cache.PVS_proxies; foreach (var p in allProxies.Where(p => p != null && p.VIF != null)) { var vif = Connection.Resolve(p.VIF); if (vif != null) { var vmFromVif = Connection.Resolve(vif.VM); if (vmFromVif != null && vmFromVif.uuid == vm.uuid) { var pvsSite = Connection.Resolve(p.site); if (pvsSite != null) { pvsSiteUuid = pvsSite.uuid; } break; } } } if (!string.IsNullOrEmpty(pvsSiteUuid)) { var sb = new StringBuilder(); sb.AppendFormat("PVS_SITE={{{0}}};", string.Format("uuid={0}", pvsSiteUuid)); OVF.AddOtherSystemSettingData(ovfEnv, vsId, "pvssite", sb.ToString(), OVF.GetContentMessage("OTHER_SYSTEM_SETTING_DESCRIPTION_5")); } #endregion OVF.FinalizeEnvelope(ovfEnv); return(ovfEnv); }
protected override void TestCore() { // Choose a linux VM at random which is not a template or control domain and which is currently switched off. var vmRecords = VM.get_all_records(_session); var vmRef = (from KeyValuePair <XenRef <VM>, VM> kvp in vmRecords let theVm = kvp.Value where !theVm.is_a_template && !theVm.is_control_domain && !theVm.name_label.ToLower().Contains("windows") && theVm.power_state == vm_power_state.Halted select kvp.Key).FirstOrDefault(); if (vmRef == null) { var msg = "Cannot find a halted linux VM. Please create one."; _logger.Log(msg); throw new Exception(msg); } //to avoid playing with existing data, clone the VM and powercycle its clone VM vm = VM.get_record(_session, vmRef); _logger.Log("Cloning VM '{0}'...", vm.name_label); string cloneVmRef = VM.clone(_session, vmRef, string.Format("Cloned VM (from '{0}')", vm.name_label)); _logger.Log("Cloned VM; new VM's ref is {0}", cloneVmRef); VM.set_name_description(_session, cloneVmRef, "Another cloned VM"); VM cloneVm = VM.get_record(_session, cloneVmRef); _logger.Log("Clone VM's Name: {0}, Description: {1}, Power State: {2}", cloneVm.name_label, cloneVm.name_description, cloneVm.power_state); _logger.Log("Starting VM in paused state..."); VM.start(_session, cloneVmRef, true, true); _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef)); _logger.Log("Unpausing VM..."); VM.unpause(_session, cloneVmRef); _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef)); // here we need to delay for a bit until the suspend feauture is written // in the guest metrics; this check should be enough for most guests; // let's try a certain number of times with sleeps of a few seconds inbetween int max = 20; int delay = 10; for (int i = 0; i < max; i++) { cloneVm = VM.get_record(_session, cloneVmRef); var metrics = VM_guest_metrics.get_record(_session, cloneVm.guest_metrics); if (metrics.other.ContainsKey("feature-suspend") && metrics.other["feature-suspend"] == "1") { break; } _logger.Log("Checked for feature-suspend count {0} out of {1}; will re-try in {2}sec.", i + 1, max, delay); Thread.Sleep(delay * 1000); } _logger.Log("Suspending VM..."); VM.suspend(_session, cloneVmRef); _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef)); _logger.Log("Resuming VM..."); VM.resume(_session, cloneVmRef, false, true); _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef)); _logger.Log("Forcing shutdown VM..."); VM.hard_shutdown(_session, cloneVmRef); _logger.Log("VM Power State: {0}", VM.get_power_state(_session, cloneVmRef)); cloneVm = VM.get_record(_session, cloneVmRef); var vdis = (from vbd in cloneVm.VBDs let vdi = VBD.get_VDI(_session, vbd) where vdi.opaque_ref != "OpaqueRef:NULL" select vdi).ToList(); _logger.Log("Destroying VM..."); VM.destroy(_session, cloneVmRef); _logger.Log("Destroying VM's disks..."); foreach (var vdi in vdis) { VDI.destroy(_session, vdi); } _logger.Log("VM destroyed."); }
public void BuildList() { Program.AssertOnEventThread(); if (!this.Visible) { return; } if (InBuildList) { return; } InBuildList = true; try { if (XenObject == null || XenObject.Locked) { return; } if (!XenObject.Connection.CacheIsPopulated) { return; } if (XenObject is VM) { DeregisterEventsOnGridRows(); VIF selectedVIF = SelectedVif; VM vm = XenObject as VM; NetworksGridView.SuspendLayout(); NetworksGridView.Rows.Clear(); List <VIF> vifs = vm.Connection.ResolveAll(vm.VIFs); vifs.Sort(); // CA-8981 - Listen for guest metric changes which is necessary for IP Address updates VM_guest_metrics vmGuestMetrics = vm.Connection.Resolve(vm.guest_metrics); if (vmGuestMetrics != null) { vmGuestMetrics.PropertyChanged += Server_PropertyChanged; } var vifRowsToAdd = new List <VifRow>(); foreach (var vif in vifs) { var network = vif.Connection.Resolve(vif.network); if (network != null && // CA-218956 - Expose HIMN when showing hidden objects (network.IsGuestInstallerNetwork() && !XenAdmin.Properties.Settings.Default.ShowHiddenVMs)) { continue; // Don't show the guest installer network in the network tab (CA-73056) } vifRowsToAdd.Add(new VifRow(vif)); } NetworksGridView.Rows.AddRange(vifRowsToAdd.ToArray()); bool selected = true; if (selectedVIF != null) { foreach (VifRow row in NetworksGridView.Rows) { // Cannot compare opaque_ref as VIFs get destroyed / recreated on each edit. if (row.Vif.device == selectedVIF.device) { row.Selected = true; break; } } } if (!selected && NetworksGridView.Rows.Count > 0) { NetworksGridView.Rows[0].Selected = true; } } else if (XenObject is Host || XenObject is Pool) { DeregisterEventsOnGridRows(); XenAPI.Network selectedNetwork = SelectedNetwork; NetworksGridView.SuspendLayout(); NetworksGridView.Rows.Clear(); XenAPI.Network[] networks = XenObject.Connection.Cache.Networks; Array.Sort <XenAPI.Network>(networks); List <NetworkRow> networkRowsToAdd = new List <NetworkRow>(); for (int i = 0; i < networks.Length; i++) { if (!networks[i].Show(XenAdmin.Properties.Settings.Default.ShowHiddenVMs)) { continue; } networkRowsToAdd.Add(new NetworkRow(networks[i], XenObject)); } NetworksGridView.Rows.AddRange(networkRowsToAdd.ToArray()); // The following update causes this to be a lot slower with many networks. Alot! CA-43944 //foreach(NetworkRow r in NetworksGridView.Rows) //r.UpdateDefaultCellStyle(); // Has to be done again after adding to the grid view, even though it's already called in the constructor if (selectedNetwork != null) { foreach (NetworkRow row in NetworksGridView.Rows) { if (row.Network.opaque_ref == selectedNetwork.opaque_ref && selectedNetwork.Show(XenAdmin.Properties.Settings.Default.ShowHiddenVMs)) { row.Selected = true; break; } } } } } finally { if (NetworksGridView.SortedColumn != null) { NetworksGridView.Sort( NetworksGridView.SortedColumn, NetworksGridView.SortOrder == SortOrder.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending); } NetworksGridView.ResumeLayout(); InBuildList = false; } }
public Object vmcollect(Session session, List <XenRef <VM> > vmRefs) { ArrayList vmc = new ArrayList(); string mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); int vme = 1; string log; string entry; try { int vmcount = 0; foreach (XenRef <VM> vmRef in vmRefs) { VM vm = VM.get_record(session, vmRef); string tempdecr = vm.name_description; //do not list templates or controller domain if (!vm.is_a_template && !vm.is_control_domain) { vmcount = vmcount + 1; vmc.Add("Virtual Machine Name:"); try { vmc.Add(Convert.ToString(vm.name_label)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Decription:"); try { vmc.Add(Convert.ToString(vm.name_description)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("VM Power State:"); try { vmc.Add(Convert.ToString(vm.power_state)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Amount of VCPUs:"); try { vmc.Add("Not displayed in demo version"); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Max Amount of Memory:"); try { long maxmem = vm.memory_static_max; maxmem = maxmem / 1048576; vmc.Add("Not displayed in demo version"); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Min Amount of Memory:"); try { long minmem = vm.memory_static_min; minmem = minmem / 1048576; vmc.Add(Convert.ToString(minmem)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } VM_metrics ms = VM_metrics.get_record(session, vm.metrics); vmc.Add("Date of install:"); try { vmc.Add(Convert.ToString(ms.install_time)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Startup time:"); try { vmc.Add(Convert.ToString(ms.start_time)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } vmc.Add("Time of last shutdown:"); try { vmc.Add(Convert.ToString(vm.other_config["last_shutdown_time"])); } catch { vmc.Add("Never Shutdown"); } vmc.Add("Reason for Shutdown:"); try { vmc.Add(vm.other_config["last_shutdown_reason"]); } catch { vmc.Add("Never Shutdown"); } vmc.Add("UUID"); try { vmc.Add(vm.uuid); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } if (vm.guest_metrics.ServerOpaqueRef == "OpaqueRef:NULL") { } else { VM_guest_metrics xms = VM_guest_metrics.get_record(session, vm.guest_metrics); vmc.Add("OS version and System disk: "); try { vmc.Add("Not displayed in demo version"); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } } VM vmRecord = VM.get_record(session, vmRef); if (vmRecord.guest_metrics == "OpaqueRef:NULL") { } else { XenRef <VM_guest_metrics> gmsref = vmRecord.guest_metrics; VM_guest_metrics gms = VM_guest_metrics.get_record(session, gmsref); Dictionary <String, String> dict = null; dict = gms.networks; String vmIP = null; if (dict.Count >= 1) { vmc.Add("Number of Xentools Visible VIFs:"); try { vmc.Add(Convert.ToString(dict.Count)); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } foreach (String keyStr in dict.Keys) { vmc.Add("IP Address:"); try { vmIP = (String)(dict[keyStr]); vmc.Add("Not displayed in demo version"); } catch { vmc.Add("Data not available"); log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Error " + vme; writelog.entry(log, entry); vme++; } } } } } vme = 1; } log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Finished "; writelog.entry(log, entry); } catch { log = mydocs + "\\Halfmode\\HalfmodeConnection.log"; entry = DateTime.Now.ToString("HH:mm:ss") + " VM Collection Failed "; writelog.entry(log, entry); } if ((vmc.Count & 2) == 0) { } else { vmc.Add(" "); } return(vmc); }